v3.0.0/src/api/routes/auth/loginPOST.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-09-16 05:56:13 +02:00
const bcrypt = require('bcrypt');
const moment = require('moment');
const JWT = require('jsonwebtoken');
const Route = require('../../structures/Route');
2018-09-16 05:56:13 +02:00
class loginPOST extends Route {
constructor() {
super('/auth/login', 'post', { bypassAuth: true });
}
2019-02-21 16:37:20 +01:00
async run(req, res, db) {
2018-09-16 05:56:13 +02:00
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' });
2018-09-17 09:55:42 +02:00
/*
Checks if the user exists
*/
2018-09-16 05:56:13 +02:00
const user = await db.table('users').where('username', username).first();
if (!user) return res.status(401).json({ message: 'Invalid authorization' });
2019-02-28 15:52:04 +01:00
/*
Checks if the user is disabled
*/
if (!user.enabled) return res.status(401).json({ message: 'This account has been disabled' });
2018-09-17 09:55:42 +02:00
/*
Checks if the password is right
*/
2018-09-16 05:56:13 +02:00
const comparePassword = await bcrypt.compare(password, user.password);
if (!comparePassword) return res.status(401).json({ message: 'Invalid authorization.' });
2018-09-17 09:55:42 +02:00
/*
Create the jwt with some data
*/
2018-09-16 05:56:13 +02:00
const jwt = JWT.sign({
2020-12-25 12:45:22 +01:00
iss: 'chibisafe',
2018-09-16 05:56:13 +02:00
sub: user.id,
2020-12-24 09:40:50 +01:00
iat: moment.utc().valueOf()
2019-02-21 16:37:20 +01:00
}, process.env.SECRET, { expiresIn: '30d' });
2018-09-16 05:56:13 +02:00
return res.json({
message: 'Successfully logged in.',
2019-02-28 15:26:44 +01:00
user: {
id: user.id,
username: user.username,
apiKey: user.apiKey,
2020-12-24 09:40:50 +01:00
isAdmin: user.isAdmin
2019-02-28 15:26:44 +01:00
},
2018-09-16 05:56:13 +02:00
token: jwt,
2020-12-24 09:40:50 +01:00
apiKey: user.apiKey
2018-09-16 05:56:13 +02:00
});
}
}
module.exports = loginPOST;