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 { HttpClient, HttpHeaders } from '@angular/common/http'
import { Observable, BehaviorSubject, from, throwError, of } from 'rxjs'
import { map, catchError } from 'rxjs/operators'
import { Observable, of } from 'rxjs'
import { map } from 'rxjs/operators'
import { User } from '../_models/user'
import { RoleReadNoUsers, ApiService, Token } from '../openapi'
import { RoleReadNoUsers, ApiService, Token, UserRead } from '../openapi'
import { BootstrapService } from './bootstrap.service'
import { ConfigService } from './config.service'
// interface AuthResponse {
// access_token: string,
// roles: string[]
// }
@Injectable()
export class AuthenticationService {
user = new BehaviorSubject<User>(undefined)
user$ = this.user.asObservable()
roles: RoleReadNoUsers[] = []
constructor(
private _http: HttpClient,
public api: ApiService,
public bootstrapService: BootstrapService,
public configService: ConfigService,
) {
// 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> {
if (!this.user.value) {
return from([false])
}
let body = JSON.stringify({
token: this.user.value.token,
})
return this._http.post(
'/auth/isLoggedIn',
body,
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
).pipe(
map(resp => true),
catchError(
err => {
const userName = this.user.value['userName']
this.user.next(undefined)
this.roles = []
localStorage.removeItem('user')
return throwError(
() => new Error('Session of user "' + userName + '" expired.')
)
}
)
)
return this.configService.conf.pipe(map(
conf => !!conf.bsData?.user
))
// if (!this.user.value) {
// return from([false])
// }
// let body = JSON.stringify({
// token: this.user.value.token,
// })
// return this._http.post(
// '/auth/isLoggedIn',
// body,
// {
// headers: new HttpHeaders({ 'Content-Type': 'application/json' })
// }
// ).pipe(
// map(resp => true),
// catchError(
// err => {
// const userName = this.user.value['userName']
// 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> {
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()
// formData.set('username', userName)
// formData.set('password', password)
@ -70,33 +64,10 @@ export class AuthenticationService {
}).pipe(map(
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(
bsData => this.configService.setConf(bsData)
)
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 = []
// Tell server that the user has logged out
this.api.logoutApiLogoutGet().subscribe()
if (has_token) {
this._http.get('/api/logout').subscribe(response => {})
localStorage.removeItem('token')
}
this.bootstrapService.get().subscribe(
@ -125,11 +96,16 @@ export class AuthenticationService {
logoutAdmin(): void {
}
getUser(): Observable<UserRead> {
return this.configService.conf.pipe(map(
conf => conf.bsData?.user
))
}
isAuthorized(roles: string[]): Observable<boolean> {
// 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.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(
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';*/
:host > div {
padding: 1em;
}
h1 {
text-align: center;
}
.emph {
font-weight: bold;
}

View file

@ -1,9 +1,25 @@
<mat-card appearance="outlined">
<mat-card-title>Gisaf admin/control center</mat-card-title>
<mat-card-content>
<div>
<h1>Gisaf admin/control center</h1>
<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>
This is the adminstration area: baskets for importing files,
tools for the management of the database...
You're logged in as: <span class='emph'>{{ user.username }}</span> ({{ user.email }}, #{{ user.id }}).
</p>
</mat-card-content>
</mat-card>
<p>
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 { ConfigService } from '../../_services/config.service'
import { BootstrapService } from '../../_services/bootstrap.service'
import { AuthenticationService } from '../../_services/authentication.service'
@Component({
selector: 'gisaf-admin-home',
templateUrl: './admin-home.component.html',
styleUrls: ['./admin-home.component.css']
})
export class AdminHomeComponent {}
export class AdminHomeComponent {
constructor(
public configService: ConfigService,
public bootsrtapService: BootstrapService,
public authenticationService: AuthenticationService,
) {}
}