authController.js 2.42 KB
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const config = require(__dirname + '/../config/config')

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

exports.login = async (req, res) => {
    const required = checkRequiredExist(req.body, ['userId', 'password'])
    if (required) {
        logging('auth', 'error', { code: 400, message: `missingKey:${required}` }, req)
        return sendError(res, 400, `missingKey:${required}`)
    }
    const userId = req.body.userId
    const password = req.body.password

    let token = null
    let user = null
    let isSuccess = false
    let tokenInfo = {
        userInfo: {
            id: null,
        },
        tokenConfig: {
            expiresIn: '24h',
            issuer: 'OSS',
        },
    }

    let match = false
    try {
        user = await User.findOne({
            where: {
                userId: userId
            }
        })
        if (user) {
            match = await bcrypt.compare(password, user.password)
        }
    } catch (error) {
        logging('auth', 'error', { code: 500, message: error.message }, req)
        return sendError(res, 500, error.message)
    }

    if (match) {
        tokenInfo.userInfo.id = user.id
        isSuccess = true
    }
    else {
        logging('auth', 'error', { code: 401, message: 'Auth Failed' }, req)
        return sendError(res, 401, 'Auth Failed')
    }

    if (isSuccess === true) { //성공할 경우 토큰 발행
        token = jwt.sign (tokenInfo.userInfo, config.JWT_KEY, tokenInfo.tokenConfig)
        logging('auth', 'access', { user: tokenInfo.userInfo.id },req)
        return res.status(200).json({ success: true, access_token: token })
    }
}

exports.userInfo = async (req, res) => {
    const id = req.decoded.id
    if (!id) {
        return sendError(res, 401, 'InvalidToken')
    }
    let user = null
    try {
        user = await User.findOne ({
            where: {
                id
            }
        })
    } catch (error) {
        return sendError(res, 500, error.message)
    }
    if (user) {
        sendResponse(res, user, 200)
    } else {
        return sendError(res, 404, 'NoUserFound')

    }
}

exports.isAdmin = async (userId) => {
    const user = await User.findByPk(userId)
    return (user && await user.isAdmin)
}