Users.js
2.64 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 cryptoJs = require("crypto-js");
const express = require("express");
const { pool } = require("../libs/MySQL");
const usersRouter = express.Router();
async function route() {
// (loginID) => null | ID(str)
usersRouter.get("/", async (req, res) => {
console.log("/db/users");
const connection = await pool.getConnection(async (con) => con);
try {
const queryString = `
SELECT ID FROM users us
WHERE us.loginID = '${req.query.loginID}'`;
const [results] = await connection.query(queryString);
res.send(results.length ? results[0].ID.toString() : null);
} catch (e) {
console.log(e);
res.end();
} finally {
connection.release();
}
});
// (loginID, loginPW) => null | "correct"
usersRouter.get("/check", async (req, res) => {
console.log("/db/users/check");
const connection = await pool.getConnection(async (con) => con);
try {
const queryString = `
SELECT loginPW FROM users us
WHERE us.loginID = '${req.query.loginID}'`;
const [results] = await connection.query(queryString);
res.send(results[0].loginPW === req.query.loginPW ? "correct" : null);
} catch (e) {
console.log(e);
res.end();
} finally {
connection.release();
}
});
// (loginID, loginPW, name, ical) => ID
usersRouter.post("/", async (req, res) => {
console.log("post /db/users/");
const connection = await pool.getConnection(async (con) => con);
try {
await connection.beginTransaction();
const hashpw = cryptoJs.SHA256(req.body.loginPW).toString();
let queryString = `
INSERT INTO users
(loginID, loginPW, name, ical)
VALUES ('${req.body.loginID}', '${hashpw}', '${req.body.name}', '${req.body.ical}')`;
await connection.query(queryString);
queryString = `SELECT LAST_INSERT_ID() ID`;
const [results] = await connection.query(queryString);
await connection.commit();
res.send(results[0]);
} catch (e) {
console.log(e);
await connection.rollback();
res.end();
} finally {
connection.release();
}
});
// (ID) => ical
usersRouter.get("/ical", async (req, res) => {
console.log("/db/users/ical");
const connection = await pool.getConnection(async (con) => con);
try {
const queryString = `
SELECT ical FROM users us
WHERE us.ID = '${req.query.ID}'`;
const [results] = await connection.query(queryString);
res.send(results[0]);
} catch (e) {
console.log(e);
res.end();
} finally {
connection.release();
}
});
}
route();
module.exports = usersRouter;