Last active
May 9, 2022 21:30
-
-
Save Ewerton/c997eb4855183696ae825696332a67d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { map, Observable, of, switchMap } from 'rxjs'; | |
import { AuthenticatedResult, OidcClientNotification, OidcSecurityService, OpenIdConfiguration, UserDataResult } from 'angular-auth-oidc-client'; | |
import { flatten } from '@angular/compiler'; | |
import { IAuthState } from './IAuthState'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthService { | |
public configuration$: Observable<OpenIdConfiguration>; | |
public userDataChanged$: Observable<OidcClientNotification<any>>; | |
private userData$: Observable<UserDataResult>; | |
private dadosEndp = null; | |
constructor(public oidcSecurityService: OidcSecurityService, private httpClient: HttpClient) { | |
this.configuration$ = this.oidcSecurityService.getConfiguration(); | |
this.userData$ = this.oidcSecurityService.userData$; | |
} | |
public getUserObservable(): Observable<UserDataResult> { | |
this.userData$.subscribe({ | |
next: (libData) => { | |
this.estaAutenticado().subscribe((estaAutenticado) => { | |
if (estaAutenticado) { | |
if (!libData.userData) { | |
this.refreshSession(); | |
} | |
} | |
}); | |
}, | |
error: (err: HttpErrorResponse) => { | |
console.log(err.message); | |
return null; | |
}, | |
}); | |
return this.userData$; | |
} | |
public getUser(): any { | |
// Parece existir um bug na biblioteca angular-auth-oidc-client onde o userData$, em algumas situações não é carregado. | |
// Percebi que se chamarmos o refreshSession() os dados de userData$ são preenchidos, então, para garantir que esta função não vai falhar | |
// chamo o refreshSession() sempre que userData$ esta nulo. | |
// Optei também por não usar Observable nestes casos visto que, uma vez que o usuário está logado, seus dados não vão mudar. Podemos revisar isso no futuro. | |
let temDadoNaLib = false; | |
let dataToReturn; | |
this.userData$.subscribe({ | |
next: (libData) => { | |
this.estaAutenticado().subscribe((estaAutenticado) => { | |
if (estaAutenticado) { | |
if (!libData.userData) { | |
this.refreshSession(); | |
temDadoNaLib = false; | |
} | |
else { | |
temDadoNaLib = true; | |
console.log('libData.userData:' + JSON.stringify(libData.userData)); | |
dataToReturn = libData.userData | |
} | |
} | |
}); | |
}, | |
error: (err: HttpErrorResponse) => { | |
console.log(err.message); | |
return null; | |
}, | |
}); | |
if (!temDadoNaLib) { | |
let dadoEndpoint = this.requestDataAndWait(); | |
return dadoEndpoint; | |
} | |
return dataToReturn; | |
} | |
async requestDataAndWait() { | |
let httpData = await this.getDataSynchronous(); | |
return httpData; | |
} | |
getDataSynchronous() { | |
return this.httpClient.get('https://localhost:5001/connect/userinfo').toPromise(); | |
} | |
public login() { | |
const authOptions = { | |
customParams: { | |
ParamCustomizado: 'MeuParametro', // Caso seja necessário passar parametros de URL para o Servidor de Identidade | |
}, | |
/* urlHandler: () => { }, */ // Não sei para que serve | |
/* redirectUrl: "/UmaURL" */ // Caso seja necessário sobrescrever a redirect URL definida no auth.config.modulo.ts (obs: essa URL tem que estar previamente cadastrada no Servidor de Autenticação (Config,cs)) | |
}; | |
// Salva um objeto do tipo State contendo a URL atual, assim, quando o usuário voltar da autenticação ele pode ser redirecionado para onde estava | |
const state: IAuthState = { UrlAntesLogin: window.location.href }; | |
this.oidcSecurityService.setState(JSON.stringify(state)).subscribe((state) => { | |
//console.log('State: ' + state) | |
}); | |
// Faz um redirect para o Servidor de Identidade para que o usuário faça login lá! | |
this.oidcSecurityService.authorize(null, authOptions); | |
} | |
public logout() { | |
const authOptions = { | |
customParams: { | |
ParamCustomizado: 'MeuParametro', // Caso seja necessário passar parametros de URL para o Servidor de Identidade | |
}, | |
//urlHandler: () => { }, | |
}; | |
// Faz um redirect para o Servidor de Identidade para que o usuário faça logoff lá. | |
this.oidcSecurityService.logoff(null, authOptions); | |
} | |
public estaAutenticado(): Observable<boolean> { | |
return this.oidcSecurityService.isAuthenticated$.pipe(map((result: AuthenticatedResult) => { return result.isAuthenticated })); | |
} | |
public getAuthState(): IAuthState { | |
let stateObj: IAuthState | |
var state = this.oidcSecurityService.getState().subscribe( | |
(state) => { | |
try { | |
stateObj = JSON.parse(state); | |
} catch (e) { | |
//window.location.href = "/"; | |
} | |
//console.log('State: ' + state); | |
}); | |
return stateObj; | |
} | |
public getAccessToken(): Observable<string> { | |
return this.oidcSecurityService.getAccessToken(); | |
} | |
public refreshSession() { | |
this.oidcSecurityService | |
.forceRefreshSession() | |
.subscribe((result) => console.log(result)); | |
} | |
public refreshSessionPromise() { | |
return this.oidcSecurityService | |
.forceRefreshSession().toPromise(); | |
//.subscribe((result) => console.log(result)); | |
} | |
public logoffAndRevokeTokens() { | |
const authOptions = { | |
customParams: { | |
ParamCustomizado: 'MeuParametro', // Caso seja necessário passar parametros de URL para o Servidor de Identidade | |
}, | |
//urlHandler: () => { }, | |
}; | |
this.oidcSecurityService | |
.logoffAndRevokeTokens(null, authOptions) | |
.subscribe((result) => console.log(result)); | |
} | |
public revokeRefreshToken() { | |
this.oidcSecurityService | |
.revokeRefreshToken() | |
.subscribe((result) => console.log(result)); | |
} | |
public revokeAccessToken() { | |
this.oidcSecurityService | |
.revokeAccessToken() | |
.subscribe((result) => console.log(result)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment