aboutsummaryrefslogtreecommitdiff
path: root/src/api/routes/auth/loginPOST.js
blob: 665d0a3ad564652f30d16edb72dd8636cd332664 (plain) (blame)
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
const bcrypt = require('bcrypt');
const moment = require('moment');
const JWT = require('jsonwebtoken');
const Route = require('../../structures/Route');
const Util = require('../../utils/Util');

class loginPOST extends Route {
	constructor() {
		super('/auth/login', 'post', { bypassAuth: true });
	}

	async run(req, res, db) {
		if (!req.body) return res.status(400).json({ message: 'No body provided' });
		const { username, password } = req.body;
		if (!username || !password) return res.status(401).json({ message: 'Invalid body provided' });

		/*
			Checks if the user exists
		*/
		const user = await db.table('users').where('username', username).first();
		if (!user) return res.status(401).json({ message: 'Invalid authorization' });

		/*
			Checks if the user is disabled
		*/
		if (!user.enabled) return res.status(401).json({ message: 'This account has been disabled' });

		/*
			Checks if the password is right
		*/
		const comparePassword = await bcrypt.compare(password, user.password);
		if (!comparePassword) return res.status(401).json({ message: 'Invalid authorization.' });

		/*
			Create the jwt with some data
		*/
		const jwt = JWT.sign({
			iss: 'hostess',
			sub: user.id,
			iat: moment.utc().valueOf()
		}, Util.config.secret, { expiresIn: '30d' });

		return res.json({
			message: 'Successfully logged in.',
			user: {
				id:	user.id,
				username: user.username,
				apiKey: user.apiKey,
				isAdmin: user.isAdmin
			},
			token: jwt,
			apiKey: user.apiKey
		});
	}
}

module.exports = loginPOST;