Updated token validation
This commit is contained in:
1 parent
94c87b933f
commit
3dbc562147
4 files changed
+111
-36
No files matched your search
@@ -1,13 +1,14 @@
|
|||||||
import {Component, OnInit} from '@angular/core';
|
import {Component, OnDestroy, OnInit} from '@angular/core';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {ArticleService} from '../shared/services/article.service';
|
import {ArticleService} from '../shared/services/article.service';
|
||||||
import {UserService} from '../shared/services/user.service';
|
import {UserService} from '../shared/services/user.service';
|
||||||
import {NgFor, NgIf, NgStyle} from '@angular/common';
|
import {NgFor, NgIf, NgStyle} from '@angular/common';
|
||||||
import { Observer} from 'rxjs';
|
import {Observer, Subscription, interval} from 'rxjs';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {DeviceDetectorService} from '../shared/services/device-detector.service';
|
import {DeviceDetectorService} from '../shared/services/device-detector.service';
|
||||||
import {Title} from '@angular/platform-browser';
|
import {Title} from '@angular/platform-browser';
|
||||||
import {ModalComponent} from '../shared/modal/modal.component';
|
import {ModalComponent} from '../shared/modal/modal.component';
|
||||||
|
import {AuthService} from '../shared/services/auth.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-admin',
|
selector: 'app-admin',
|
||||||
@@ -21,7 +22,7 @@ import {ModalComponent} from '../shared/modal/modal.component';
|
|||||||
ModalComponent
|
ModalComponent
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
export class AdminComponent implements OnInit {
|
export class AdminComponent implements OnInit, OnDestroy {
|
||||||
articles: any[] = [];
|
articles: any[] = [];
|
||||||
users: any[] = [];
|
users: any[] = [];
|
||||||
noArticles: boolean = false;
|
noArticles: boolean = false;
|
||||||
@@ -36,50 +37,94 @@ export class AdminComponent implements OnInit {
|
|||||||
isModalOpen: boolean = false;
|
isModalOpen: boolean = false;
|
||||||
isViewingArticles: boolean = true;
|
isViewingArticles: boolean = true;
|
||||||
|
|
||||||
|
token: string | null= localStorage.getItem('token');
|
||||||
|
tokenValidationInterval: Subscription = new Subscription();
|
||||||
|
|
||||||
userData = {
|
userData = {
|
||||||
username: '',
|
username: '',
|
||||||
password: '',
|
password: '',
|
||||||
id: '',
|
id: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
token: string | null = localStorage.getItem('token');
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private articleService: ArticleService,
|
private articleService: ArticleService,
|
||||||
private userService: UserService,
|
private userService: UserService,
|
||||||
private router: Router,
|
private router: Router,
|
||||||
private deviceService: DeviceDetectorService,
|
private deviceService: DeviceDetectorService,
|
||||||
private titleService: Title
|
private titleService: Title,
|
||||||
|
private authService: AuthService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// Fetch articles from backend
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.titleService.setTitle('Admin Panel | itzMiney')
|
this.titleService.setTitle('Admin Panel | itzMiney')
|
||||||
this.isMobile = this.deviceService.isMobile;
|
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();
|
this.navigateToLogin();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.loadArticles();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
navigateToLogin() {
|
isValidToken(token: string) {
|
||||||
this.router.navigate(['/login']).then(
|
try {
|
||||||
(success) => {
|
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) {
|
if (success) {
|
||||||
console.log('Navigation to login succeeded');
|
console.log('Navigation to login succeeded');
|
||||||
} else {
|
} else {
|
||||||
console.warn('Navigation to login failed');
|
console.warn('Navigation to login failed');
|
||||||
}
|
}
|
||||||
},
|
} catch (error) {
|
||||||
(error) => {
|
|
||||||
console.error('Navigation error:', error);
|
console.error('Navigation error:', error);
|
||||||
}
|
}
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createArticle(form: any) {
|
createArticle(form: any) {
|
||||||
if (!this.token) {
|
if (!this.token || !this.isValidToken(this.token)) {
|
||||||
|
localStorage.removeItem('token');
|
||||||
this.navigateToLogin();
|
this.navigateToLogin();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -106,10 +151,7 @@ export class AdminComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
editArticle(form: any): void {
|
editArticle(form: any): void {
|
||||||
if (!this.token) {
|
this.checkToken();
|
||||||
this.navigateToLogin();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const articleId = form.value.editId;
|
const articleId = form.value.editId;
|
||||||
|
|
||||||
@@ -154,7 +196,8 @@ export class AdminComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
deleteArticle(form: any): void {
|
deleteArticle(form: any): void {
|
||||||
if (!this.token) {
|
if (!this.token || !this.isValidToken(this.token)) {
|
||||||
|
localStorage.removeItem('token');
|
||||||
this.navigateToLogin();
|
this.navigateToLogin();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {AfterViewInit, Component, Inject, OnDestroy, OnInit, PLATFORM_ID} from '@angular/core';
|
import {AfterViewInit, Component, Inject, OnDestroy, OnInit, PLATFORM_ID} from '@angular/core';
|
||||||
import {AuthService} from '../shared/services/auth.service';
|
import {AuthService} from '../shared/services/auth.service';
|
||||||
import {Router} from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {NgIf} from '@angular/common';
|
import {NgIf} from '@angular/common';
|
||||||
import {VantaBackgroundService} from '../shared/services/vanta-background.service';
|
import {VantaBackgroundService} from '../shared/services/vanta-background.service';
|
||||||
@@ -24,10 +24,12 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
errorMessage: string = '';
|
errorMessage: string = '';
|
||||||
private readonly elementId = 'vanta-login-bg';
|
private readonly elementId = 'vanta-login-bg';
|
||||||
isMobile: boolean = false;
|
isMobile: boolean = false;
|
||||||
|
redirectUrl: string = '/admin';
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private authService: AuthService,
|
private authService: AuthService,
|
||||||
private router: Router,
|
private router: Router,
|
||||||
|
private route: ActivatedRoute,
|
||||||
private vantaService: VantaBackgroundService,
|
private vantaService: VantaBackgroundService,
|
||||||
private deviceService: DeviceDetectorService,
|
private deviceService: DeviceDetectorService,
|
||||||
private titleService: Title,
|
private titleService: Title,
|
||||||
@@ -37,6 +39,13 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.titleService.setTitle('Login | itzMiney')
|
this.titleService.setTitle('Login | itzMiney')
|
||||||
this.isMobile = this.deviceService.isMobile;
|
this.isMobile = this.deviceService.isMobile;
|
||||||
|
|
||||||
|
this.route.queryParams.subscribe(params => {
|
||||||
|
if (params['redirectUrl']) {
|
||||||
|
this.redirectUrl = decodeURIComponent(params['redirectUrl']);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (isPlatformBrowser(this.platformId)) {
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
window.addEventListener('resize', this.onResize.bind(this));
|
window.addEventListener('resize', this.onResize.bind(this));
|
||||||
}
|
}
|
||||||
@@ -46,7 +55,7 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
const observer = {
|
const observer = {
|
||||||
'next': (response: any) => {
|
'next': (response: any) => {
|
||||||
localStorage.setItem('token', response.token);
|
localStorage.setItem('token', response.token);
|
||||||
this.router.navigate(['/admin']).then(
|
this.router.navigate([this.redirectUrl]).then(
|
||||||
(success) => {
|
(success) => {
|
||||||
if (success) {
|
if (success) {
|
||||||
console.log('Navigation to admin succeeded');
|
console.log('Navigation to admin succeeded');
|
||||||
@@ -60,7 +69,6 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
error: (err: any) => {
|
error: (err: any) => {
|
||||||
// Check if the error response contains a message
|
|
||||||
if (err.error && err.error.message) {
|
if (err.error && err.error.message) {
|
||||||
this.errorMessage = err.error.message;
|
this.errorMessage = err.error.message;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {Injectable} from '@angular/core';
|
import {Injectable} from '@angular/core';
|
||||||
import {HttpClient} from '@angular/common/http';
|
import {HttpClient} from '@angular/common/http';
|
||||||
import {Observable, tap} from 'rxjs';
|
import {Observable, of, tap} from 'rxjs';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root'
|
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}` }
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -37,15 +37,33 @@ export class ShortenerComponent implements OnInit {
|
|||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.titleService.setTitle('Shortener | itzMiney')
|
this.titleService.setTitle('Shortener | itzMiney')
|
||||||
if (!this.token) {
|
this.checkToken()
|
||||||
this.navigateToLogin();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.loadURLs();
|
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() {
|
navigateToLogin() {
|
||||||
this.router.navigate(['/login']).then(
|
const currentRoute = this.router.url;
|
||||||
|
this.router.navigate(['/login'], { queryParams: { redirectUrl: currentRoute } }).then(
|
||||||
(success) => {
|
(success) => {
|
||||||
if (success) {
|
if (success) {
|
||||||
console.log('Navigation to login succeeded');
|
console.log('Navigation to login succeeded');
|
||||||
@@ -60,10 +78,7 @@ export class ShortenerComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadURLs(): void {
|
loadURLs(): void {
|
||||||
if (!this.token) {
|
this.checkToken()
|
||||||
this.navigateToLogin();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const urlObserver: Observer<any> = {
|
const urlObserver: Observer<any> = {
|
||||||
next: (data) => {
|
next: (data) => {
|
||||||
this.urls = data;
|
this.urls = data;
|
||||||
@@ -81,7 +96,8 @@ export class ShortenerComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
createShortURL(form: any) {
|
createShortURL(form: any) {
|
||||||
if (!this.token) {
|
if (!this.token || !this.isValidToken(this.token)) {
|
||||||
|
localStorage.removeItem('token');
|
||||||
this.navigateToLogin();
|
this.navigateToLogin();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -121,7 +137,8 @@ export class ShortenerComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
deleteShortURL(form: any) {
|
deleteShortURL(form: any) {
|
||||||
if (!this.token) {
|
if (!this.token || !this.isValidToken(this.token)) {
|
||||||
|
localStorage.removeItem('token');
|
||||||
this.navigateToLogin();
|
this.navigateToLogin();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user