authController.js
2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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)
}