Skip to content

Commit

Permalink
refactor: extract decode user to util
Browse files Browse the repository at this point in the history
Signed-off-by: jannyHou <[email protected]>
  • Loading branch information
jannyHou committed Jan 25, 2019
1 parent 3cbb0a8 commit 9de6315
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 95 deletions.
87 changes: 0 additions & 87 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 2 additions & 8 deletions src/authentication-strategies/JWT.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

const jwt = require('jsonwebtoken');
import {promisify} from 'util';
const verifyAsync = promisify(jwt.verify);
// Consider turn it to a binding
const SECRET = 'secretforjwt';
import {Request, HttpErrors} from '@loopback/rest';
import {UserProfile} from '@loopback/authentication';
import * as _ from 'lodash';
import {AuthenticationStrategy} from './authentication.strategy';
import {decodeAccessToken} from '../utils/user.authentication';

export class JWTStrategy implements AuthenticationStrategy {
async authenticate(request: Request): Promise<UserProfile | undefined> {
Expand All @@ -23,10 +20,7 @@ export class JWTStrategy implements AuthenticationStrategy {
}

try {
const decoded = await verifyAsync(token, SECRET);
let user = _.pick(decoded, ['id', 'email', 'firstName']);
(user as UserProfile).name = user.firstName;
delete user.firstName;
const user = await decodeAccessToken(token, SECRET);
return user;
} catch (err) {
Object.assign(err, {
Expand Down
14 changes: 14 additions & 0 deletions src/utils/user.authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import {toJSON} from '@loopback/testlab';
import {promisify} from 'util';
import * as isemail from 'isemail';
import {HttpErrors} from '@loopback/rest';
import {UserProfile} from '@loopback/authentication';
const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);

export async function getAccessTokenForUser(
userRepository: UserRepository,
Expand Down Expand Up @@ -46,3 +48,15 @@ export function validateCredentials(credentials: Credentials) {
);
}
}

// secret should be injected
export async function decodeAccessToken(
token: string,
secret: string,
): Promise<UserProfile> {
const decoded = await verifyAsync(token, secret);
let user = _.pick(decoded, ['id', 'email', 'firstName']);
(user as UserProfile).name = user.firstName;
delete user.firstName;
return user;
}

0 comments on commit 9de6315

Please sign in to comment.