-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
160 lines (146 loc) · 4.45 KB
/
index.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mysql = require("mysql");
const md5 = require("md5");
const jwt = require("jsonwebtoken");
const now = Date.now();
// import * as dotenv from 'dotenv';
// dotenv.config()
require("dotenv").config();
// console.log(process.env)
const PORT = process.env.APP_PORT;
// parse application/json
app.use(bodyParser.json());
const config = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
};
//create database connection
const conn = mysql.createConnection(config);
// console.log(config);
//connect to database
conn.connect((err) => {
// if(err) throw err;
if (err) {
return console.error("error: " + err.message);
}
console.log("Mysql Connected...");
});
// router
app.get("/", (req, res) => {
res.setHeader("content-type", "application/json");
res.send(
JSON.stringify({
status: 200,
error: null,
message: "auth services is available",
})
);
});
app.post("/token", (req, res) => {
const refreshToken = req.body.token
conn.query("SELECT token FROM Tokens WHERE token='" + refreshToken + "'", (err, results) => {
if (err) throw err;
if (results.length == 0) {
res.sendStatus(403)
} else {
jwt.verify(refreshToken, process.env.JWT_REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403)
const accessToken = createJwt(user)
const data = {
accessToken: accessToken,
};
res.send(JSON.stringify({status: 200, error: null, response: data}));
})
}
})
})
app.post("/login", (req, res) => {
const username = req.body.username;
const password = md5(req.body.password);
let sql =
"SELECT * FROM auth WHERE username='" +
username +
"' AND password='" +
password +
"'";
let query = conn.query(sql, (err, results) => {
if (err) throw err;
if (results.length == 1) {
// console.log(results[0]);
const token = createJwt(results[0].user_id);
const refreshToken = jwt.sign(results[0].user_id, process.env.JWT_REFRESH_TOKEN_SECRET);
const data = {
accessToken: token,
refreshToken: refreshToken
};
const datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
let userId = results[0].user_id
let checkToken =
"SELECT id FROM Tokens WHERE userId=" + results[0].user_id + "";
conn.query(checkToken, (err, results) => {
if (err) throw err;
if (results.length == 1) {
conn.query("UPDATE Tokens SET token = '" + refreshToken + "', updatedAt = '" + datetime + "' WHERE id = " + results[0].id + ";", (err, _) => {
if (err) throw err;
console.log("user token successfully updated!")
})
} else {
let insertToken =
"INSERT INTO Tokens VALUES (0," + userId + ",'" + refreshToken + "','" + datetime + "','" + datetime + "')";
conn.query(insertToken, (err, _) => {
if (err) throw err;
console.log("user token inserted successfully!")
})
}
})
res.setHeader("content-type", "application/json");
res.send(JSON.stringify({status: 200, error: null, response: data}));
} else {
res.setHeader("content-type", "application/json");
res.send(
JSON.stringify({status: 401, error: "Unauthorized", response: []})
);
}
});
});
app.post("/verify", (req, res) => {
const token = req.body.token;
//const tokenVerify = verify(token, process.env.JWT_SECRET_KEY);
jwt.verify(token, process.env.JWT_SECRET_KEY, (err, payload) => {
if (!err) {
res.setHeader("content-type", "application/json");
res.send(
JSON.stringify({status: 200, error: null, response: payload})
);
} else {
res.setHeader("content-type", "application/json");
res.status(401)
res.send(
JSON.stringify({
status: 'error',
error: err,
})
);
}
});
});
// functions
function createJwt(userId) {
let jwtSecretKey = process.env.JWT_SECRET_KEY;
let data = {
iss: process.env.ISS,
//exp: now + 1000
//exp: now + 1000 * 60 * 60 * 24, // satu hari (24 jam)
userId,
};
const token = jwt.sign(data, jwtSecretKey, {expiresIn: '2h'});
return token;
}
//Server listening
app.listen(PORT, () => {
console.log("Server started on port " + PORT + "...");
});