forked from mxstbr/login-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
71 lines (69 loc) · 2.02 KB
/
auth.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
import request from './fakeRequest';
/**
* Authentication lib
* @type {Object}
*/
var auth = {
/**
* Logs a user in
* @param {string} username The username of the user
* @param {string} password The password of the user
* @param {Function} callback Called after a user was logged in on the remote server
*/
login(username, password, callback) {
// If there is a token in the localStorage, the user already is
// authenticated
if (this.loggedIn()) {
callback(true);
return;
}
// Post a fake request (see below)
request.post('/login', { username, password }, (response) => {
// If the user was authenticated successfully, save a random token to the
// localStorage
if (response.authenticated) {
localStorage.token = response.token;
callback(true);
} else {
// If there was a problem authenticating the user, show an error on the
// form
callback(false, response.error);
}
});
},
/**
* Logs the current user out
*/
logout(callback) {
request.post('/logout', {}, () => {
callback(true);
});
},
/**
* Checks if anybody is logged in
* @return {boolean} True if there is a logged in user, false if there isn't
*/
loggedIn() {
return !!localStorage.token;
},
/**
* Registers a user in the system
* @param {string} username The username of the user
* @param {string} password The password of the user
* @param {Function} callback Called after a user was registered on the remote server
*/
register(username, password, callback) {
// Post a fake request
request.post('/register', { username, password }, (response) => {
// If the user was successfully registered, log them in
if (response.registered === true) {
this.login(username, password, callback);
} else {
// If there was a problem registering, show the error
callback(false, response.error);
}
});
},
onChange() {}
}
module.exports = auth;