diff --git a/src/routes/auth.ts b/src/routes/auth.ts index f67a80160f..8d3e818629 100644 --- a/src/routes/auth.ts +++ b/src/routes/auth.ts @@ -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 }, diff --git a/src/services/auth.ts b/src/services/auth.ts new file mode 100644 index 0000000000..1cb6cacf40 --- /dev/null +++ b/src/services/auth.ts @@ -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; +};