Admin home: show logged in user info

This commit is contained in:
phil 2024-03-27 17:14:19 +05:30
parent e38d84f37a
commit 96331e2450
4 changed files with 86 additions and 74 deletions

View file

@ -1,66 +1,60 @@
import { Injectable } from '@angular/core' import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders } from '@angular/common/http' import { Observable, of } from 'rxjs'
import { Observable, BehaviorSubject, from, throwError, of } from 'rxjs' import { map } from 'rxjs/operators'
import { map, catchError } from 'rxjs/operators'
import { User } from '../_models/user' import { RoleReadNoUsers, ApiService, Token, UserRead } from '../openapi'
import { RoleReadNoUsers, ApiService, Token } from '../openapi'
import { BootstrapService } from './bootstrap.service' import { BootstrapService } from './bootstrap.service'
import { ConfigService } from './config.service' import { ConfigService } from './config.service'
// interface AuthResponse {
// access_token: string,
// roles: string[]
// }
@Injectable() @Injectable()
export class AuthenticationService { export class AuthenticationService {
user = new BehaviorSubject<User>(undefined)
user$ = this.user.asObservable()
roles: RoleReadNoUsers[] = [] roles: RoleReadNoUsers[] = []
constructor( constructor(
private _http: HttpClient,
public api: ApiService, public api: ApiService,
public bootstrapService: BootstrapService, public bootstrapService: BootstrapService,
public configService: ConfigService, public configService: ConfigService,
) { ) {
// set token if saved in local storage // set token if saved in local storage
this.user.next(<User>JSON.parse(localStorage.getItem('user'))) // this.user.next(<User>JSON.parse(localStorage.getItem('user')))
} }
isLoggedIn() : Observable<boolean> { isLoggedIn() : Observable<boolean> {
if (!this.user.value) { return this.configService.conf.pipe(map(
return from([false]) conf => !!conf.bsData?.user
} ))
let body = JSON.stringify({
token: this.user.value.token, // if (!this.user.value) {
}) // return from([false])
return this._http.post( // }
'/auth/isLoggedIn', // let body = JSON.stringify({
body, // token: this.user.value.token,
{ // })
headers: new HttpHeaders({ 'Content-Type': 'application/json' }) // return this._http.post(
} // '/auth/isLoggedIn',
).pipe( // body,
map(resp => true), // {
catchError( // headers: new HttpHeaders({ 'Content-Type': 'application/json' })
err => { // }
const userName = this.user.value['userName'] // ).pipe(
this.user.next(undefined) // map(resp => true),
this.roles = [] // catchError(
localStorage.removeItem('user') // err => {
return throwError( // const userName = this.user.value['userName']
() => new Error('Session of user "' + userName + '" expired.') // this.user.next(undefined)
) // this.roles = []
} // localStorage.removeItem('user')
) // return throwError(
) // () => new Error('Session of user "' + userName + '" expired.')
// )
// }
// )
// )
} }
login(username: string, password: string): Observable<Token> { login(username: string, password: string): Observable<Token> {
const headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'}) // const headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'})
// var formData: any = new URLSearchParams() // var formData: any = new URLSearchParams()
// formData.set('username', userName) // formData.set('username', userName)
// formData.set('password', password) // formData.set('password', password)
@ -70,33 +64,10 @@ export class AuthenticationService {
}).pipe(map( }).pipe(map(
token => { token => {
localStorage.setItem('token', token.access_token) localStorage.setItem('token', token.access_token)
// store jwt token in local storage to keep user logged in between page refreshes
// localStorage.setItem('user',
// JSON.stringify({
// userName: username,
// token: token,
// roles: response.roles,
// })
// )
this.bootstrapService.get().subscribe( this.bootstrapService.get().subscribe(
bsData => this.configService.setConf(bsData) bsData => this.configService.setConf(bsData)
) )
return token return token
// this.roles = response.roles
// Notify
// this.user.next(new User(userName, token))
// return true to indicate successful login
// return true
// } else {
// this.user.next(undefined)
// this.roles = []
// // return false to indicate failed login
// // return false
// }
// return response
} }
)) ))
} }
@ -112,8 +83,8 @@ export class AuthenticationService {
// this.roles = [] // this.roles = []
// Tell server that the user has logged out // Tell server that the user has logged out
this.api.logoutApiLogoutGet().subscribe()
if (has_token) { if (has_token) {
this._http.get('/api/logout').subscribe(response => {})
localStorage.removeItem('token') localStorage.removeItem('token')
} }
this.bootstrapService.get().subscribe( this.bootstrapService.get().subscribe(
@ -125,11 +96,16 @@ export class AuthenticationService {
logoutAdmin(): void { logoutAdmin(): void {
} }
getUser(): Observable<UserRead> {
return this.configService.conf.pipe(map(
conf => conf.bsData?.user
))
}
isAuthorized(roles: string[]): Observable<boolean> { isAuthorized(roles: string[]): Observable<boolean> {
// Return true if at least one role in given list matches one role of the authenticated user // Return true if at least one role in given list matches one role of the authenticated user
if (roles.length == 0) return of(true) if (roles.length == 0) return of(true)
if (roles.every(role => role == undefined)) return of(true) if (roles.every(role => role == undefined)) return of(true)
// return this.roles.filter(value => -1 !== roles.indexOf(value.name)).length > 0
return this.configService.conf.pipe(map( return this.configService.conf.pipe(map(
conf => conf.bsData?.user?.roles?.filter(value => -1 !== roles.indexOf(value.name)).length > 0 conf => conf.bsData?.user?.roles?.filter(value => -1 !== roles.indexOf(value.name)).length > 0
)) ))

View file

@ -1 +1,12 @@
/*@import '../node_modules/@angular/material/prebuilt-themes/purple-green.css';*/ /*@import '../node_modules/@angular/material/prebuilt-themes/purple-green.css';*/
:host > div {
padding: 1em;
}
h1 {
text-align: center;
}
.emph {
font-weight: bold;
}

View file

@ -1,9 +1,25 @@
<mat-card appearance="outlined"> <div>
<mat-card-title>Gisaf admin/control center</mat-card-title> <h1>Gisaf admin/control center</h1>
<mat-card-content> <p>
This is the adminstration area: baskets for importing files,
tools for the management of the database...
</p>
<div *ngIf="authenticationService.getUser() | async as user; else anonymous">
<p> <p>
This is the adminstration area: baskets for importing files, You're logged in as: <span class='emph'>{{ user.username }}</span> ({{ user.email }}, #{{ user.id }}).
tools for the management of the database...
</p> </p>
</mat-card-content> <p>
</mat-card> Your roles are:
</p>
<ul>
<li *ngFor="let role of user.roles">
{{ role.name }}
</li>
</ul>
</div>
</div>
<ng-template #anonymous>
<div>You're not logged in.</div>
</ng-template>

View file

@ -1,9 +1,18 @@
import { Component } from '@angular/core' import { Component } from '@angular/core'
import { ConfigService } from '../../_services/config.service'
import { BootstrapService } from '../../_services/bootstrap.service'
import { AuthenticationService } from '../../_services/authentication.service'
@Component({ @Component({
selector: 'gisaf-admin-home', selector: 'gisaf-admin-home',
templateUrl: './admin-home.component.html', templateUrl: './admin-home.component.html',
styleUrls: ['./admin-home.component.css'] styleUrls: ['./admin-home.component.css']
}) })
export class AdminHomeComponent {} export class AdminHomeComponent {
constructor(
public configService: ConfigService,
public bootsrtapService: BootstrapService,
public authenticationService: AuthenticationService,
) {}
}