Code cleanup, fixed some loops and bugs
This commit is contained in:
1 parent
a88ab3fe9c
commit
47428ee891
7 files changed
+2241
-1709
No files matched your search
Generated
+1999
-1410
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -41,7 +41,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^20.0.1",
|
||||
"@angular/cli": "^20.0.1",
|
||||
"@angular/cli": "^21.0.4",
|
||||
"@angular/compiler-cli": "^20.0.2",
|
||||
"@biesbjerg/ngx-translate-extract": "^7.0.4",
|
||||
"@types/express": "^4.17.17",
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
<button (click)="openModal('create')">Create User</button>
|
||||
<button (click)="openModal('edit')">Edit User</button>
|
||||
<button (click)="openModal('delete')">Delete User</button>
|
||||
<button class="logout" (click)="logout()">Logout</button>
|
||||
<button class="logout" (click)="this.authService.logout()">Logout</button>
|
||||
</div>
|
||||
|
||||
<!-- User Actions Modal -->
|
||||
|
||||
@@ -23,6 +23,8 @@ import {AuthService} from '../shared/services/auth.service';
|
||||
]
|
||||
})
|
||||
export class AdminComponent implements OnInit, OnDestroy {
|
||||
tokenValidationInterval: Subscription = new Subscription();
|
||||
|
||||
articles: any[] = [];
|
||||
users: any[] = [];
|
||||
noArticles: boolean = false;
|
||||
@@ -37,9 +39,6 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
isModalOpen: boolean = false;
|
||||
isViewingArticles: boolean = true;
|
||||
|
||||
token: string | null= localStorage.getItem('token');
|
||||
tokenValidationInterval: Subscription = new Subscription();
|
||||
|
||||
userData = {
|
||||
username: '',
|
||||
password: '',
|
||||
@@ -52,85 +51,28 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
private router: Router,
|
||||
private deviceService: DeviceDetectorService,
|
||||
private titleService: Title,
|
||||
private authService: AuthService
|
||||
protected authService: AuthService
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.titleService.setTitle('Admin Panel | itzMiney')
|
||||
this.isMobile = this.deviceService.isMobile;
|
||||
this.checkToken();
|
||||
this.loadArticles();
|
||||
this.authService.validateToken().subscribe();
|
||||
this.startTokenValidation();
|
||||
this.loadArticles();
|
||||
}
|
||||
|
||||
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.');
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
console.error('Error validating token:', error);
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
}
|
||||
);
|
||||
this.authService.validateToken().subscribe();
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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 || !this.isValidToken(this.token)) {
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
return;
|
||||
}
|
||||
|
||||
const title = form.value.title;
|
||||
const content = form.value.content;
|
||||
|
||||
@@ -139,28 +81,38 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.articleService.postArticle(this.token, title, content).subscribe(
|
||||
(response) => {
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
const token = this.authService.token!;
|
||||
this.articleService.postArticle(token, title, content).subscribe(
|
||||
() => {
|
||||
alert('Article created successfully!');
|
||||
this.loadArticles();
|
||||
console.log(response);
|
||||
},
|
||||
(error) => {
|
||||
error => {
|
||||
alert('Error creating article');
|
||||
console.error(error);
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
editArticle(form: NgForm): void {
|
||||
this.checkToken();
|
||||
|
||||
const articleId = form.value.editId;
|
||||
|
||||
if (articleId && !isNaN(Number(articleId))) {
|
||||
if (!articleId || isNaN(Number(articleId))) {
|
||||
alert('Invalid input. Please enter a valid article ID.');
|
||||
return;
|
||||
}
|
||||
|
||||
const id = Number(articleId);
|
||||
|
||||
// Fetch the current article to get existing values
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.articleService.getArticleById(id).subscribe(
|
||||
(article) => {
|
||||
if (!article) {
|
||||
@@ -171,11 +123,10 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
const newTitle = form.value.editTitle || form.value.editTitleMobile;
|
||||
const newContent = form.value.editContent || form.value.editContentMobile;
|
||||
|
||||
// Use current values if left blank
|
||||
const updatedTitle = newTitle?.trim() || article.title;
|
||||
const updatedContent = newContent?.trim() || article.content;
|
||||
|
||||
this.articleService.editArticle(id, this.token, updatedTitle, updatedContent).subscribe(
|
||||
this.articleService.editArticle(id, token, updatedTitle, updatedContent).subscribe(
|
||||
(response) => {
|
||||
alert(`Article ${id} updated successfully!`);
|
||||
console.log('Updated Article:', response);
|
||||
@@ -183,58 +134,46 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
},
|
||||
(error) => {
|
||||
alert(`Error updating article ${id}: ${error.message}`);
|
||||
console.error('Error:', error)
|
||||
console.error('Error:', error);
|
||||
}
|
||||
);
|
||||
},
|
||||
(error: { message: any; }) => {
|
||||
(error: { message: any }) => {
|
||||
alert(`Failed to fetch article with ID ${id}: ${error.message}`);
|
||||
console.error('Error:', error)
|
||||
console.error('Error:', error);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
alert('Invalid input. Please enter a valid article ID.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteArticle(form: any): void {
|
||||
if (!this.token || !this.isValidToken(this.token)) {
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
const articleId = form.value.deleteId || form.value.deleteIdMobile;
|
||||
|
||||
if (!articleId || isNaN(Number(articleId))) {
|
||||
alert('Invalid input. Please enter a valid article ID.');
|
||||
return;
|
||||
}
|
||||
|
||||
const articleId = form.value.deleteId || form.value.deleteIdMobile;
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
if (articleId && !isNaN(Number(articleId))) {
|
||||
this.articleService.deleteArticle(articleId, this.token).subscribe(
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.articleService.deleteArticle(Number(articleId), token).subscribe(
|
||||
() => {
|
||||
alert(`Article ${articleId} deleted successfully`);
|
||||
this.loadArticles();
|
||||
},
|
||||
(error) => {
|
||||
error => {
|
||||
alert(`Error deleting article ${articleId}: ${error.message}`);
|
||||
console.error('Error deleting article:', error)
|
||||
console.error(error);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
alert('Invalid input. Please enter a valid article ID.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
navigateToArticle(slug: string): void {
|
||||
this.router.navigate([`/blog/${slug}`]).then(
|
||||
(success) => {
|
||||
if (success) {
|
||||
console.log('Navigation to article succeeded');
|
||||
} else {
|
||||
console.warn('Navigation to article failed');
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
console.error('Navigation error:', error);
|
||||
}
|
||||
);
|
||||
void this.router.navigate([`/blog/${slug}`]);
|
||||
}
|
||||
|
||||
loadArticles(): void {
|
||||
@@ -254,9 +193,15 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
loadUsers() {
|
||||
this.userService.getAllUsers(this.token).subscribe((data: any[]) => {
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.userService.getAllUsers(token).subscribe(data => {
|
||||
this.users = data;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
toggleView() {
|
||||
@@ -267,11 +212,6 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
logout() {
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
}
|
||||
|
||||
openModal(action: string) {
|
||||
this.isModalOpen = true;
|
||||
this.modalAction = action;
|
||||
@@ -299,11 +239,6 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
createUser(form: any): void {
|
||||
if (!this.token) {
|
||||
this.navigateToLogin();
|
||||
return;
|
||||
}
|
||||
|
||||
const username = form.value.createUsername;
|
||||
const password = form.value.createPassword;
|
||||
|
||||
@@ -312,30 +247,43 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.userService.createUser(this.token, username, password).subscribe(
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.userService.createUser(token, username, password).subscribe(
|
||||
(response) => {
|
||||
alert('User created successfully!');
|
||||
this.loadUsers();
|
||||
console.log(response);
|
||||
},
|
||||
|
||||
(error) => {
|
||||
alert('Error creating user');
|
||||
console.error(error);
|
||||
});
|
||||
this.closeModal();
|
||||
});
|
||||
}
|
||||
|
||||
editUser(form: any): void {
|
||||
if (!this.token) {
|
||||
this.navigateToLogin();
|
||||
return;
|
||||
}
|
||||
const userId = form.value.editUserId;
|
||||
|
||||
if (userId && !isNaN(Number(userId))) {
|
||||
if (!userId || isNaN(Number(userId))) {
|
||||
alert('Invalid input. Please enter a valid user ID.');
|
||||
this.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
const id = Number(userId);
|
||||
|
||||
this.userService.getUserById(id, this.token).subscribe(
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.userService.getUserById(id, token).subscribe(
|
||||
(user) => {
|
||||
if (!user) {
|
||||
alert(`User with ID ${id} not found.`);
|
||||
@@ -345,11 +293,10 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
const newUsername = form.value.editUsername;
|
||||
const newPassword = form.value.editPassword;
|
||||
|
||||
// Use current values if left blank
|
||||
const updatedUsername = newUsername?.trim();
|
||||
const updatedPassword = newPassword?.trim();
|
||||
|
||||
this.userService.editUser(id, this.token, updatedUsername, updatedPassword).subscribe(
|
||||
this.userService.editUser(id, token, updatedUsername, updatedPassword).subscribe(
|
||||
(response) => {
|
||||
alert(`User ${id} updated successfully!`);
|
||||
console.log('Updated User:', response);
|
||||
@@ -357,44 +304,47 @@ export class AdminComponent implements OnInit, OnDestroy {
|
||||
},
|
||||
(error) => {
|
||||
alert(`Error updating user ${id}: ${error.message}`);
|
||||
console.error('Error:', error)
|
||||
console.error('Error:', error);
|
||||
}
|
||||
);
|
||||
},
|
||||
(error: { message: any; }) => {
|
||||
(error: { message: any }) => {
|
||||
alert(`Failed to fetch user with ID ${id}: ${error.message}`);
|
||||
console.error('Error:', error)
|
||||
console.error('Error:', error);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
alert('Invalid input. Please enter a valid article ID.');
|
||||
}
|
||||
});
|
||||
|
||||
this.closeModal();
|
||||
}
|
||||
|
||||
deleteUser(form: any): void {
|
||||
if (!this.token) {
|
||||
this.navigateToLogin();
|
||||
const userId = form.value.deleteUserId;
|
||||
|
||||
if (!userId || isNaN(Number(userId))) {
|
||||
alert('Invalid input. Please enter a valid user ID.');
|
||||
console.error('Invalid input:', userId);
|
||||
this.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
const userId = form.value.deleteUserId;
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
if (userId && !isNaN(Number(userId))) {
|
||||
this.userService.deleteUser(userId, this.token).subscribe(
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.userService.deleteUser(Number(userId), token).subscribe(
|
||||
() => {
|
||||
alert(`User ${userId} deleted successfully`);
|
||||
this.loadUsers();
|
||||
},
|
||||
(error) => {
|
||||
alert(`Error deleting user ${userId}: ${error.message}`);
|
||||
console.error('Error deleting user:', error)
|
||||
console.error('Error deleting user:', error);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
alert('Invalid input. Please enter a valid user ID.');
|
||||
console.error('Invalid input:', userId);
|
||||
}
|
||||
});
|
||||
|
||||
this.closeModal();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import {VantaBackgroundService} from '../shared/services/vanta-background.servic
|
||||
import {DeviceDetectorService} from '../shared/services/device-detector.service';
|
||||
import {isPlatformBrowser} from '@angular/common';
|
||||
import { Title } from '@angular/platform-browser';
|
||||
import { take } from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
@@ -19,12 +20,18 @@ import {Title} from '@angular/platform-browser';
|
||||
})
|
||||
|
||||
export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
||||
username: string = '';
|
||||
password: string = '';
|
||||
errorMessage: string = '';
|
||||
username = '';
|
||||
password = '';
|
||||
errorMessage = '';
|
||||
private readonly isBrowser: boolean;
|
||||
private readonly boundResize = this.onResize.bind(this);
|
||||
private readonly elementId = 'vanta-login-bg';
|
||||
isMobile: boolean = false;
|
||||
redirectUrl: string = '/admin';
|
||||
private readonly allowedAdminRoutes = new Set([
|
||||
'/admin',
|
||||
'/shortener'
|
||||
]);
|
||||
isMobile = false;
|
||||
redirectUrl = '/admin';
|
||||
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
@@ -34,51 +41,42 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
||||
private deviceService: DeviceDetectorService,
|
||||
private titleService: Title,
|
||||
@Inject(PLATFORM_ID) private platformId: Object
|
||||
) {}
|
||||
) {
|
||||
this.isBrowser = isPlatformBrowser(this.platformId);
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.titleService.setTitle('Login | itzMiney')
|
||||
this.isMobile = this.deviceService.isMobile;
|
||||
|
||||
this.route.queryParams.subscribe(params => {
|
||||
if (params['redirectUrl']) {
|
||||
this.redirectUrl = decodeURIComponent(params['redirectUrl']);
|
||||
this.route.queryParams.pipe(take(1)).subscribe(params => {
|
||||
const raw = params['redirectUrl'];
|
||||
|
||||
if (typeof raw === 'string' && this.allowedAdminRoutes.has(raw)) {
|
||||
this.redirectUrl = raw;
|
||||
} else {
|
||||
this.redirectUrl = '/admin';
|
||||
}
|
||||
});
|
||||
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
window.addEventListener('resize', this.onResize.bind(this));
|
||||
if (this.isBrowser) {
|
||||
window.addEventListener('resize', this.boundResize);
|
||||
}
|
||||
}
|
||||
|
||||
onLogin() {
|
||||
const observer = {
|
||||
'next': (response: any) => {
|
||||
localStorage.setItem('token', response.token);
|
||||
this.router.navigate([this.redirectUrl]).then(
|
||||
(success) => {
|
||||
if (success) {
|
||||
console.log('Navigation to admin succeeded');
|
||||
} else {
|
||||
console.warn('Navigation to admin failed');
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
console.error('Navigation error:', error);
|
||||
}
|
||||
);
|
||||
},
|
||||
error: (err: any) => {
|
||||
if (err.error && err.error.message) {
|
||||
this.errorMessage = err.error.message;
|
||||
} else {
|
||||
this.errorMessage = 'An error occurred. Please try again later.';
|
||||
}
|
||||
console.error('Login error:', err);
|
||||
},
|
||||
};
|
||||
this.errorMessage = '';
|
||||
|
||||
this.authService.login(this.username.trim(), this.password).subscribe(observer);
|
||||
this.authService.login(this.username.trim(), this.password).subscribe({
|
||||
next: () => {
|
||||
void this.router.navigateByUrl(this.redirectUrl);
|
||||
},
|
||||
error: (err) => {
|
||||
this.errorMessage =
|
||||
err?.error?.message ?? 'An error occurred. Please try again later.';
|
||||
console.error('Login error:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
@@ -86,8 +84,8 @@ export class LoginComponent implements OnInit, OnDestroy, AfterViewInit {
|
||||
}
|
||||
ngOnDestroy() {
|
||||
this.vantaService.destroyVanta(this.elementId);
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
window.removeEventListener('resize', this.onResize);
|
||||
if (this.isBrowser) {
|
||||
window.removeEventListener('resize', this.boundResize);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,32 +1,89 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable, of, tap} from 'rxjs';
|
||||
import {Observable, of, tap, map, catchError} from 'rxjs';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
|
||||
private apiUrl = '/api/auth/login';
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
private redirectingToLogin = false;
|
||||
|
||||
constructor(
|
||||
private http: HttpClient,
|
||||
private router: Router
|
||||
) {}
|
||||
|
||||
get token(): string | null {
|
||||
return localStorage.getItem('token');
|
||||
}
|
||||
|
||||
login(username: string, password: string): Observable<any> {
|
||||
return this.http.post(this.apiUrl, { username, password })
|
||||
.pipe(
|
||||
return this.http.post(this.apiUrl, { username, password }).pipe(
|
||||
tap((response: any) => {
|
||||
// Store token in localStorage after successful login
|
||||
if (response.token) {
|
||||
localStorage.setItem('token', response.token);
|
||||
}
|
||||
if (response?.token) localStorage.setItem('token', response.token);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
isTokenValid(token: string | null) {
|
||||
if (!token) return of(false);
|
||||
return this.http.get<boolean>('/api/users', {
|
||||
logout(): void {
|
||||
if (this.redirectingToLogin) return;
|
||||
|
||||
if (this.router.url.startsWith('/login')) {
|
||||
localStorage.removeItem('token');
|
||||
return;
|
||||
}
|
||||
|
||||
this.redirectingToLogin = true;
|
||||
|
||||
localStorage.removeItem('token');
|
||||
|
||||
const tree = this.router.parseUrl(this.router.url);
|
||||
delete tree.queryParams?.['redirectUrl'];
|
||||
const cleanRedirectUrl = tree.toString();
|
||||
|
||||
void this.router.navigate(['/login'], {
|
||||
queryParams: { redirectUrl: cleanRedirectUrl },
|
||||
replaceUrl: true
|
||||
}).finally(() => {
|
||||
this.redirectingToLogin = false;
|
||||
});
|
||||
}
|
||||
|
||||
private isJwtNotExpired(token: string | null): boolean {
|
||||
if (!token) return false;
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
const expMs = payload.exp * 1000;
|
||||
return expMs > Date.now();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
isTokenValid(): Observable<boolean> {
|
||||
const token = this.token;
|
||||
|
||||
if (!this.isJwtNotExpired(token)) {
|
||||
return of(false);
|
||||
}
|
||||
|
||||
return this.http.get('/api/users', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
}).pipe(
|
||||
map(() => true),
|
||||
catchError(() => of(false))
|
||||
);
|
||||
}
|
||||
|
||||
validateToken(): Observable<boolean> {
|
||||
return this.isTokenValid().pipe(
|
||||
tap(valid => {
|
||||
if (!valid) {
|
||||
this.logout();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Component, OnInit, OnDestroy} from '@angular/core';
|
||||
import {Title} from '@angular/platform-browser';
|
||||
import {Router} from '@angular/router';
|
||||
import {ShortenerService} from '../shared/services/shortener.service';
|
||||
import {interval, Observer, Subscription} from 'rxjs';
|
||||
import {interval, Subscription, switchMap} from 'rxjs';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {NgFor, NgIf, SlicePipe} from '@angular/common';
|
||||
import {AuthService} from '../shared/services/auth.service';
|
||||
import {filter} from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'app-shortener',
|
||||
@@ -18,111 +18,52 @@ import {AuthService} from '../shared/services/auth.service';
|
||||
templateUrl: './shortener.component.html',
|
||||
styleUrl: './shortener.component.css'
|
||||
})
|
||||
export class ShortenerComponent implements OnInit {
|
||||
export class ShortenerComponent implements OnInit, OnDestroy {
|
||||
tokenValidationInterval: Subscription = new Subscription();
|
||||
|
||||
urls: any[] = [];
|
||||
noURLs: boolean = false;
|
||||
|
||||
token: string | null = localStorage.getItem('token');
|
||||
|
||||
og_url: string = '';
|
||||
short_name: string | null = null;
|
||||
deleteId: number | null = null;
|
||||
tokenValidationInterval: Subscription = new Subscription();
|
||||
|
||||
constructor(
|
||||
private shortenerService: ShortenerService,
|
||||
private router: Router,
|
||||
private authService: AuthService,
|
||||
private titleService: Title
|
||||
) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.titleService.setTitle('Shortener | itzMiney')
|
||||
this.checkToken()
|
||||
this.loadURLs();
|
||||
this.startTokenValidation();
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
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.');
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
console.error('Error validating token:', error);
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
}
|
||||
);
|
||||
this.authService.validateToken().subscribe();
|
||||
});
|
||||
}
|
||||
|
||||
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() {
|
||||
const currentRoute = this.router.url;
|
||||
this.router.navigate(['/login'], { queryParams: { redirectUrl: currentRoute } }).then(
|
||||
(success) => {
|
||||
if (success) {
|
||||
console.log('Navigation to login succeeded');
|
||||
} else {
|
||||
console.warn('Navigation to login failed');
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
console.error('Navigation error:', error);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
loadURLs(): void {
|
||||
this.checkToken()
|
||||
const urlObserver: Observer<any> = {
|
||||
this.authService.validateToken().pipe(
|
||||
filter(valid => valid),
|
||||
switchMap(() => this.shortenerService.getAllURLs(this.authService.token!))
|
||||
).subscribe({
|
||||
next: (data) => {
|
||||
this.urls = data;
|
||||
this.noURLs = this.urls.length === 0;
|
||||
this.noURLs = data.length === 0;
|
||||
},
|
||||
error: (error) => {
|
||||
console.error('Failed to load Short URLs', error);
|
||||
},
|
||||
complete: () => {
|
||||
console.log('Short URL loading complete');
|
||||
}
|
||||
};
|
||||
if (!this.token) return;
|
||||
this.shortenerService.getAllURLs(this.token).subscribe(urlObserver);
|
||||
error: (err) => console.error(err)
|
||||
});
|
||||
}
|
||||
|
||||
createShortURL(form: any) {
|
||||
if (!this.token || !this.isValidToken(this.token)) {
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
return;
|
||||
}
|
||||
|
||||
const og_url = form.value.og_url;
|
||||
const short_name = form.value.short_name ?? null;
|
||||
|
||||
@@ -130,55 +71,52 @@ export class ShortenerComponent implements OnInit {
|
||||
alert('Original URL Required!');
|
||||
return;
|
||||
}
|
||||
if (!short_name) {
|
||||
this.shortenerService.postURL(this.token, og_url).subscribe(
|
||||
(response) => {
|
||||
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
const token = this.authService.token!;
|
||||
|
||||
const req$ = short_name
|
||||
? this.shortenerService.postURL(token, og_url, short_name)
|
||||
: this.shortenerService.postURL(token, og_url);
|
||||
|
||||
req$.subscribe(
|
||||
() => {
|
||||
alert('Short URL created successfully!');
|
||||
this.loadURLs();
|
||||
console.log(response);
|
||||
},
|
||||
(error) => {
|
||||
alert('Error creating Short URL');
|
||||
console.error(error);
|
||||
}
|
||||
);
|
||||
} else if (short_name) {
|
||||
this.shortenerService.postURL(this.token, og_url, short_name).subscribe(
|
||||
(response) => {
|
||||
alert('Short URL created successfully!');
|
||||
this.loadURLs();
|
||||
console.log(response);
|
||||
},
|
||||
(error) => {
|
||||
alert('Error creating Short URL');
|
||||
console.error(error);
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteShortURL(form: any) {
|
||||
if (!this.token || !this.isValidToken(this.token)) {
|
||||
localStorage.removeItem('token');
|
||||
this.navigateToLogin();
|
||||
const id = form.value.deleteId;
|
||||
|
||||
if (!id || isNaN(Number(id))) {
|
||||
alert('Invalid input. Please enter a valid Short URL ID.');
|
||||
return;
|
||||
}
|
||||
|
||||
const id = form.value.deleteId
|
||||
this.authService.validateToken().subscribe(valid => {
|
||||
if (!valid) return;
|
||||
|
||||
if (id && !isNaN(Number(id))) {
|
||||
this.shortenerService.deleteURL(id, this.token).subscribe(
|
||||
const token = this.authService.token!;
|
||||
|
||||
this.shortenerService.deleteURL(Number(id), token).subscribe(
|
||||
() => {
|
||||
alert(`Short URL with ID ${id} deleted successfully`);
|
||||
this.loadURLs();
|
||||
},
|
||||
(error) => {
|
||||
alert(`Error deleting Short URL ${id}: ${error.message}`);
|
||||
console.error('Error deleting Short URL:', error)
|
||||
console.error('Error deleting Short URL:', error);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
alert('Invalid input. Please enter a valid Short URL ID.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user