diff --git a/src/controllers/user.controller.ts b/src/controllers/user.controller.ts index 1855b92..7c3eb71 100644 --- a/src/controllers/user.controller.ts +++ b/src/controllers/user.controller.ts @@ -11,8 +11,6 @@ import { LogService } from "../services/log.service"; class UserController extends BaseController { - private Service = new UserService(UserModel) - private LogService = new LogService() public readonly router = Router() constructor() { @@ -24,6 +22,9 @@ class UserController extends BaseController { } } + private Service = new UserService(UserModel, this.getApplicationSecret()) + private LogService = new LogService() + private loadRoutes() { this.router.get('/', Guard, this.getAll) this.router.get('/:id', Guard, this.getById) diff --git a/src/services/index.ts b/src/services/index.ts index ae31f2f..02be2f8 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -1 +1 @@ -export { Environment as EnvironmentService } from "./evironment.service"; +export { Environment as EnvironmentService } from "./environment.service"; diff --git a/src/services/user.service.spec.ts b/src/services/user.service.spec.ts index 172a78e..dc98e5e 100644 --- a/src/services/user.service.spec.ts +++ b/src/services/user.service.spec.ts @@ -11,7 +11,7 @@ let UserModel = { findOne: jest.fn() } as unknown as ModelCtor> -const service = new UserService(UserModel) +const service = new UserService(UserModel, 'key') const hash = '$2b$10$1Q6Zz1' diff --git a/src/services/user.service.ts b/src/services/user.service.ts index 11d8847..f72521a 100644 --- a/src/services/user.service.ts +++ b/src/services/user.service.ts @@ -5,28 +5,27 @@ import { User, UserModel } from "../models"; import { searchEntity } from "../utils/searchEntity"; import * as bcrypt from 'bcrypt' import { LegendHttpError } from "../web/errors"; -import jwt from 'jsonwebtoken' +import { Auth as AuthService } from "./auth.service"; class UserService { - constructor(private readonly userModel: typeof UserModel) {} + constructor(private readonly userModel: typeof UserModel, private readonly applicationSecret: string = '') {} async signIn(signInDto: SignInDto): Promise { const user = await searchEntity(this.userModel, { username: signInDto.username }, false, false) - if (user === null) { - throw new LegendHttpError(401, 'User or password invalid.') - } - - const isPasswordMatch = await bcrypt.compare(signInDto.password, user.password) + const isPasswordMatch = await bcrypt.compare( + signInDto.password, + user?.password || '' + ) - if (!isPasswordMatch) { + if ((user === null) || !isPasswordMatch) { throw new LegendHttpError(401, 'User or password invalid.') } - const token = await jwt.sign({ id: user.id, username: user.username }, process.env.JWT_SECRET, { - expiresIn: '20min' - }) + const auth = new AuthService(user, this.applicationSecret) + + const token = auth.signToken() return token }