session guard

This commit is contained in:
Bastian Wagner
2024-09-05 12:01:05 +02:00
parent 767e3cbb41
commit fe6b8a8984
2 changed files with 81 additions and 1 deletions

View File

@@ -2,9 +2,10 @@ import { Routes } from '@angular/router';
import { LoginComponent } from './auth/login/login.component';
import { RegisterComponent } from './auth/register/register.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { SessionKeyGuard } from './core/guards/session-key.guard';
export const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'login', component: LoginComponent, canActivate: [SessionKeyGuard] },
{ path: 'register', component: RegisterComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: '', component: LoginComponent },

View File

@@ -0,0 +1,79 @@
import { HttpClient } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, Router } from "@angular/router";
import { HotToastService } from "@ngxpert/hot-toast";
import { UserService } from "../../auth/user.service";
import { User } from "../../model/user.interface";
@Injectable({
providedIn: 'root'
})
export class SessionKeyGuard {
public isLoading = false;
private http = inject(HttpClient);
private toast = inject(HotToastService);
private userService = inject(UserService);
private router = inject(Router);
private redirectUri;
private client_id;
async canActivate(route: ActivatedRouteSnapshot):
Promise<boolean> {
this.isLoading = true;
const success = await this.loginWithSessionId(route);
console.log("LOGIN: ", success)
return success;
}
async loginWithSessionId(route: ActivatedRouteSnapshot): Promise<boolean> {
return new Promise(resolve => {
const params = (route.queryParamMap as any)["params"];
this.redirectUri = params.redirect_uri;
this.client_id = params.client_id;
const id = window.localStorage.getItem("auth_session_key");
if (!id ||id.length < 2) { return resolve(true); }
const url = this.client_id ? 'api/auth/login-with-session-id' : 'api/auth/login-with-session-id/userlogin'
this.http.post(url, {
code: id,
client_id: this.client_id
}).pipe(
this.toast.observe({
loading: 'Logging in...',
success: 'Logged in',
error: 'Invalid session, please log in with your credentials'
})
).subscribe({
next: (data) => {
this.handleLoginData(data, resolve);
},
error: (error) => {
console.error(error);
}
});
})
}
private handleLoginData(data: any, resolve: any) {
if (data["code"] != null) {
if (this.redirectUri) {
location.href = this.redirectUri + "?code=" + data["code"];
resolve(true);
}
} else if (data["id"] != null) {
this.userService.user = data as User;
resolve(false);
this.navigateToDashboard();
}
}
private navigateToDashboard() {
this.router.navigateByUrl("/dashboard");
}
}