From 3dbc562147003789bd610b43bbb6ba5a5bef1180 Mon Sep 17 00:00:00 2001 From: itzMiney Date: Sat, 15 Mar 2025 21:32:19 +0100 Subject: [PATCH] Updated token validation --- src/app/admin/admin.component.ts | 99 +++++++++++++++++------- src/app/login/login.component.ts | 14 +++- src/app/shared/services/auth.service.ts | 9 ++- src/app/shortener/shortener.component.ts | 39 +++++++--- 4 files changed, 118 insertions(+), 43 deletions(-) diff --git a/src/app/admin/admin.component.ts b/src/app/admin/admin.component.ts index dd30b17..c1ddc0d 100644 --- a/src/app/admin/admin.component.ts +++ b/src/app/admin/admin.component.ts @@ -1,13 +1,14 @@ -import {Component, OnInit} from '@angular/core'; +import {Component, OnDestroy, OnInit} from '@angular/core'; import {Router} from '@angular/router'; import {ArticleService} from '../shared/services/article.service'; import {UserService} from '../shared/services/user.service'; import {NgFor, NgIf, NgStyle} from '@angular/common'; -import { Observer} from 'rxjs'; +import {Observer, Subscription, interval} from 'rxjs'; import {FormsModule} from '@angular/forms'; import {DeviceDetectorService} from '../shared/services/device-detector.service'; import {Title} from '@angular/platform-browser'; import {ModalComponent} from '../shared/modal/modal.component'; +import {AuthService} from '../shared/services/auth.service'; @Component({ selector: 'app-admin', @@ -21,7 +22,7 @@ import {ModalComponent} from '../shared/modal/modal.component'; ModalComponent ] }) -export class AdminComponent implements OnInit { +export class AdminComponent implements OnInit, OnDestroy { articles: any[] = []; users: any[] = []; noArticles: boolean = false; @@ -36,50 +37,94 @@ export class AdminComponent implements OnInit { isModalOpen: boolean = false; isViewingArticles: boolean = true; + token: string | null= localStorage.getItem('token'); + tokenValidationInterval: Subscription = new Subscription(); + userData = { username: '', password: '', id: '', }; - token: string | null = localStorage.getItem('token'); - constructor( private articleService: ArticleService, private userService: UserService, private router: Router, private deviceService: DeviceDetectorService, - private titleService: Title + private titleService: Title, + private authService: AuthService ) {} - // Fetch articles from backend ngOnInit() { this.titleService.setTitle('Admin Panel | itzMiney') this.isMobile = this.deviceService.isMobile; - if (!this.token) { + this.checkToken(); + this.loadArticles(); + this.startTokenValidation(); + } + + ngOnDestroy() { + if (this.tokenValidationInterval) { + this.tokenValidationInterval.unsubscribe(); + } + } + + startTokenValidation() { + this.tokenValidationInterval = interval(300000).subscribe(() => { + this.authService.isTokenValid(this.token).subscribe( + (isValid: boolean) => { + if (!isValid) { + console.warn('Token is no longer valid. Logging out.'); + this.navigateToLogin(); + } + }, + (error) => { + console.error('Error validating token:', error); + this.navigateToLogin(); + } + ); + }); + } + + checkToken() { + if (!this.token || !this.isValidToken(this.token)) { + localStorage.removeItem('token'); this.navigateToLogin(); return; } - this.loadArticles(); } - navigateToLogin() { - this.router.navigate(['/login']).then( - (success) => { - if (success) { - console.log('Navigation to login succeeded'); - } else { - console.warn('Navigation to login failed'); - } - }, - (error) => { - console.error('Navigation error:', error); - } - ); + isValidToken(token: string) { + try { + const payload = JSON.parse(atob(token.split('.')[1])); + const expiry = payload.exp * 1000; + + return expiry > Date.now(); + } catch (e) { + console.error('Invalid token format:', e); + return false; + } + } + + async navigateToLogin() { + try { + const currentRoute = this.router.url; + const success = await this.router.navigate(['/login'], { + queryParams: { redirectUrl: currentRoute }, + }); + if (success) { + console.log('Navigation to login succeeded'); + } else { + console.warn('Navigation to login failed'); + } + } catch (error) { + console.error('Navigation error:', error); + } } createArticle(form: any) { - if (!this.token) { + if (!this.token || !this.isValidToken(this.token)) { + localStorage.removeItem('token'); this.navigateToLogin(); return; } @@ -106,10 +151,7 @@ export class AdminComponent implements OnInit { } editArticle(form: any): void { - if (!this.token) { - this.navigateToLogin(); - return; - } + this.checkToken(); const articleId = form.value.editId; @@ -154,7 +196,8 @@ export class AdminComponent implements OnInit { } deleteArticle(form: any): void { - if (!this.token) { + if (!this.token || !this.isValidToken(this.token)) { + localStorage.removeItem('token'); this.navigateToLogin(); return; } diff --git a/src/app/login/login.component.ts b/src/app/login/login.component.ts index 9e668cf..0ba5610 100644 --- a/src/app/login/login.component.ts +++ b/src/app/login/login.component.ts @@ -1,6 +1,6 @@ import {AfterViewInit, Component, Inject, OnDestroy, OnInit, PLATFORM_ID} from '@angular/core'; import {AuthService} from '../shared/services/auth.service'; -import {Router} from '@angular/router'; +import {ActivatedRoute, Router} from '@angular/router'; import {FormsModule} from '@angular/forms'; import {NgIf} from '@angular/common'; import {VantaBackgroundService} from '../shared/services/vanta-background.service'; @@ -24,10 +24,12 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit { errorMessage: string = ''; private readonly elementId = 'vanta-login-bg'; isMobile: boolean = false; + redirectUrl: string = '/admin'; constructor( private authService: AuthService, private router: Router, + private route: ActivatedRoute, private vantaService: VantaBackgroundService, private deviceService: DeviceDetectorService, private titleService: Title, @@ -37,6 +39,13 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit { ngOnInit() { this.titleService.setTitle('Login | itzMiney') this.isMobile = this.deviceService.isMobile; + + this.route.queryParams.subscribe(params => { + if (params['redirectUrl']) { + this.redirectUrl = decodeURIComponent(params['redirectUrl']); + } + }); + if (isPlatformBrowser(this.platformId)) { window.addEventListener('resize', this.onResize.bind(this)); } @@ -46,7 +55,7 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit { const observer = { 'next': (response: any) => { localStorage.setItem('token', response.token); - this.router.navigate(['/admin']).then( + this.router.navigate([this.redirectUrl]).then( (success) => { if (success) { console.log('Navigation to admin succeeded'); @@ -60,7 +69,6 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit { ); }, error: (err: any) => { - // Check if the error response contains a message if (err.error && err.error.message) { this.errorMessage = err.error.message; } else { diff --git a/src/app/shared/services/auth.service.ts b/src/app/shared/services/auth.service.ts index 7f8b92e..b84bd03 100644 --- a/src/app/shared/services/auth.service.ts +++ b/src/app/shared/services/auth.service.ts @@ -1,6 +1,6 @@ import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; -import {Observable, tap} from 'rxjs'; +import {Observable, of, tap} from 'rxjs'; @Injectable({ providedIn: 'root' @@ -22,4 +22,11 @@ export class AuthService { }) ); } + + isTokenValid(token: string | null) { + if (!token) return of(false); + return this.http.get('/api/users', { + headers: { Authorization: `Bearer ${token}` } + }) + } } diff --git a/src/app/shortener/shortener.component.ts b/src/app/shortener/shortener.component.ts index 54b38a8..4f70a6b 100644 --- a/src/app/shortener/shortener.component.ts +++ b/src/app/shortener/shortener.component.ts @@ -37,15 +37,33 @@ export class ShortenerComponent implements OnInit { ngOnInit() { this.titleService.setTitle('Shortener | itzMiney') - if (!this.token) { - this.navigateToLogin(); - return; - } + this.checkToken() this.loadURLs(); } + checkToken() { + if (!this.token || !this.isValidToken(this.token)) { + localStorage.removeItem('token'); + this.navigateToLogin(); + return; + } + } + + isValidToken(token: string) { + try { + const payload = JSON.parse(atob(token.split('.')[1])); + const expiry = payload.exp * 1000; + + return expiry > Date.now(); + } catch (e) { + console.error('Invalid token format:', e); + return false; + } + } + navigateToLogin() { - this.router.navigate(['/login']).then( + const currentRoute = this.router.url; + this.router.navigate(['/login'], { queryParams: { redirectUrl: currentRoute } }).then( (success) => { if (success) { console.log('Navigation to login succeeded'); @@ -60,10 +78,7 @@ export class ShortenerComponent implements OnInit { } loadURLs(): void { - if (!this.token) { - this.navigateToLogin(); - return; - } + this.checkToken() const urlObserver: Observer = { next: (data) => { this.urls = data; @@ -81,7 +96,8 @@ export class ShortenerComponent implements OnInit { } createShortURL(form: any) { - if (!this.token) { + if (!this.token || !this.isValidToken(this.token)) { + localStorage.removeItem('token'); this.navigateToLogin(); return; } @@ -121,7 +137,8 @@ export class ShortenerComponent implements OnInit { } deleteShortURL(form: any) { - if (!this.token) { + if (!this.token || !this.isValidToken(this.token)) { + localStorage.removeItem('token'); this.navigateToLogin(); return; }