79 lines
2.7 KiB
JavaScript
79 lines
2.7 KiB
JavaScript
import UserService from '../services/user.js';
|
|
import log from '../utils/log.js';
|
|
import bcrypt from 'bcrypt';
|
|
import jwtutils 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;
|
|
|
|
let userId = await UserService.create(username, password);
|
|
|
|
log.info(`New user with name ${username} has just registered`);
|
|
return res.status(200).send(userId.toString());
|
|
}
|
|
|
|
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 = jwtutils.genToken(user);
|
|
return res.status(200).send({ id: user.id, token: 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 = jwtutils.getUserIdFromToken(req.headers.authorization.split(' ')[1]);
|
|
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 = jwtutils.getUserIdFromToken(req.headers.authorization.split(' ')[1]);
|
|
const { password } = req.body;
|
|
|
|
await UserService.changePassword(userId, password);
|
|
return res.status(200).send(translate(req.headers["accept-language"], responseCodes.responses.general.ok))
|
|
}
|
|
|
|
async getAllGroupsForUser(req, res) {
|
|
const userId = jwtutils.getUserIdFromToken(req.headers.authorization.split(' ')[1]);
|
|
|
|
let result = await UserService.getAllGroupsForUser(userId);
|
|
|
|
return res.status(200).send(result);
|
|
}
|
|
|
|
async getById(req, res) {
|
|
const userId = req.params.userId
|
|
|
|
let result = (await UserService.getById(userId)).username;
|
|
|
|
return res.status(200).send(result);
|
|
}
|
|
}
|
|
|
|
export default new UserController() |