mirror of
https://github.com/directus/directus.git
synced 2026-01-29 11:17:57 -05:00
Move login logic to service
This commit is contained in:
@@ -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
35
src/services/auth.ts
Normal 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;
|
||||
};
|
||||
Reference in New Issue
Block a user