1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | const { HTTPMethod, LogLevel } = require('./Constants');
|
17 | const { Endpoints, isNullOrUndefined } = require('./Utils');
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | class Authentication {
|
23 | constructor(cliManager) {
|
24 | this.cliManager = cliManager;
|
25 | this._currentUser = null;
|
26 | }
|
27 |
|
28 | getCurrentUser() {
|
29 | return this._currentUser;
|
30 | }
|
31 |
|
32 | setCurrentUser({ email, token, host }) {
|
33 | this._currentUser = {
|
34 | email,
|
35 | token,
|
36 | host
|
37 | };
|
38 | }
|
39 |
|
40 | hasCurrentUser() {
|
41 | return this._currentUser && this._currentUser.token;
|
42 | }
|
43 |
|
44 | login(email, password, MFAToken, host, done) {
|
45 | const data = {
|
46 | email,
|
47 | password
|
48 | };
|
49 |
|
50 | if (!isNullOrUndefined(MFAToken)) {
|
51 | data.twoFactorToken = MFAToken;
|
52 | }
|
53 |
|
54 | this.cliManager.sendRequest(
|
55 | {
|
56 | data,
|
57 | host,
|
58 | endpoint: Endpoints.session(),
|
59 | method: HTTPMethod.POST
|
60 | },
|
61 | (err, result) => {
|
62 | if (err) {
|
63 | return done(err, result);
|
64 | }
|
65 |
|
66 | this.setCurrentUser({
|
67 | host,
|
68 | email: data.email,
|
69 | token: result.token
|
70 | });
|
71 |
|
72 | done(null, result);
|
73 | }
|
74 | );
|
75 | }
|
76 |
|
77 | logout(done) {
|
78 | if (!this.hasCurrentUser()) {
|
79 | return setImmediate(() => done());
|
80 | }
|
81 |
|
82 | const options = {
|
83 | endpoint: Endpoints.session(),
|
84 | method: HTTPMethod.DELETE
|
85 | };
|
86 |
|
87 | this.cliManager.sendRequest(options, (err) => {
|
88 | this._currentUser = null;
|
89 | if (!err) {
|
90 | this.cliManager.log(LogLevel.DEBUG, 'Logged out current user.');
|
91 | }
|
92 |
|
93 | done(err);
|
94 | });
|
95 | }
|
96 | }
|
97 |
|
98 | module.exports = Authentication;
|