|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | +import React from 'react'; |
| 4 | +import { UserAgentApplication } from 'msal'; |
| 5 | + |
| 6 | +import { config } from './Config'; |
| 7 | +import { getUserDetails } from './GraphService'; |
| 8 | + |
| 9 | +export interface AuthComponentProps { |
| 10 | + error: any; |
| 11 | + isAuthenticated: boolean; |
| 12 | + user: any; |
| 13 | + login: Function; |
| 14 | + logout: Function; |
| 15 | + getAccessToken: Function; |
| 16 | + setError: Function; |
| 17 | +} |
| 18 | + |
| 19 | +interface AuthProviderState { |
| 20 | + error: any; |
| 21 | + isAuthenticated: boolean; |
| 22 | + user: any; |
| 23 | +} |
| 24 | + |
| 25 | +export default function withAuthProvider<T extends React.Component<AuthComponentProps>> |
| 26 | + (WrappedComponent: new(props: AuthComponentProps, context?: any) => T): React.ComponentClass { |
| 27 | + return class extends React.Component<any, AuthProviderState> { |
| 28 | + private userAgentApplication: UserAgentApplication; |
| 29 | + |
| 30 | + constructor(props: any) { |
| 31 | + super(props); |
| 32 | + this.state = { |
| 33 | + error: null, |
| 34 | + isAuthenticated: false, |
| 35 | + user: {} |
| 36 | + }; |
| 37 | + |
| 38 | + // Initialize the MSAL application object |
| 39 | + this.userAgentApplication = new UserAgentApplication({ |
| 40 | + auth: { |
| 41 | + clientId: config.appId, |
| 42 | + redirectUri: config.redirectUri |
| 43 | + }, |
| 44 | + cache: { |
| 45 | + cacheLocation: "sessionStorage", |
| 46 | + storeAuthStateInCookie: true |
| 47 | + } |
| 48 | + }); |
| 49 | + } |
| 50 | + |
| 51 | + componentDidMount() { |
| 52 | + // If MSAL already has an account, the user |
| 53 | + // is already logged in |
| 54 | + var account = this.userAgentApplication.getAccount(); |
| 55 | + |
| 56 | + if (account) { |
| 57 | + // Enhance user object with data from Graph |
| 58 | + this.getUserProfile(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + render() { |
| 63 | + return <WrappedComponent |
| 64 | + error = { this.state.error } |
| 65 | + isAuthenticated = { this.state.isAuthenticated } |
| 66 | + user = { this.state.user } |
| 67 | + login = { () => this.login() } |
| 68 | + logout = { () => this.logout() } |
| 69 | + getAccessToken = { (scopes: string[]) => this.getAccessToken(scopes)} |
| 70 | + setError = { (message: string, debug: string) => this.setErrorMessage(message, debug)} |
| 71 | + {...this.props} {...this.state} />; |
| 72 | + } |
| 73 | + |
| 74 | + async login() { |
| 75 | + try { |
| 76 | + // Login via popup |
| 77 | + await this.userAgentApplication.loginPopup( |
| 78 | + { |
| 79 | + scopes: config.scopes, |
| 80 | + prompt: "select_account" |
| 81 | + }); |
| 82 | + // After login, get the user's profile |
| 83 | + await this.getUserProfile(); |
| 84 | + } |
| 85 | + catch(err) { |
| 86 | + this.setState({ |
| 87 | + isAuthenticated: false, |
| 88 | + user: {}, |
| 89 | + error: this.normalizeError(err) |
| 90 | + }); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + logout() { |
| 95 | + this.userAgentApplication.logout(); |
| 96 | + } |
| 97 | + |
| 98 | + async getAccessToken(scopes: string[]): Promise<string> { |
| 99 | + try { |
| 100 | + // Get the access token silently |
| 101 | + // If the cache contains a non-expired token, this function |
| 102 | + // will just return the cached token. Otherwise, it will |
| 103 | + // make a request to the Azure OAuth endpoint to get a token |
| 104 | + var silentResult = await this.userAgentApplication.acquireTokenSilent({ |
| 105 | + scopes: scopes |
| 106 | + }); |
| 107 | + |
| 108 | + return silentResult.accessToken; |
| 109 | + } catch (err) { |
| 110 | + // If a silent request fails, it may be because the user needs |
| 111 | + // to login or grant consent to one or more of the requested scopes |
| 112 | + if (this.isInteractionRequired(err)) { |
| 113 | + var interactiveResult = await this.userAgentApplication.acquireTokenPopup({ |
| 114 | + scopes: scopes |
| 115 | + }); |
| 116 | + |
| 117 | + return interactiveResult.accessToken; |
| 118 | + } else { |
| 119 | + throw err; |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + // <getUserProfileSnippet> |
| 125 | + async getUserProfile() { |
| 126 | + try { |
| 127 | + var accessToken = await this.getAccessToken(config.scopes); |
| 128 | + |
| 129 | + if (accessToken) { |
| 130 | + // Get the user's profile from Graph |
| 131 | + var user = await getUserDetails(accessToken); |
| 132 | + this.setState({ |
| 133 | + isAuthenticated: true, |
| 134 | + user: { |
| 135 | + displayName: user.displayName, |
| 136 | + email: user.mail || user.userPrincipalName |
| 137 | + }, |
| 138 | + error: null |
| 139 | + }); |
| 140 | + } |
| 141 | + } |
| 142 | + catch(err) { |
| 143 | + this.setState({ |
| 144 | + isAuthenticated: false, |
| 145 | + user: {}, |
| 146 | + error: this.normalizeError(err) |
| 147 | + }); |
| 148 | + } |
| 149 | + } |
| 150 | + // </getUserProfileSnippet> |
| 151 | + |
| 152 | + setErrorMessage(message: string, debug: string) { |
| 153 | + this.setState({ |
| 154 | + error: {message: message, debug: debug} |
| 155 | + }); |
| 156 | + } |
| 157 | + |
| 158 | + normalizeError(error: string | Error): any { |
| 159 | + var normalizedError = {}; |
| 160 | + if (typeof(error) === 'string') { |
| 161 | + var errParts = error.split('|'); |
| 162 | + normalizedError = errParts.length > 1 ? |
| 163 | + { message: errParts[1], debug: errParts[0] } : |
| 164 | + { message: error }; |
| 165 | + } else { |
| 166 | + normalizedError = { |
| 167 | + message: error.message, |
| 168 | + debug: JSON.stringify(error) |
| 169 | + }; |
| 170 | + } |
| 171 | + return normalizedError; |
| 172 | + } |
| 173 | + |
| 174 | + isInteractionRequired(error: Error): boolean { |
| 175 | + if (!error.message || error.message.length <= 0) { |
| 176 | + return false; |
| 177 | + } |
| 178 | + |
| 179 | + return ( |
| 180 | + error.message.indexOf('consent_required') > -1 || |
| 181 | + error.message.indexOf('interaction_required') > -1 || |
| 182 | + error.message.indexOf('login_required') > -1 |
| 183 | + ); |
| 184 | + } |
| 185 | + } |
| 186 | +} |
0 commit comments