Skip to content

Commit

Permalink
🔐 complete authentication flow with passport
Browse files Browse the repository at this point in the history
  • Loading branch information
BHesseldieck committed Dec 8, 2021
1 parent 72c1dca commit 3ceac75
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 27 deletions.
38 changes: 18 additions & 20 deletions packages/cli/src/UserManagement/auth/jwt.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// @ts-nocheck

import { ExtractJwt, JwtStrategy } from 'passport-jwt';
import { ExtractJwt, Strategy } from 'passport-jwt';
import * as jwt from 'jsonwebtoken';
import * as passport from 'passport';

import { Db } from '../..';
import config = require('../../../config');
Expand All @@ -12,40 +11,39 @@ const options = {
secretOrKey: 'abc', //config.get('jwt_key'),
};

// The JWT payload is passed into the verify callback
passport.use(
new JwtStrategy(options, function (jwt_payload, done) {
// We will assign the `sub` property on the JWT to the database ID of user
// const { id, email } = jwt_payload;
Db.collections.User.findOne({
id: jwt_payload.id,
email: jwt_payload.email,
}).then((user) => {
export function useJwt(passport) {
// The JWT payload is passed into the verify callback
passport.use(
new Strategy(options, async function (jwt_payload, done) {
// We will assign the `sub` property on the JWT to the database ID of user
const user = await Db.collections.User.findOne({
id: jwt_payload.id,
email: jwt_payload.email,
});
if (!user) {
return done('User not found', false);
return done(null, false, { message: 'User not found' });
}
return done(null, user);
});
}),
);
}),
);
}

export function issueJWT(user) {
const { id, email } = user;
const expiresIn = '7d';
const expiresIn = 14 * 86400000; // 14 days

const payload = {
id,
email,
issuedAt: Date.now(),
};

const signedToken = jwt.sign(payload, options.secretOrKey, {
expiresIn,
algorithm: 'RS256',
expiresIn: expiresIn / 1000 /* in seconds */,
});

return {
token: 'Bearer ' + signedToken,
expires: expiresIn,
expiresIn,
validTill: Date.now() + expiresIn,
};
}
22 changes: 15 additions & 7 deletions packages/cli/src/UserManagement/auth/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,39 @@

import * as express from 'express';
import * as passport from 'passport';
import { Db, ResponseHelper } from '..';
import { Db, ResponseHelper } from '../..';
import { User } from '../databases/entities/User';
import { issueJWT } from './jwt';
import { issueJWT, useJwt } from './jwt';

useJwt(passport);

export function authenticationRoutes(): void {
// ----------------------------------------
// authentication middleware
// ----------------------------------------
this.app.use(passport.initialize());
this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
passport.authenticate('jwt', { session: false });
next();
// just temp for development
if (req.url.includes('login')) {
return next();
}
// get access to this from Server.ts
// if (authIgnoreRegex.exec(req.url)) {
// return next();
// }
return passport.authenticate('jwt', { session: false })(req, res, next);
});

// ----------------------------------------
// login a user
// ----------------------------------------

this.app.post(
this.app.get(
`/${this.restEndpoint}/login`,
ResponseHelper.send(async (req: express.Request, res: express.Response) => {
const user = await Db.collections.User!.findOne({ firstName: 'Ben' });

const tokenObject = issueJWT(user);
res.status(200).json({ success: true, token: tokenObject.token });
return issueJWT(user);
}),
);
}

0 comments on commit 3ceac75

Please sign in to comment.