-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.js
86 lines (73 loc) · 2.27 KB
/
utils.js
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
const jwt = require('jsonwebtoken');
const Url = require('url');
const uniqueString = require('unique-string');
const Promotion = require('./schemas/promotion');
const setting = require('./setting.json');
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max + 1);
return Math.floor(Math.random() * (max - min)) + min;
}
module.exports.getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max + 1);
return Math.floor(Math.random() * (max - min)) + min;
}
module.exports.isLogin = (req, res, next) => {
if(!req.isAuthenticated()) {
res.redirect(`/login?redirect=${encodeURIComponent(req.url)}`);
return;
}
next();
}
module.exports.isNotLogin = (req, res, next) => {
if(req.isAuthenticated()) {
res.redirect('/');
return;
}
next();
}
module.exports.isAdmin = (req, res, next) => {
if(!req.isAuthenticated()) {
res.redirect('/login');
return;
}
if(!req.user.admin) {
res.redirect('/');
return;
}
next();
}
module.exports.verifyToken = token => {
try {
const decoded = jwt.verify(token, setting.TOKEN_SECRET);
return decoded;
}
catch(err) {
if(err.name == 'TokenExpiredError') {
return { "error" : true , "code" : "error" , "message" : "토큰이 만료되었습니다." , "errcode" : err.name };
}
return { "error" : true , "code" : "error" , "message" : "유효하지 않은 토큰입니다." , "errcode" : err.name };
}
}
module.exports.getRandomNote = key_limit => {
return key_limit[getRandomInt(0, key_limit.length - 1)];
}
const createPromotion = async () => {
let promotion_code = uniqueString().substring(0, 25).replace(/(.{5})/g,"$1-").toUpperCase();
if(promotion_code.endsWith('-')) promotion_code = promotion_code.slice(0, -1);
const check = await Promotion.findOne({
code: promotion_code
});
if(!check) return promotion_code;
else return createPromotion();
}
module.exports.createPromotion = createPromotion;
module.exports.escapeHTML = s => {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}