-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdao.js
84 lines (77 loc) · 2.79 KB
/
dao.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
const { errorWithCode } = require('./util');
class Dao {
constructor(connection) {
this.db = connection;
this.db.connect();
}
getClient(client_id) {
return new Promise((resolve, reject) => {
const sql = `SELECT * FROM auth.oauth_clients WHERE client_id = ?`;
this.db.query(sql, [client_id], (error, rows) => {
if (error) {
reject(errorWithCode(error));
} else {
resolve(rows.length ? rows[0] : null);
}
});
});
}
loginExists(username) {
return new Promise((resolve, reject) => {
const sql = `SELECT COUNT(*) AS cnt FROM auth.users WHERE login = ?`;
this.db.query(sql, [username], (error, rows) => {
if (error) {
reject(errorWithCode(error));
} else {
resolve(rows[0].cnt > 0);
}
});
});
}
getUser(username, password) {
return new Promise((resolve, reject) => {
const sql = `SELECT u.*
FROM auth.users u
INNER JOIN auth.passwords p ON p.password_id = u.password_id
WHERE u.login = ?
AND p.password_hash = SHA2(?, 256)`;
this.db.query(sql, [username, password], (error, rows) => {
if (error) {
reject(errorWithCode(error));
} else {
resolve(rows.length ? rows[0] : null);
}
});
});
}
getUserConsent(user, client_id) {
return new Promise((resolve, reject) => {
const sql = `SELECT *
FROM auth.users_clients uc
WHERE uc.user_id = ? AND uc.client_id = ?`;
this.db.query(sql, [user.user_id, client_id], (error, rows) => {
if (error) {
reject(errorWithCode(error));
} else {
resolve(!!rows.length);
}
});
});
}
addUserConsent(username, client_id) {
return new Promise((resolve, reject) => {
const sql = `INSERT INTO auth.users_clients (user_id, client_id)
SELECT user_id, ?
FROM auth.users u
WHERE u.login = ?`;
this.db.query(sql, [client_id, username], (error, rows) => {
if (error) {
reject(errorWithCode(error));
} else {
resolve(true);
}
});
});
}
}
module.exports = Dao;