-
Notifications
You must be signed in to change notification settings - Fork 676
/
Copy pathlogin.ts
executable file
·42 lines (35 loc) · 1.54 KB
/
login.ts
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
import express from 'express';
import { SuccessResponse } from '../../core/ApiResponse';
import crypto from 'crypto';
import UserRepo from '../../database/repository/UserRepo';
import { BadRequestError, AuthFailureError } from '../../core/ApiError';
import KeystoreRepo from '../../database/repository/KeystoreRepo';
import { createTokens } from '../../auth/authUtils';
import validator from '../../helpers/validator';
import schema from './schema';
import asyncHandler from '../../helpers/asyncHandler';
import bcrypt from 'bcrypt';
import { getUserData } from './utils';
import { PublicRequest } from '../../types/app-request';
const router = express.Router();
router.post(
'/basic',
validator(schema.credential),
asyncHandler(async (req: PublicRequest, res) => {
const user = await UserRepo.findByEmail(req.body.email);
if (!user) throw new BadRequestError('User not registered');
if (!user.password) throw new BadRequestError('Credential not set');
const match = await bcrypt.compare(req.body.password, user.password);
if (!match) throw new AuthFailureError('Authentication failure');
const accessTokenKey = crypto.randomBytes(64).toString('hex');
const refreshTokenKey = crypto.randomBytes(64).toString('hex');
await KeystoreRepo.create(user, accessTokenKey, refreshTokenKey);
const tokens = await createTokens(user, accessTokenKey, refreshTokenKey);
const userData = getUserData(user);
new SuccessResponse('Login Success', {
user: userData,
tokens: tokens,
}).send(res);
}),
);
export default router;