UNPKG

@speakr/speakr-module-services

Version:
113 lines (102 loc) 2.92 kB
'user strict'; const db = require('../../db/'); const env = require('../../env/'); const njwt = require('njwt'); const uuid = require('node-uuid'); const moment = require('moment'); const secretKey = uuid.v4(); module.exports = { newToken, setHeaders }; function newToken(options) { return sign(options) .then(save) .then(setHeaders) .then((options) => Promise.resolve(options)) } // Sign the token function sign(options) { const invalidToken = { code: 400, section: '/auth/', message: 'could not generate a token for this user' }; /* * README -> https://stormpath.com/blog/nodejs-jwt-create-verify * */ var claims = { /* * sub – This is the “subject” of the token, * the person whom it identifies. * For this field you should use the opaque user ID * from your user management system. * Don’t use personally identifiable information, * like an email address. * */ sub: options.users.id_hash, meta: { id_hash: options.users.id_hash, fname: options.users.first_name, lname: options.users.last_name, email: options.users.email, agency: options.users.agency_id, network: options.users.network_id }, /* * iss – This is the “issuer” field, * and it lets other parties know who created this token. * This could be the URL of your website, * or something more specific if your website has * multiple applications with different user databases. * */ iss: env.ISSUER, /* * permissions – Sometimes you’ll see this as scope if the * JWT is being used as an OAuth Bearer Token. * This is simply a comma-seperated list of things that * the user has access to do. * */ permissions: "all" }; // Create the token payload let jwt = njwt.create(claims, secretKey); // Set the expiration date on the token let exp = new Date().getTime() + env.AUTH_EXPIRES; // Set the token expiration jwt.setExpiration(exp); // Convert the payload to a base 64 hash let token = jwt.compact(); // Set the options token value options.tokens = token; // Set the claims value options.claims = jwt.body; return Promise.resolve(options); } function save(options) { // Convert the exp time to timestamp let exp = moment(options.claims.exp * 1000).format('YYYY-MM-DD HH:mm:ss'); return db.tokens.create( { user_id: options.users.id, key: secretKey, jwt: options.tokens, expired_at: exp, active: true } ).then((tokens) => { if (!tokens) { return Promise.reject({ code: 500, section: '/auth/', message: 'could not create a valid token' }); } else { return Promise.resolve(options); } }); } function setHeaders(options) { options.res.set('X-Auth-Token', options.tokens); return Promise.resolve(options); }