|
| 1 | +import { Injectable } from '@angular/core'; |
| 2 | +import { AppConfigService } from './app-config.service'; |
| 3 | +import { wait } from '../util/util'; |
| 4 | + |
| 5 | +/** |
| 6 | + * This service emulates an Authentication Service. |
| 7 | + */ |
| 8 | +@Injectable() |
| 9 | +export class AuthService { |
| 10 | + // data |
| 11 | + |
| 12 | + |
| 13 | + constructor(public appConfig: AppConfigService) { } |
| 14 | + |
| 15 | + /** |
| 16 | + * Returns true if the user is currently authenticated, else false |
| 17 | + */ |
| 18 | + isAuthenticated() { |
| 19 | + return !!this.appConfig.emailAddress; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Fake authentication function that returns a promise that is either resolved or rejected. |
| 24 | + * |
| 25 | + * Given a username and password, checks that the username matches one of the known |
| 26 | + * usernames (this.usernames), and that the password matches 'password'. |
| 27 | + * |
| 28 | + * Delays 800ms to simulate an async REST API delay. |
| 29 | + */ |
| 30 | + authenticate(username, password) { |
| 31 | + const appConfig = this.appConfig; |
| 32 | + |
| 33 | + // checks if the username is one of the known usernames, and the password is 'password' |
| 34 | + const checkCredentials = () => new Promise<string>((resolve, reject) => { |
| 35 | + const validUsername = this.usernames.indexOf(username) !== -1; |
| 36 | + const validPassword = password === 'password'; |
| 37 | + |
| 38 | + return (validUsername && validPassword) ? resolve(username) : reject('Invalid username or password'); |
| 39 | + }); |
| 40 | + |
| 41 | + return wait(800) |
| 42 | + .then(checkCredentials) |
| 43 | + .then((authenticatedUser) => { |
| 44 | + appConfig.emailAddress = authenticatedUser; |
| 45 | + appConfig.save(); |
| 46 | + }); |
| 47 | + } |
| 48 | + |
| 49 | + /** Logs the current user out */ |
| 50 | + logout() { |
| 51 | + this.appConfig.emailAddress = undefined; |
| 52 | + this.appConfig.save(); |
| 53 | + } |
| 54 | +} |
0 commit comments