Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 45x 45x 45x 45x 44x 44x 44x 1x 44x | import {UserRepository} from '@loopback/authentication-jwt';
import {inject} from '@loopback/core';
import {repository} from '@loopback/repository';
import {UserProfile} from '@loopback/security';
import {promisify} from 'util';
import {TokenServiceBindings} from '../keys';
import errorMessages from '../utils/errorMessages';
const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);
export class JWTService {
// @inject('authentication.jwt.secret')
@inject(TokenServiceBindings.TOKEN_SECRET)
public readonly jwtSecret: string;
@inject(TokenServiceBindings.TOKEN_EXPIRES_IN)
public readonly expiresSecret: string;
@repository(UserRepository)
public userRepository: UserRepository;
async generateToken(userProfile: UserProfile): Promise<string> {
let methodName = "generateToken"
Iif (!userProfile) {
throw {code: 401, message: errorMessages.userProfileMissingInJWT, methodName,className:JWTService.name}
}
try {
return await signAsync(userProfile, this.jwtSecret, {
expiresIn: this.expiresSecret
});
} catch (err) {
throw {code: 401, message: errorMessages.generatingToken + " " + err, methodName,className:JWTService.name}
}
}
async verifyToken(token: string): Promise<UserProfile> {
let methodName = "verifyToken"
Iif (!token) {
throw {code: 401, message: errorMessages.errorVerifyingToken + ": token is null", methodName,className:JWTService.name}
};
let userProfile: UserProfile;
try {
const decryptedToken = await verifyAsync(token, this.jwtSecret);
const foundUser = await this.userRepository.findOne({where: {UID: decryptedToken.UID}, include: ['role']});
Iif (!foundUser) {
throw {code: 401, message: errorMessages.tokenNotValid, methodName,className:JWTService.name}
}
userProfile = Object.assign(foundUser);
}
catch (err: any) {
throw {code: 401, message: errorMessages.errorVerifyingToken + " " + err.message, methodName,className:JWTService.name}
}
return userProfile;
}
}
|