microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/extension/appcenter/auth/auth.ts
58lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. |
| 3 | |
| 4 | import * as Q from "q"; |
| 5 | import { SettingsHelper } from "../../../extension/settingsHelper"; |
| 6 | import { createAppCenterClient, getQPromisifiedClientResult } from "../api/index"; |
| 7 | import { Profile, saveUser, deleteUser, getUser } from "../auth/profile/profile"; |
| 8 | import * as models from "../lib/app-center-node-client/models"; |
| 9 | |
| 10 | export default class Auth { |
| 11 | public static getProfile(projectRootPath: string): Q.Promise<Profile | null> { |
| 12 | const profile: Profile | null = getUser(projectRootPath); |
| 13 | if (profile) { |
| 14 | return Q.resolve(profile); |
| 15 | } else { |
| 16 | return Q.resolve(null); |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | public static doTokenLogin(token: string, projectRootPath: string): Q.Promise<Profile | null> { |
| 21 | if (!token) { |
| 22 | return Q.resolve(null); |
| 23 | } |
| 24 | return this.removeLoggedInUser(projectRootPath).then(() => { |
| 25 | return Auth.fetchUserInfoByTokenAndSave(token, projectRootPath).then((profile: Profile) => { |
| 26 | return Q.resolve(profile); |
| 27 | }).catch((e: Error) => { |
| 28 | return Q.resolve(null); |
| 29 | }); |
| 30 | }); |
| 31 | } |
| 32 | |
| 33 | public static doLogout(projectRootPath: string): Q.Promise<void> { |
| 34 | // TODO: Probably we need to delete token from server also? |
| 35 | return this.removeLoggedInUser(projectRootPath); |
| 36 | } |
| 37 | |
| 38 | private static fetchUserInfoByTokenAndSave(token: string, projectRootPath: string): Q.Promise<Profile> { |
| 39 | return Auth.getUserInfo(token).then(userResponse => { |
| 40 | return saveUser(userResponse, { token: token }, projectRootPath).then((profile: Profile) => { |
| 41 | return Q.resolve(profile); |
| 42 | }); |
| 43 | }).catch((e: any) => { |
| 44 | throw e; |
| 45 | }); |
| 46 | } |
| 47 | |
| 48 | private static getUserInfo(token: string): Q.Promise<models.UserProfileResponse> { |
| 49 | const client = createAppCenterClient().fromToken(token, SettingsHelper.getAppCenterAPIEndpoint()); |
| 50 | return getQPromisifiedClientResult(client.account.users.get()); |
| 51 | } |
| 52 | |
| 53 | private static removeLoggedInUser(projectRootPath: string): Q.Promise<void> { |
| 54 | return deleteUser(projectRootPath).then(() => { |
| 55 | return Q.resolve(void 0); |
| 56 | }).catch(() => { }); // Noop, it's ok if deletion fails |
| 57 | } |
| 58 | } |