-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathAuthController.ts
More file actions
71 lines (55 loc) · 2.16 KB
/
AuthController.ts
File metadata and controls
71 lines (55 loc) · 2.16 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
import { getRepository } from 'typeorm';
import { Request, Response } from 'express';
import { Users } from '../entity/Users';
import * as jwt from 'jsonwebtoken';
import config from '../config/config';
import { validate } from 'class-validator';
class AuthController {
static login = async (req: Request, res: Response) => {
const { username, password } = req.body;
if (!(username && password)) {
return res.status(400).json({ message: ' Username & Password are required!' });
}
const userRepository = getRepository(Users);
let user: Users;
try {
user = await userRepository.findOneOrFail({ where: { username } });
} catch (e) {
return res.status(400).json({ message: ' Username or password incorecct!' });
}
// Check password
if (!user.checkPassword(password)) {
return res.status(400).json({ message: 'Username or Password are incorrect!' });
}
const token = jwt.sign({ userId: user.id, username: user.username }, config.jwtSecret, { expiresIn: '1h' });
res.json({ message: 'OK', token, userId: user.id, role: user.role, username: user.username });
};
static changePassword = async (req: Request, res: Response) => {
const { userId } = res.locals.jwtPayload;
const { oldPassword, newPassword } = req.body;
if (!(oldPassword && newPassword)) {
res.status(400).json({ message: 'Old password & new password are required' });
}
const userRepository = getRepository(Users);
let user: Users;
try {
user = await userRepository.findOneOrFail(userId);
} catch (e) {
res.status(400).json({ message: 'Somenthing goes wrong!' });
}
if (!user.checkPassword(oldPassword)) {
return res.status(401).json({ message: 'Check your old Password' });
}
user.password = newPassword;
const validationOps = { validationError: { target: false, value: false } };
const errors = await validate(user, validationOps);
if (errors.length > 0) {
return res.status(400).json(errors);
}
// Hash password
user.hashPassword();
userRepository.save(user);
res.json({ message: 'Password change!' });
};
}
export default AuthController;