forked from projects/fipamo
89 lines
2.1 KiB
JavaScript
89 lines
2.1 KiB
JavaScript
import * as DataEvent from '../../tools/events/DataEvent';
|
|
const express = require('express');
|
|
const router = express.Router();
|
|
const bCrypt = require('bcrypt-nodejs');
|
|
const jwt = require('jsonwebtoken');
|
|
const fs = require('fs-extra');
|
|
const _ = require('lodash');
|
|
|
|
/**
|
|
* Get Auth Status
|
|
*/
|
|
router.get('/', function(req, res) {
|
|
var token = req.headers['x-access-token'];
|
|
if (!token) return res.status(401).send({ auth: false, message: 'No token provided.' });
|
|
|
|
jwt.verify(token, 'super-secret-string', function(err, decoded) {
|
|
if (err)
|
|
return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
|
|
res.status(200).send(decoded);
|
|
});
|
|
});
|
|
/**
|
|
* Login Member and return token
|
|
*/
|
|
router.post('/login', function(req, res) {
|
|
fs.readJson('config/folks.json').then(folks => {
|
|
let found = _.find(folks, { handle: req.body.handle });
|
|
if (found) {
|
|
if (!isValidPassword(found, req.body.password)) {
|
|
res.json({
|
|
type: DataEvent.REQUEST_LAME,
|
|
message: 'CHECK YOUR PASSWORD'
|
|
});
|
|
}
|
|
|
|
let token = jwt.sign({ id: found.id }, 'super-secret-string', {
|
|
expiresIn: 86400 // expires in 24 hours
|
|
});
|
|
|
|
let session = req.session;
|
|
session.user = found;
|
|
session.token = token;
|
|
res.json({ type: DataEvent.REQUEST_GOOD, message: 'Yes', token: session.token });
|
|
} else {
|
|
res.json({
|
|
type: DataEvent.REQUEST_LAME,
|
|
message: 'MEMBER NOT FOUND'
|
|
});
|
|
}
|
|
});
|
|
|
|
/**
|
|
Models.User.findOne({
|
|
where: {
|
|
handle: req.body.handle
|
|
}
|
|
})
|
|
.then(user => {
|
|
if (!isValidPassword(user, req.body.password)) {
|
|
return res.json({
|
|
message: 'CHECK YOUR PASSWORD'
|
|
});
|
|
}
|
|
|
|
let token = jwt.sign({ id: user._id }, 'super-secret-string', {
|
|
expiresIn: 86400 // expires in 24 hours
|
|
});
|
|
|
|
let session = req.session;
|
|
session.user = user;
|
|
session.token = token;
|
|
|
|
res.json({ auth: 'Yes', token: session.token });
|
|
})
|
|
.catch(() => {
|
|
return res.json({
|
|
message: 'NOT FOUND, HAWS'
|
|
});
|
|
});
|
|
**/
|
|
});
|
|
|
|
//router.post('/logout', function(req, res) {});
|
|
module.exports = router;
|
|
|
|
function isValidPassword(user, password) {
|
|
return bCrypt.compareSync(password, user.password);
|
|
}
|