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.
88 lines
2.1 KiB
JavaScript
88 lines
2.1 KiB
JavaScript
import * as DataEvent from '../../../src/com/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');
|
|
//const crypto = require('crypto'); // for setting up new accounts
|
|
|
|
/**
|
|
* 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);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Get Auth Status
|
|
*/
|
|
router.get('/status', function (req, res) {
|
|
if (req.session.user) {
|
|
let session = req.session;
|
|
res.json({
|
|
type: DataEvent.API_REQUEST_GOOD,
|
|
message: 'Auth is Good',
|
|
token: session.hashToken
|
|
});
|
|
} else {
|
|
res.json({
|
|
type: DataEvent.API_REQUEST_LAME,
|
|
message: 'NOT AUTHORIZED'
|
|
});
|
|
}
|
|
});
|
|
/**
|
|
* Login Member and return token
|
|
*/
|
|
router.post('/login', function (req, res) {
|
|
fs.readJson('site/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 }, found.key, {
|
|
expiresIn: 86400 // expires in 24 hours
|
|
});
|
|
|
|
let session = req.session;
|
|
session.user = found;
|
|
session.token = token;
|
|
session.hashToken = hashToken(token);
|
|
res.json({
|
|
type: DataEvent.REQUEST_GOOD,
|
|
message: 'Welcome Back',
|
|
token: session.hashToken
|
|
});
|
|
} else {
|
|
res.json({
|
|
type: DataEvent.REQUEST_LAME,
|
|
message: 'Need to see some id, champ.'
|
|
});
|
|
}
|
|
});
|
|
});
|
|
|
|
//router.post('/logout', function(req, res) {});
|
|
module.exports = router;
|
|
|
|
function isValidPassword(user, password) {
|
|
return bCrypt.compareSync(password, user.password);
|
|
}
|
|
|
|
function hashToken(token) {
|
|
return bCrypt.hashSync(token, bCrypt.genSaltSync(10), null);
|
|
}
|