captcha_aggregator/src/controllers/user.js

49 lines
2.1 KiB
JavaScript

import UserService from '../services/user.js';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import config from '../config.js';
class UserController {
async register(req, res) {
try {
const { username, password } = req.body;
if (!username) return res.status(400).send({"message":"You must specify username"});
if (!password) return res.status(400).send({"message":"You must specify password"});
if (await UserService.get_by_username(username)) return res.status(409).send({"message":"Such user already exists!"})
const id = await UserService.add(username, bcrypt.hashSync(password, 10));
const token = jwt.sign({"username": username, "id": id}, config.secret);
return res.status(200).send({"messae": "Success", "token": token});
} catch (e) {
console.log(e)
return res.status(500).send({"message": "Unknown server error. Please, contact the developer"});
}
}
async login (req, res) {
try {
const { username, password } = req.body;
const user = await UserService.get_by_username(username);
if (!user) return res.status(404).send({"message":"No such user exists"});
const hashed_password = user.password;
if (!bcrypt.compareSync(password, hashed_password)) return res.status(403).send({"message":"Passwords dont match"});
const token = jwt.sign({"username": username, "id": user.id}, config.secret);
return res.status(200).send({"message": "Success", "token": token});
} catch (e) {
console.log(e)
return res.status(500).send({"message": "Unknown server error"});
}
}
async stats (req, res) {
try {
const user_id = jwt.decode(req.token).id;
const stats = await UserService.get_stats(user_id);
return res.status(200).send({"message": "Success", "stats": stats});
} catch (e) {
console.log(e)
return res.status(500).send({"message": "Unknown server error"});
}
}
}
export default new UserController();