const { body, validationResult } = require('express-validator') const userService = require('../services/userService') const FetchResult = require('../common/web/fetchResult') const messages = require('../config/messages') const { HTTP_STATUS } = require('../common/constant/httpStatus') exports.getAllUsers = async (res) => { try { const users = await userService.user_list() return FetchResult.formatResult(res, 200, 'success', users) } catch (err) { return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } } exports.createUser = [ body('account').isLength({ min: 3 }).withMessage('Account must be at least 3 characters long'), body('account').isEmpty().withMessage('Account is required'), body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'), body('password').isEmpty().withMessage('Password is required'), async (req, res, next) => { const errors = validationResult(req) if (!errors.isEmpty()) { return FetchResult.formatResult( res, HTTP_STATUS.BAD_REQUEST, errors .array() .map((err) => err.msg) .join(', ') ) } next() }, async (req, res) => { try { const user = req.body await userService.create_user(user) return FetchResult.formatResult(res, HTTP_STATUS.CREATED, messages.user.created) } catch (err) { logger('Error creating user: ', err) if (err.message === messages.user.already_exists) { return FetchResult.formatResult(res, HTTP_STATUS.CONFLICT, messages.user.already_exists) } return FetchResult.formatResult( res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error' ) } } ] exports.login = [ body('account').notEmpty().withMessage('Account is required'), body('password').notEmpty().withMessage('Password is required'), async (req, res, next) => { const errors = validationResult(req) if (!errors.isEmpty()) { console.log(errors) return FetchResult.formatResult( res, 400, errors .array() .map((err) => err.msg) .join(', ') ) } next() }, async (req, res) => { try { const { account, password } = req.body const user = await userService.login(account, password) req.session.user = user return FetchResult.formatResult(res, 200, messages.user.login) } catch (err) { if (err.message === messages.user.not_found) { return FetchResult.formatResult(res, 401, messages.user.account_password_not_match) } logger('Error logging in: ', err) return FetchResult.formatResult( res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error' ) } } ] exports.getUserExist = async (req, res) => { try { const { account } = req.query const exist = await userService.get_user_exist(account) if (!exist) { return FetchResult.formatResult(res, 404, messages.user.not_found) } return FetchResult.formatResult(res, 200, messages.user.exist) } catch (err) { logger('Error checking user existence: ', err) return FetchResult.formatResult(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal server error') } }