This repository has been archived by the owner on Mar 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
91 lines (78 loc) · 2.25 KB
/
db.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
const rdb = require("rethinkdb")
module.exports = class Database {
async connect({host = 'localhost', port, user, password, database}) {
let err, conn = await rdb.connect({host, port, user, password})
if(err) return this.onError(err)
console.log('[DB]', 'Connected')
if(database) conn.use(database)
conn.on('close', this.onClose.bind(this));
conn.on('timeout', this.onTimeout.bind(this));
this.conn = conn
this.host = host
this.port = port
this.user = user
this.password = password
this.database = database
}
get r() {
return rdb
}
async ticketValid(profile, ticket) {
try{
let data = await rdb.db('Turquoise').table('tickets').get(ticket).run(this.conn)
if(data.profile !== profile) return false
if(data.expire < Date.now()) {
await rdb.db('Turquoise').table('tickets').get(ticket).delete().run(this.conn)
return false
}
return true
} catch (e) {
return false
}
}
getTicket(ticket) {
return rdb.db('Turquoise').table('tickets').get(ticket).run(this.conn)
}
addToken(token) {
rdb.table('apitokens').insert(token).run(this.conn)
}
async valid(token) {
try{
let data = await (await rdb.table('apitokens').filter({ token }).run(this.conn)).toArray()
return data[0]
} catch (e) {
return false
}
}
hasPerm(perm, token) {
let okay = false
if(this.prefix) perm = this.prefix + '.' + perm
token.permissions.map(p => {
if(p === perm) return okay = true
if(perm.startsWith(p) && ['.', undefined].includes(perm.slice(p.length)[0])) return okay = true
})
return okay
}
getAuth(id) {
return rdb.table('apitokens').get(id).run(this.conn)
}
replaceToken(id, token) {
return rdb.table('apitokens').get(id).update({ token }).run(this.conn)
}
async reconnect() {
this.conn = await this.conn.reconnect({noreplyWait: false})
conn.on('close', this.onClose.bind(this));
conn.on('timeout', this.onTimeout.bind(this));
}
onError(err) {
console.log('[DB]', 'Error', err)
}
async onClose() {
console.log('[DB]', 'Closed')
await this.reconnect()
}
async onTimeout() {
console.log('[DB]', 'Connection Timeout')
await this.reconnect()
}
}