merged shortener page into admin page, refactored into modal

This commit is contained in:
itzMiney committed 2026-03-18 07:15:21 +01:00
1 parent d1d72022da
commit 6110248668
14 files changed
+363 -337

No files matched your search

+3 -3
View File
@@ -26,12 +26,12 @@
.close-btn {
position: absolute;
top: 4px;
right: 8px;
top: 25px;
right: 25px;
background: none;
color: white;
border: none;
font-size: 28px;
font-size: 40px;
cursor: pointer;
transition: all ease-in-out 0.2s;
}
+3 -3
View File
@@ -1,7 +1,7 @@
@if (isOpen) {
<div class="modal-backdrop">
<div class="modal">
<button class="close-btn" (click)="closeModal()"><i class="fa-solid fa-xmark"></i></button>
<div class="modal-backdrop" (click)="closeModal()">
<button class="close-btn" (click)="closeModal()"><i class="fa-solid fa-xmark"></i></button>
<div class="modal" (click)="$event.stopPropagation()">
<h2>{{ title }}</h2>
<ng-content></ng-content>
</div>
+28 -41
View File
@@ -18,10 +18,10 @@ export class AuthService {
return localStorage.getItem('token');
}
login(username: string, password: string): Observable<any> {
return this.http.post(this.apiUrl, { username, password }).pipe(
tap((response: any) => {
if (response?.token) localStorage.setItem('token', response.token);
login(username: string, password: string): Observable<{ token: string }> {
return this.http.post<{ token: string }>(this.apiUrl, { username, password }).pipe(
tap(response => {
localStorage.setItem('token', response.token);
})
);
}
@@ -29,60 +29,47 @@ export class AuthService {
logout(): void {
if (this.redirectingToLogin) return;
localStorage.removeItem('token');
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(() => {
void this.router.navigate(['/login'], { 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> {
validateToken(): Observable<boolean> {
const token = this.token;
if (!this.isJwtNotExpired(token)) {
if (!token) {
this.logout();
return of(false);
}
return this.http.get('/api/users', {
headers: { Authorization: `Bearer ${token}` }
try {
const payload = JSON.parse(atob(token.split('.')[1]));
const isValid = payload.exp * 1000;
if (!isValid) {
this.logout();
return of(false);
}
} catch {
this.logout();
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();
}
catchError(() => {
this.logout();
return of(false);
})
);
}
@@ -0,0 +1,179 @@
.container-wrapper {
position: fixed;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 1000;
}
.container {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
min-width: 300px;
padding: 25px;
background-color: #202025;
color: #fff;
border-radius: 35px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
max-height: 90vh;
overflow: hidden;
z-index: 1001;
}
.container-content {
flex: 0 0 auto;
width: 100%;
}
h1 {
margin-top: 40px;
text-align: center;
}
h3 {
text-align: center;
}
.form-section {
margin-bottom: 30px;
text-align: center;
}
.form-group {
justify-content: center;
display: flex;
margin-bottom: 15px;
gap: 12px;
}
input {
color: white;
background: #26262c;
border: none;
padding: 10px 20px;
border-radius: 25px;
transition: all ease-in-out 0.2s;
box-sizing: border-box;
font-size: 1rem;
}
input:focus {
outline: none;
background: #2b2b32;
}
input[type="url"],
input[type="text"] {
min-width: 250px;
}
input[type="number"] {
max-width: 80px;
-moz-appearance: textfield;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
button {
padding: 12px 20px;
border: none;
border-radius: 25px;
font-size: 1rem;
cursor: pointer;
}
.btn-primary {
background-color: #8a6bbf;
color: white;
}
.btn-danger {
background-color: #BA243AFF;
color: white;
}
button:hover {
opacity: 0.9;
}
.url-list-wrapper {
flex: 1 1 auto;
overflow-y: auto;
min-height: 0;
width: 100%;
margin-top: 20px;
}
.url-list-items {
list-style-type: none;
padding: 0;
width: 100%;
}
.url-list-items li {
background: #26262c;
padding: 10px 15px;
row-gap: 10px;
border-radius: 20px;
line-height: 1.5rem;
}
li + li {
margin-top: 10px;
}
.url-list-items a {
color: #D688ECFF;
text-decoration: none;
}
.url-list-items a:hover {
text-decoration: underline;
}
.copy-btn {
background: transparent;
color: #D688ECFF;
border: none;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
padding: 0;
margin-left: 4px;
}
.copy-btn:active, .copy-btn:focus {
color: #7dc68e;
}
.close-btn {
position: absolute;
top: 25px;
right: 25px;
background: none;
color: white;
border: none;
font-size: 40px;
cursor: pointer;
transition: all ease-in-out 0.2s;
}
.close-btn:hover {
color: #ebe1fa;
}
.close-btn:active {
color: #a172e8;
}
@@ -0,0 +1,89 @@
@if (isOpen) {
<div class="container-wrapper" (click)="closeShortenerModal()">
<div class="container" (click)="$event.stopPropagation()">
<button class="close-btn" (click)="closeShortenerModal()"><i class="fa-solid fa-xmark"></i></button>
<div class="container-content">
<h1>URL Shortener</h1>
<!-- URL Creation Form -->
<div class="form-section">
<form (ngSubmit)="createShortURL(shortURLForm)" #shortURLForm="ngForm">
<div class="form-group">
<input
type="url"
id="og_url"
name="og_url"
ngModel
class="form-control"
placeholder="Original URL"
required
/>
</div>
<div class="form-group">
<input
type="text"
id="short_name"
name="short_name"
ngModel
class="form-control"
placeholder="Short URL Name (Optional)"
/>
</div>
<button type="submit" class="btn btn-primary">Shorten URL</button>
</form>
</div>
<!-- Delete URL Section -->
<div class="form-section">
<h3>Delete Short URL</h3>
<form (ngSubmit)="deleteShortURL(deleteURLForm)" #deleteURLForm="ngForm">
<div class="form-group">
<input
type="number"
id="deleteId"
name="deleteId"
ngModel
class="form-control"
placeholder="ID"
required
/>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</form>
</div>
<h3>Existing Short URLs</h3>
</div>
<!-- Scrollable URL list -->
<div class="url-list-wrapper">
@if (noURLs) {
<div>
<p>No short URLs available.</p>
</div>
} @else {
<ul class="url-list-items">
@for (url of urls; track url) {
<li>
<strong>ID {{ url.id }}</strong> // <strong>URL: </strong>
<a [href]="'https://itz.sh/' + url.short_url" target="_blank"
rel="noopener">{{ 'https://itz.sh/' + url.short_url }}</a>
<button type="button" class="copy-btn" (click)="copyShortUrl(url.short_url)"
[attr.aria-label]="'Copy ' + ('https://itz.sh/' + url.short_url)" title="Copy Short URL">
<span class="link-icon"><i class="fa-solid fa-link"></i></span>
</button>
<br>
<strong>Original: </strong>
<a [href]="url.og_url"
target="_blank">{{ (url.og_url | slice:0:45) + (url.og_url.length > 40 ? '...' : '') }}</a><br>
</li>
}
</ul>
}
</div>
</div>
</div>
}
@@ -0,0 +1,130 @@
import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import {ShortenerService} from '../services/shortener.service';
import {FormsModule} from '@angular/forms';
import { SlicePipe } from '@angular/common';
import {AuthService} from '../services/auth.service';
@Component({
selector: 'app-shortener',
imports: [
FormsModule,
SlicePipe
],
templateUrl: './shortener.component.html',
styleUrl: './shortener.component.css'
})
export class ShortenerComponent implements OnInit {
@Input() isOpen: boolean = false;
@Output() onClose = new EventEmitter<void>();
urls: any[] = [];
noURLs: boolean = false;
og_url: string = '';
short_name: string | null = null;
deleteId: number | null = null;
copiedShort: string | null = null;
constructor(
private shortenerService: ShortenerService,
private authService: AuthService,
) {}
ngOnInit() {
this.loadURLs();
}
loadURLs(): void {
const token = this.authService.token;
if (!token) {
return;
}
this.shortenerService.getAllURLs(token).subscribe({
next: (data) => {
this.urls = data;
this.noURLs = data.length === 0;
},
error: (err) => {
console.error('Error loading URLs:', err)
}
});
}
createShortURL(form: any) {
const og_url = form.value.og_url;
const short_name = form.value.short_name ?? null;
if (!og_url) {
alert('Original URL Required!');
return;
}
const token = this.authService.token;
if (!token) {
return;
}
const req$ = short_name
? this.shortenerService.postURL(token, og_url, short_name)
: this.shortenerService.postURL(token, og_url);
req$.subscribe({
next: () => {
alert('Short URL created successfully!');
this.loadURLs();
},
error: (error) => {
alert('Error creating Short URL');
console.error(error);
}
});
}
deleteShortURL(form: any) {
const id = form.value.deleteId;
if (!id || isNaN(Number(id))) {
alert('Invalid input. Please enter a valid Short URL ID.');
return;
}
const token = this.authService.token!;
if (!token) {
return;
}
this.shortenerService.deleteURL(Number(id), token).subscribe({
next: () => {
alert(`Short URL with ID ${id} deleted successfully`);
this.loadURLs();
},
error: (error) => {
alert(`Error deleting Short URL ${id}: ${error.message}`);
console.error('Error deleting Short URL:', error);
}
});
}
copyShortUrl(shortCode: string): void {
const shortUrl = `https://itz.sh/${shortCode}`;
navigator.clipboard.writeText(shortUrl).then(() => {
this.copiedShort = shortCode;
setTimeout(() => {
if (this.copiedShort === shortCode) this.copiedShort = null;
}, 2000);
}).catch(() => {
});
}
closeShortenerModal() {
this.isOpen = false;
this.onClose.emit();
}
}