userController.js 5.56 KB
const bcrypt = require('bcrypt')

const { sequelize, Sequelize, User, Group} = require('../models')
const { sendResponse, sendError } = require('../utils/response')
const { logging } = require('../utils/log')
const { checkRequiredExist, setValues } = require('../utils/validation')

const Op = Sequelize.Op

exports.userRegister = async (req, res) => {
    try {
        const requiredKey = ['userId', 'password', 'name', 'phone', 'email']
        const required = checkRequiredExist(req.body, requiredKey)
        if (required) {
            logging('user', 'error', { code: 400, message: `missingKey:${required}` }, req)
            return sendError(res, 400, `missingKey:${required}`)
        }
        let registerData = setValues(req.body, ['userId', 'password', 'name', 'phone', 'email'])

        if (typeof registerData.password !== 'undefined' && registerData.password !== null) {
            registerData.password = await bcrypt.hash(registerData.password, 10)
        }

        if (typeof registerData.userId !== 'undefined' && registerData.userId !== null) {
            let userIdDuplicated = await User.count({
                where: {
                    userId: registerData.userId
                },
            })
            if (userIdDuplicated > 0) {
                logging('user', 'error', { code: 400, message: 'duplicatedUserId' }, req)
                return sendError(res, 400, 'duplicatedUserId')
            }
        }
        let user = await User.create(registerData)
        logging('user', 'register', user, req)
        return sendResponse(res, user, 200)

    } catch (error) {
        logging('user', 'error', { code: 500, message: error.message }, req)
        return sendError(res, 500, error.message)
    }
}

exports.userUpdate = async (req, res) => {
    const id = req.decoded.id
    if (!id) {
        return sendError(res, 401, 'InvalidToken')
    }
    try {
        let updateData = setValues(req.body, ['password', 'name', 'phone', 'email'])

        if (typeof updateData.password !== 'undefined' && updateData.password !== null) {
            updateData.password = await bcrypt.hash(updateData.password, 10)
        }
        let logdata = { }
        let user = await User.findByPk(id)
        if (!user) {
            logging('user', 'error', {code: 404, message: 'NoUserFound'}, req)
            return sendError(res, 404, 'NoUserFound')
        }
        logdata.before = { user: user }
        await user.update(updateData)

        logdata.after = { user: user }
        logging('user', 'update', user, req)
        return sendResponse(res, user, 200)

    } catch (error) {
        logging('user', 'error', { code: 500, message: error.message }, req)
        return sendError(res, 500, error.message)
    }
}

exports.adminUserList = async (req, res) => {
    try{
        let users = await User.findAndCountAll({
            where: {
                id: { [Op.ne]: 1 }
            },
            order: [
                ['createdAt', 'desc']
            ]
        })

        const result = {
            count: users.count,
            data: users.rows
        }
        return sendResponse(res, result, 200)
    } catch(error) {
        logging('user', 'error', { code: 500, message: error.message }, req)
        return sendError(res, 500, error.message)
    }
}

exports.adminUserInfo = async  (req, res) => {
    const requiredKey = ['id']
    const required = checkRequiredExist(req.body, requiredKey)
    if (required) {
        logging('user', 'error', { code: 400, message: `missingKey:${required}` }, req)
        return sendError(res, 400, `missingKey:${required}`)
    }

    const userId = req.body.id

    try {
        const user = await User.findByPk(userId)
        if (!user) {
            logging('user', 'error', { code: 404, message: 'NoUserFound' }, req)
            return sendError(res, 404, 'NoUserFound')
        }

        return sendResponse(res, user, 200)
    } catch (error) {
        return sendError(res, 500, error.message)
    }
}

exports.adminUserUpsert = async (req, res) => {
    const id = req.body.id

    try {
        let updatedData = setValues(req.body, ['userId', 'password', 'name', 'phone', 'email', 'isAdmin'])

        if (typeof updatedData.password !== 'undefined' && updatedData.password !== null) {
            updatedData.password = await bcrypt.hash(updatedData.password, 10)
        }

        if (typeof updatedData.userId !== 'undefined' && updatedData.userId !== null) {
            let userIdDuplicated = await User.count({
                where: {
                    id: { [Op.ne]: id },
                    userId: updatedData.userId
                },
            })
            if (userIdDuplicated > 0) {
                logging('user', 'error', { code: 400, message: 'duplicatedUserId' }, req)
                return sendError(res, 400, 'duplicatedUserId')
            }
        }

        let logdata = { }
        let user = null
        if (id) {
            user = await User.findByPk(id)
            if (!user) {
                logging('user', 'error', {code: 404, message: 'NoUserFound'}, req)
                return sendError(res, 404, 'NoUserFound')
            }
            logdata.before = { user: user }
            await user.update(updatedData)
        } else {
            user = await User.create(updatedData)
            logdata.before = null
        }

        logdata.after = { user: user }
        logging('user', 'update', logdata, req)
        return sendResponse(res, user, 200)

    } catch (error) {
        logging('user', 'error', { code: 500, message: error.message }, req)
        return sendError(res, 500, error.message)
    }
}