63 lines
2.3 KiB
JavaScript
63 lines
2.3 KiB
JavaScript
import UserService from '../services/user.js';
|
|
import log from '../utils/log.js';
|
|
import bcrypt from 'bcrypt';
|
|
import genToken from '../utils/jwt.js';
|
|
import AbstractProductService from '../services/abstractproduct.js';
|
|
import ProductService from '../services/product.js';
|
|
import translate from '../utils/translate.js';
|
|
import responseCodes from '../response/responseCodes.js';
|
|
import customError from '../response/customError.js';
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
const TAG = "/controllers/userjs"
|
|
|
|
class UserController {
|
|
async register(req, res) {
|
|
const { username, password } = req.body;
|
|
|
|
await UserService.create(username, password);
|
|
|
|
log.info(`New user with name ${username} has just registered`);
|
|
return res.status(200).send(translate(req.headers["accept-language"], responseCodes.responses.general.ok));
|
|
}
|
|
|
|
async login(req, res) {
|
|
const { username, password } = req.body;
|
|
|
|
const user = await UserService.getByUsername(username);
|
|
if (!bcrypt.compareSync(password, user.password)) throw new customError(`Wrong user password`, responseCodes.responses.passwords.invalid);
|
|
|
|
const token = genToken(user);
|
|
return res.status(200).send(token);
|
|
}
|
|
|
|
async synchronize(req, res) {
|
|
const { groupId } = req.params;
|
|
|
|
let result = {};
|
|
result.abstract_products = await AbstractProductService.getAll(groupId);
|
|
result.products = await ProductService.getAll(groupId);
|
|
result.categories = await CategoryService.getAll(groupId);
|
|
|
|
return res.status(200).send(result);
|
|
}
|
|
|
|
async changeUsername(req, res) {
|
|
const userId = jwt.decode(req.headers.authorization.split(' ')[1]).login.id
|
|
const { username } = req.body;
|
|
|
|
await UserService.changeUsername(userId, username);
|
|
|
|
return res.status(200).send(translate(req.headers["accept-language"], responseCodes.responses.general.ok))
|
|
}
|
|
|
|
async changePassword(req, res) {
|
|
const userId = jwt.decode(req.headers.authorization.split(' ')[1]).login.id
|
|
const { password } = req.body;
|
|
|
|
await UserService.changePassword(userId, password);
|
|
return res.status(200).send(translate(req.headers["accept-language"], responseCodes.responses.general.ok))
|
|
}
|
|
}
|
|
|
|
export default new UserController() |