opt-cc/api/routes/authenticate.js

168 lines
4.5 KiB
JavaScript
Raw Normal View History

2017-05-10 11:04:06 +02:00
"use strict";
// modules
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const Q = require('q');
const _ = require('lodash');
const logger = require('debug')('cc:authenticate');
2017-06-08 16:03:20 +02:00
const apiAuthenticationMiddleware = require('../middleware/auth-middleware');
const checkAdmin = require('../middleware/permission-check').checkAdmin;
2017-05-10 11:04:06 +02:00
// HTTP status codes by name
const codes = require('./http-codes');
const config = require('../config/config');
2017-05-10 11:04:06 +02:00
const routerHandling = require('../middleware/router-handling');
const AppUserModel = require('../models/app-user');
const authenticate = express.Router();
// routes **********************
authenticate.route('/')
.post((req, res, next) => {
authCheck(req.body.username, req.body.password)
.then((user) => {
if (user) {
// authentication successful
res.send(user);
} else {
// authentication failed
2017-05-11 15:14:57 +02:00
res.status(codes.unauthorized).send('Username or password is incorrect');
2017-05-10 11:04:06 +02:00
}
})
.catch((err) => {
2017-05-11 15:14:57 +02:00
res.status(codes.wrongrequest).send(err);
2017-05-10 11:04:06 +02:00
});
})
.all(
routerHandling.httpMethodNotAllowed
);
let authCheck = (username, password) => {
const deferred = Q.defer();
AppUserModel.findOne({username: username}, (err, user) => {
if (err) deferred.reject(err.name + ': ' + err.message);
2017-05-11 15:14:57 +02:00
const diff = 3 * 60 * 24; // time till expiration [minutes]
2017-05-10 11:04:06 +02:00
2017-06-08 16:03:20 +02:00
if (user && user.activated && bcrypt.compareSync(password, user.password)) {
2017-05-10 11:04:06 +02:00
// authentication successful
deferred.resolve({
_id: user._id,
username: user.username,
2017-06-08 16:03:20 +02:00
permission: user.permission,
2017-05-10 11:04:06 +02:00
token: jwt.sign({sub: user._id}, config.secret, {expiresIn: diff * 60}),
tokenExpireDate: new Date(Date.now().valueOf() + diff * 60000 - 1000)
});
} else {
// authentication failed
deferred.resolve();
}
});
return deferred.promise;
};
2017-06-08 16:03:20 +02:00
// ******************************** EDITING USING ADMIN PANEL ************************
authenticate.route('/editUser/:id')
.patch(apiAuthenticationMiddleware, checkAdmin, (req, res, next) => {
if (!req.body || (req.body._id && req.body._id !== req.params.id)) {
// little bit different as in PUT. :id does not need to be in data, but if the _id and url id must match
const err = new Error('id of PATCH resource and send JSON body are not equal ' + req.params.id + " " + req.body._id);
err.status = codes.notfound;
next(err);
return; // prevent node to process this function further after next() has finished.
}
// increment version manually as we do not use .save(.)
req.body.updatedAt = new Date();
req.body.$inc = {__v: 1};
// PATCH is easier with mongoose than PUT. You simply update by all data that comes from outside. no need to reset attributes that are missing.
AppUserModel.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, item) => {
if (err) {
err.status = codes.wrongrequest;
}
else if (!item) {
err = new Error("appUser not found");
err.status = codes.notfound;
}
else {
res.locals.items = item;
}
next(err);
})
})
.all(
routerHandling.httpMethodNotAllowed
);
// ******************************** SIGNUP ************************
authenticate.route('/signup')
.post((req, res, next) => {
create(req.body)
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
res.status(400).send(err);
});
})
.all(
routerHandling.httpMethodNotAllowed
);
let create = (userParam) => {
const deferred = Q.defer();
// validation
AppUserModel.findOne(
{username: userParam.username},
(err, user) => {
if (err) deferred.reject(err.name + ': ' + err.message);
if (user) {
// username already exists
deferred.reject('Username "' + userParam.username + '" is already taken');
} else {
createUser();
}
});
let createUser = () => {
// set user object to userParam without the cleartext password
const user = _.omit(userParam, 'password');
// add hashed password to user object
user.password = bcrypt.hashSync(userParam.password, 10);
const newUser = new AppUserModel(user);
newUser.save((err, doc) => {
if (err) deferred.reject(err.name + ': ' + err.message);
deferred.resolve();
});
};
return deferred.promise;
};
2017-05-10 11:04:06 +02:00
authenticate.use(routerHandling.emptyResponse);
module.exports = authenticate;