{"size": 1925, "ext": "js", "max_stars_repo_path": "Cross Platform Apps/server for course project/server/app/utils/auth.js", "max_stars_repo_name": "apletea/MMF_Labs", "max_stars_repo_stars_event_min_datetime": "2017-08-06T15:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T08:11:39.000Z", "max_issues_repo_path": "Cross Platform Apps/server for course project/server/app/utils/auth.js", "max_issues_repo_name": "apletea/MMF_Java_Labs", "max_issues_repo_issues_event_min_datetime": "2017-11-04T13:56:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-04T13:56:10.000Z", "max_forks_repo_path": "Cross Platform Apps/server for course project/server/app/utils/auth.js", "max_forks_repo_name": "apletea/MMF_Java_Labs", "max_forks_repo_forks_event_min_datetime": "2018-05-30T13:56:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-30T13:56:38.000Z"}
{"max_stars_count": 6, "max_issues_count": 1, "max_forks_count": 1, "avg_line_length": 23.4756097561, "max_line_length": 132, "alphanum_fraction": 0.665974026}
'use strict';

let bcrypt = require('bcrypt'),
	jwt = require('jwt-simple'),
	request = require('request'),
	md5 = require('md5'),
	secretOrKey = require('../config').secretOrKey;

const compose = require('composable-middleware');
const errorUtil = require('./errors');
const responseUtil = require('./response');
const userConst = require('../constants/userConstants');

let comparePassword = (password, hash, cb) => {
	bcrypt.compare(password, hash.replace(), (err, isMatch) => {
		if (err)
			return cb(err);
		cb(null, isMatch);
	});
};

let hashPassword = (pass, cb) => {
	bcrypt.genSalt(10, (err, salt) => {

		if (err)
			return cb(err);

		bcrypt.hash(pass, salt, (err, hash) => {
			if (err)
				return cb(err);

			cb(null, hash);
		});
	});
};

let getJwtToken = user => {
	return `JWT ${jwt.encode(user, secretOrKey)}`;
};
	
let allowForUsers = (passport) => {
	return passport.authenticate('jwt', {session : false});
};

let allowForDevelopers = (passport) => {
	return compose()
		.use(allowForUsers(passport))
		.use(function (req, res, next){
			const user = req.user;
			if (user.role ===  userConst.USER_ROLE_DEVELOPER){
				next();
			}
			else{
				res.status(403).json(responseUtil.getErrorResponseJsonObject(errorUtil.ERR_OBJECT_ACCESS, 'Action allowe only for developers'));
			}
		});
};

let allowForManagers = (passport) => {
	return compose()
		.use(allowForUsers(passport))
		.use(function (req, res, next){
			const user = req.user;
			if (user.role ===  userConst.USER_ROLE_MANAGER){
				next();
			}
			else{
				res.status(403).json(responseUtil.getErrorResponseJsonObject(errorUtil.ERR_OBJECT_ACCESS, 'Action allowe only for managers'));
			}
		});
}


module.exports = {
	comparePassword: comparePassword,
    hashPassword: hashPassword,
    getJwtToken: getJwtToken,
    allowForDevelopers : allowForDevelopers,
    allowForManagers : allowForManagers,
    allowForUsers : allowForUsers
};
