Move login logic to service

This commit is contained in:
rijkvanzanten
2020-06-23 15:45:14 -04:00
parent 654c00afe3
commit 637031f53c
2 changed files with 37 additions and 25 deletions

View File

@@ -1,9 +1,7 @@
import { Router } from 'express';
import asyncHandler from 'express-async-handler';
import Joi from '@hapi/joi';
import database from '../database';
import APIError, { ErrorCode } from '../error';
import jwt from 'jsonwebtoken';
import * as AuthService from '../services/auth';
const router = Router();
@@ -18,28 +16,7 @@ router.post(
await loginSchema.validateAsync(req.body);
const { email, password } = req.body;
const user = await database
.select('id', 'password')
.from('directus_users')
.where({ email })
.first();
if (!user) {
throw new APIError(ErrorCode.INVALID_USER_CREDENTIALS, 'Invalid user credentials');
}
/** @TODO implement password hash */
if (password !== user.password) {
throw new APIError(ErrorCode.INVALID_USER_CREDENTIALS, 'Invalid user credentials');
}
const payload = {
id: user.id,
};
const token = jwt.sign(payload, process.env.SECRET, {
expiresIn: process.env.ACCESS_TOKEN_EXPIRY_TIME,
});
const token = await AuthService.authenticate(email, password);
return res.status(200).json({
data: { token },

35
src/services/auth.ts Normal file
View File

@@ -0,0 +1,35 @@
import database from '../database';
import APIError, { ErrorCode } from '../error';
import jwt from 'jsonwebtoken';
export const authenticate = async (email: string, password: string) => {
const user = await database
.select('id', 'password', 'role')
.from('directus_users')
.where({ email })
.first();
if (!user) {
throw new APIError(ErrorCode.INVALID_USER_CREDENTIALS, 'Invalid user credentials');
}
/** @TODO implement password hash */
if (password !== user.password) {
throw new APIError(ErrorCode.INVALID_USER_CREDENTIALS, 'Invalid user credentials');
}
const payload = {
id: user.id,
};
/**
* @TODO
* Sign token with combination of server secret + user password hash
* That way, old tokens are immediately invalidated whenever the user changes their password
*/
const token = jwt.sign(payload, process.env.SECRET, {
expiresIn: process.env.ACCESS_TOKEN_EXPIRY_TIME,
});
return token;
};