UNPKG

2.46 kBJavaScriptView Raw
1/**
2 * Copyright (c) 2018, Kinvey, Inc. All rights reserved.
3 *
4 * This software is licensed to you under the Kinvey terms of service located at
5 * http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this
6 * software, you hereby accept such terms of service (and any agreement referenced
7 * therein) and agree that you have read, understand and agree to be bound by such
8 * terms of service and are of legal age to agree to such terms with Kinvey.
9 *
10 * This software contains valuable confidential and proprietary information of
11 * KINVEY, INC and is subject to applicable licensing agreements.
12 * Unauthorized reproduction, transmission or distribution of this file and its
13 * contents is a violation of applicable laws.
14 */
15
16const { HTTPMethod, LogLevel } = require('./Constants');
17const { Endpoints, isNullOrUndefined } = require('./Utils');
18
19/**
20 * Handles authentication: set/unset current user, login/logout.
21 */
22class 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
98module.exports = Authentication;