Code cleanup, fixed some loops and bugs

This commit is contained in:
itzMiney committed 2025-12-24 00:50:01 +01:00
1 parent a88ab3fe9c
commit 47428ee891
7 files changed
+2242 -1710

No files matched your search

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