-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-controller.ts
More file actions
89 lines (74 loc) · 2.44 KB
/
user-controller.ts
File metadata and controls
89 lines (74 loc) · 2.44 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import jwt, { SignOptions } from 'jsonwebtoken';
import { ENV } from '../config/env';
import { hashPassword, generateApiKey } from '../utils/auth';
import { successResponse, errorResponse } from '../utils/response';
import UserRepository from '../repositories/user-repository';
import Users from '../models/user';
import { InferAttributes } from 'sequelize';
type UserType = InferAttributes<Users>;
interface AuthRequest extends Request {
user?: UserType;
}
export const registerUser = async (req: Request, res: Response) => {
try {
const { name, email, password } = req.body;
if (!name || !email || !password) {
return errorResponse(res, 'Name, email, and password are required', 400);
}
const existingUser = await UserRepository.findOne({ email });
if (existingUser) {
return errorResponse(res, 'Email is already registered', 400);
}
const hashedPassword = await hashPassword(password);
const apiKey = await generateApiKey();
const newUser = await UserRepository.insert({
name,
email,
password: hashedPassword,
apikey: apiKey,
});
return successResponse(
res,
{ id: newUser.id },
'User registered successfully',
);
} catch (error) {
console.error(error);
return errorResponse(res, 'Internal server error', 500);
}
};
export const loginUser = async (req: Request, res: Response) => {
try {
const { email, password } = req.body;
const user = await UserRepository.findOne({ email });
if (!user) {
return errorResponse(res, 'Unauthorized', 401);
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return errorResponse(res, 'Unauthorized', 401);
}
const signOptions: SignOptions = {
expiresIn: ENV.JWT_EXPIRES_IN as SignOptions['expiresIn'],
};
const token = jwt.sign(
{ userId: user.id, email: user.email },
ENV.JWT_SECRET,
signOptions,
);
return successResponse(res, { token }, 'Login successful');
} catch (error) {
console.error(error);
return errorResponse(res, 'Internal server error', 500);
}
};
export const getUserDetails = async (req: AuthRequest, res: Response) => {
try {
return successResponse(res, req.user, 'User details retrieved');
} catch (error) {
console.error(error);
return errorResponse(res, 'Unauthorized', 401);
}
};