Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const db = require('./db');
- const bodyParser = require('body-parser');
- const app = express();
- const jsonParser = bodyParser.json({ extended: false });
- const PORT = 4000;
- //Generate a key within stupid&simple algorithm
- function keyGen() {
- return Math.floor(Math.random() * (4 - 1)) + 1; //returning a random (расширить генерацию с применением MD5)
- // value from 1 to 3
- }
- //killing a key after 1 minute pass(setting it to NULL)
- function killKey() {
- return db.models.users.findAll().then((rows) => {
- let promises = [];
- for (let i in rows) {
- console.log('hello');
- let difference = new Date().getTime() - rows[i].dataValues.updatedAt.getTime(); // unixtime
- if(difference > 60 * 1000) { //if diff more than 1 min setting key to NULL
- promises.push(rows[i].update({
- key: null
- }));
- }
- }
- return Promise.all(promises); // ждём завершения всех промисов
- });
- }
- app.use('/auth',jsonParser,function (req, res, next) {
- killKey(); // killing a keys
- let clientKey;
- if (!req.headers.cookie) {
- clientKey = null;
- } else {
- clientKey = req.headers.cookie; // TODO: fix it (parse cookies)
- }
- return db.models.users.findOne({
- where: {
- login: req.body.login,
- password: req.body.password,
- key: clientKey
- }
- }).then(row => {
- if (row === null) {
- res.send('session expired relog in please');
- } else {
- next();
- }
- });
- });
- app.route('/auth')
- .post(jsonParser, (req,res) => {
- return db.models.users.findUser(req.body.login, req.body.password)
- .then(user => {
- if (user !== null) { // logged correct
- if (!req.headers.cookie) { // if the req has no key server send it within the object
- let key;
- key = keyGen();
- return user.update({
- key // fixed (shorter)
- });
- } else {
- throw new Error('key is valid, u re authorized')
- }
- } else { //no comb like this
- throw new Error('No such user with login and password');
- }
- }).then(() => {
- return db.models.users.findUser(req.body.login, req.body.password);
- }).then(user => {
- res.json(user.dataValues);//sending the obj with the new key to the client
- }).catch(e => res.status(500).send(e.msg));
- });
- app.route('/reg')
- .post(jsonParser, (req,res) => {
- return db.models.users.findUser(req.body.login, req.body.password).then(user => {
- if (user === null) {
- return db.models.users.regUser(req.body.login, req.body.login).then(() => { // fix promise chaining
- res.send('registred successfully');
- });
- } else {
- res.send('this log&pass combination is already exist');
- }
- });
- });
- app.listen(PORT, '127.0.0.1', (err) => {
- if(err) {
- console.error(err.message);
- } else {
- console.log('listening to port ' + PORT);
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement