You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Fipamo/brain/data/Auth.js

106 lines
2.5 KiB
JavaScript

import * as DataEvent from '../../src/com/events/DataEvent';
const bCrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
export default class Auth {
//--------------------------
// constructor
//--------------------------
constructor() {}
//--------------------------
// methods
//--------------------------
start() {}
/**
* Makes sure access token is legit
* @parameter req
*/
authCheck(req) {
let self = this;
return new Promise((resolve, reject) => {
let hash = req.headers['x-access-token'];
let response = [];
//check to see if user is logged in
if (!req.session.user) {
response = {
status: false,
type: DataEvent.API_REQUEST_LAME,
message: "You're not logged in, champ."
};
reject(response);
}
//Checks if token is a proper hash, if not reject
if (!self.isTokenValid(req.session.token, hash)) {
response = {
status: false,
type: DataEvent.API_REQUEST_LAME,
message: 'No Token Present. Auth Blocked'
};
reject(response);
//res.json();
} else {
var member = req.session.user;
jwt.verify(req.session.token, member.key, function (err, decoded) {
if (err) {
response = {
status: false,
type: DataEvent.API_REQUEST_LAME,
message: 'Invalid Token. Auth Blocked'
};
reject(response);
}
response = {
status: true,
type: DataEvent.API_REQUEST_GOOD,
message: 'Token Verified',
token: decoded
};
resolve(response);
});
}
});
}
verifyCredentials(config, credentials) {
return new Promise((resolve, reject) => {
var found = _.find(config, { handle: credentials.handle });
var response;
if (found) {
if (!this.isValidPassword(found, credentials.pass)) {
response = {
type: DataEvent.REQUEST_LAME,
message: 'CHECK YOUR PASSWORD'
};
reject(response);
}
response = { type: DataEvent.REQUEST_GOOD, message: 'Backup Verified. Restoring' };
resolve(response);
} else {
response = { type: DataEvent.REQUEST_LAME, message: 'Handle not found, boss' };
reject(response);
}
});
}
isValidPassword(user, password) {
return bCrypt.compareSync(password, user.password);
}
/**
* Checks to make sure received token matches
* @parameter token: created token
* @parameter hashedToken: encrypted token
*/
isTokenValid(token, hashedToken) {
return bCrypt.compareSync(token, hashedToken);
}
//--------------------------
// event handlers
//--------------------------
}