-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (88 loc) · 2.39 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
const axios = require("axios");
const errors = {
login: {
expired: "Login Expired",
bad: "Bad Login",
failed: "Login Failed",
notStored: "Login Not Stored"
}
}
class LcsClient {
constructor(LcsUrl) {
this.token = null;
this.email = null;
this.validUntil = null;
this.cached_profile = null;
this.raw = axios.create({
baseURL: LcsUrl
});
this.login = new Login(this);
this.profile = new Profile(this);
}
}
class LcsGroup {
constructor(client) {
this.client = client;
}
requireLogin() {
return new Promise((resolve, reject) => {
if (!this.client.login.isValid) {
reject(erros.login.expired);
} else {
resolve(null);
}
})
}
}
class Login extends LcsGroup {
token(email, token) {
return this.client.raw.post("/validate", {
email, token
})
}
password(email, password) {
return this.client.raw.post("/authorize", {
email, password
}).then(res => {
if (res.status === 200 && res.data.statusCode === 200) {
return JSON.parse(res.data.body).auth;
} else if (res.status === 403 || res.data.statusCode === 403) {
throw new Error(errors.login.bad);
} else {
throw new Error(errors.login.failed);
}
}).then(auth => {
this.client.token = auth.token;
this.client.email = auth.email;
this.client.validUntil = new Date(auth.valid_until);
return auth;
})
}
isValid() {
if (this.client.validUntil === null) {
return false;
}
return this.client.validUntil > Date.now()
}
}
class Profile extends LcsGroup {
get() {
return this.requireLogin().then((_) => {
const email = this.client.email;
const token = this.client.token
return this.client.raw.post("/read", {
email,
token,
query: {email}
})
}).then(res => {
const profile = res.data.body[0];
this.client.cached_profile = profile;
return profile;
})
}
}
module.exports = {
LcsClient,
errors
}