Updated token validation

This commit is contained in:
itzMiney committed 2025-03-15 21:32:19 +01:00
1 parent 94c87b933f
commit 3dbc562147
4 files changed
+118 -43

No files matched your search

+71 -28
View File
@@ -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;
}
+11 -3
View File
@@ -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 {
+8 -1
View File
@@ -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<boolean>('/api/users', {
headers: { Authorization: `Bearer ${token}` }
})
}
}
+28 -11
View File
@@ -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<any> = {
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;
}