Skip to content

Commit

Permalink
Bug-fix navbar; -Add admin role
Browse files Browse the repository at this point in the history
  • Loading branch information
JarvisScienz committed Jun 29, 2023
1 parent 3a410d4 commit b15b48c
Show file tree
Hide file tree
Showing 19 changed files with 376 additions and 167 deletions.
120 changes: 63 additions & 57 deletions .firebase/hosting.ZGlzdFxkYWlseS1pbnNwaXJl.cache

Large diffs are not rendered by default.

26 changes: 26 additions & 0 deletions src/app/_helpers/login.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { CookiesService } from '../_services/cookies.service';
import { AuthService } from '../_services/auth.service';

@Injectable({ providedIn: 'root' })
export class LoginGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthService,
private cookiesService: CookiesService
) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.cookiesService.getCookie("userID");
if (!currentUser) {
// logged in so return true
return true;
}

// not logged in so redirect to login page with the return url
this.router.navigate(['/profile'], { queryParams: { returnUrl: state.url } });
return false;
}
}
37 changes: 30 additions & 7 deletions src/app/_services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';

import { User } from '../_models/user';
import { CookiesService } from '../_services/cookies.service'

@Injectable({
providedIn: 'root'
})
export class AuthService {
userId!: string;
email!: string;
/*private currentUserSubject: BehaviorSubject<User>;
private currentUserSubject?: BehaviorSubject<User>;
private isLoggedInSubject = new BehaviorSubject<boolean>(false);
isLoggedIn$: Observable<boolean> = this.isLoggedInSubject.asObservable();

constructor(){
this.currentUserSubject = new BehaviorSubject<User>();
constructor(
private afAuth: AngularFireAuth, private cookiesService: CookiesService,
private router: Router){
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}*/
public get currentUserValue(): any {
//return this.currentUserSubject?.value;
return this.isLoggedInSubject.value;
}

setUserData(userId: string, email: string) {
//this.currentUserSubject?.next(new User(userId, email));
var user = new User(userId, email);
//this.currentUserSubject?.next(user);
this.userId = userId;
this.email = email;
this.isLoggedInSubject.next(true);
}

getUserID() {
Expand All @@ -32,4 +41,18 @@ export class AuthService {
this.userId = '';
this.email = '';
}

logout (){
this.afAuth.signOut()
.then(() => {
this.cookiesService.setCookie("userID", "", 2);
this.cookiesService.setCookie("userEmail", "", 2);
this.isLoggedInSubject.next(false);
this.router.navigate(["/daily-phrase"]);
})
.catch(error => {
console.error('Error logging out:', error);
});
//this.currentUserSubject?.next(new User("", ""));
}
}
76 changes: 74 additions & 2 deletions src/app/_services/database.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import { AngularFireAuth } from '@angular/fire/auth';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { PhraseClass } from './../_models/PhraseClass';

Expand Down Expand Up @@ -43,6 +44,33 @@ export class DatabaseService {
return listRef.valueChanges();
}

/*getPhrasesToApproved(): Observable<any> {
const listRef = this.db.list(this.databasePath, (ref) =>
ref.orderByChild('approved').equalTo(false)
);
return listRef.valueChanges();
}*/

getPhrasesToApproved(): Observable<any[]> {
const listRef = this.db.list(this.databasePath, (ref) =>
ref.orderByChild('approved').equalTo(false)
);

return listRef.snapshotChanges().pipe(
map(actions =>
actions.map(action => ({
id: action.key,
// ...action.payload.val()
quote: this.getPayload(action).quote,
approved: this.getPayload(action).approved,
author: this.getPayload(action).author,
contributor: this.getPayload(action).contributor,
}))
)
);
}

async addPhrase(phrase: PhraseClass): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
this.auth.currentUser.then(user => {
Expand Down Expand Up @@ -71,9 +99,53 @@ export class DatabaseService {

getLastNPhrases(index: number) {
const listRef = this.db.list(this.databasePath, (ref) =>
ref.orderByChild('datePublication').limitToFirst(index)
ref.orderByChild('datePublication')
.startAt(null)
.limitToLast(index)
);

return listRef.valueChanges();
}
}

checkUserRole(userUID: string): Promise<string | null> {
return new Promise<string | null>((resolve, reject) => {
this.db.object(`users/${userUID}/role`).valueChanges().subscribe(
role => {
resolve(role as string);
},
error => {
reject(error);
}
);
});
}

/*isAdminLogged(userUID: string) {
return (this.checkUserRole(userUID) == "admin") ? true : false;
}*/
async isAdminLogged(userUID: string) {
var adminLogged = false;
try {
const userRole = await this.checkUserRole(userUID);

if (userRole === 'admin') {
adminLogged = true;
} else {
console.log('Utente non autenticato o ruolo non riconosciuto');
}
} catch (error) {
console.log('Errore durante il controllo del ruolo utente:', error);
}
return adminLogged;
}

assignUserRole(uid: string, role: string): Promise<void> {
return this.db.object(`users/${uid}/role`).set(role);
}


getPayload(action: any) {
return action.payload.val();
}
}

26 changes: 19 additions & 7 deletions src/app/_services/date.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,43 @@ import { Injectable } from '@angular/core';
export class DateService {
getCurrentDate(): string {
const today = new Date();

const day = String(today.getDate()).padStart(2, '0');
const month = String(today.getMonth() + 1).padStart(2, '0'); // Mese numerato da 0 a 11
const year = today.getFullYear();

return `${day}/${month}/${year}`;
}

getCurrentDateNotParsed(): string {
const today = new Date();

const day = String(today.getDate()).padStart(2, '0');
const month = String(today.getMonth() + 1).padStart(2, '0'); // Mese numerato da 0 a 11
const year = today.getFullYear();

return `${year}${month}${day}`;
}

getNumberDayOfTheYear(): number {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = (now.getTime() - start.getTime()) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);

return day;
}

parseDateToItalianFormat(dateString: string): string {
var dateParsed = "";
if (dateString.length >= 8){
const year = dateString.substr(0, 4);
const month = dateString.substr(4, 2);
const day = dateString.substr(6, 2);
dateParsed = `${day}/${month}/${year}`
}

return dateParsed;
}
}
5 changes: 3 additions & 2 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@ import { RegistrationComponent } from './registration/registration.component';
import { ProfileComponent } from './profile/profile.component';

import { AuthGuard } from './_helpers/auth.guard';
import { LoginGuard } from './_helpers/login.guard';

const routes: Routes = [
{ path: '', redirectTo: '/daily-phrase', pathMatch: 'full' },
{ path: "random-phrase", component: RandomPhraseComponent },
{ path: "daily-phrase", component: DailyPhraseComponent },
{ path: "historical", component: HistoricalPhraseComponent },
{ path: "profile", component: ProfileComponent, canActivate: [AuthGuard] },
{ path: "login", component: LoginComponent },
{ path: "registration", component: RegistrationComponent }
{ path: "login", component: LoginComponent, canActivate: [LoginGuard]},
{ path: "registration", component: RegistrationComponent, canActivate: [LoginGuard] }
];

@NgModule({
Expand Down
3 changes: 3 additions & 0 deletions src/app/component/navbar/navbar.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@
<a class="dropdown-item" [routerLink]="['/registration']" *ngIf="!userLogged"> <i
class="tim-icons fa fa-user-plus"> </i> Registrati
</a>
<a class="dropdown-item" [routerLink]="['/daily-phrase']"> <i
class="tim-icons icon-bullet-list-67"> </i> Giornaliero
</a>
<a class="dropdown-item" [routerLink]="['/historical']"> <i
class="tim-icons icon-bullet-list-67"> </i> Storico
</a> <a class="dropdown-item" [routerLink]="['/profile']" *ngIf="userLogged"> <i
Expand Down
66 changes: 35 additions & 31 deletions src/app/component/navbar/navbar.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { Component, OnInit, OnDestroy } from "@angular/core";
import { Location } from "@angular/common";
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { BehaviorSubject, Observable } from 'rxjs';

import { CookiesService } from '../../_services/cookies.service'
import { AuthService } from '../../_services/auth.service'

@Component({
selector: "app-navbar",
Expand All @@ -15,51 +17,53 @@ export class NavbarComponent implements OnInit, OnDestroy {
mobile_menu_visible: any = 0;
public isCollapsed = true;
closeResult!: string;
userLogged = false;
userLogged = false;//new BehaviorSubject(false);
isLoggedIn?: boolean;

constructor(
location: Location,
private cookiesService: CookiesService,
private afAuth: AngularFireAuth,
private router: Router) {
private authService: AuthService, private cookiesService: CookiesService) {
this.location = location;

}

ngOnInit() {
this.userLogged = (this.cookiesService.getCookie("userID") != "") ? true : false;
this.authService.isLoggedIn$.subscribe(isLoggedIn => {
console.log ("Cookie: " + this.cookiesService.getCookie("userID"));
//console.log ("CurrentValue: " + this.authService.currentUserValue());
var isLogged = (this.cookiesService.getCookie("userID") != "") ? true : false;
if (isLogged) {
this.userLogged = isLogged;
} else {
this.userLogged = isLoggedIn;
}

// Puoi eseguire altre operazioni qui in base allo stato di autenticazione
// ...
});
}

collapse() {
this.isCollapsed = !this.isCollapsed;
const navbar = document.getElementsByTagName("nav")[0];
if (!this.isCollapsed) {
navbar.classList.remove("navbar-transparent");
navbar.classList.add("bg-white");
} else {
navbar.classList.add("navbar-transparent");
navbar.classList.remove("bg-white");
}
collapse() {
this.isCollapsed = !this.isCollapsed;
const navbar = document.getElementsByTagName("nav")[0];
if (!this.isCollapsed) {
navbar.classList.remove("navbar-transparent");
navbar.classList.add("bg-white");
} else {
navbar.classList.add("navbar-transparent");
navbar.classList.remove("bg-white");
}
}

setCollapsed() {
this.isCollapsed = !this.isCollapsed;
}
setCollapsed() {
this.isCollapsed = !this.isCollapsed;
}

logout() {
this.afAuth.signOut()
.then(() => {
this.cookiesService.setCookie("userID", "", 2);
this.cookiesService.setCookie("userEmail", "", 2);
this.router.navigate(["/daily-phrase"]);
})
.catch(error => {
console.error('Error logging out:', error);
});
}
logout() {
this.authService.logout();
}

ngOnDestroy() {
ngOnDestroy() {

}
}
}
18 changes: 10 additions & 8 deletions src/app/daily-phrase/daily-phrase.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@
<div class="squares square1"></div>
<div class="squares square2"></div>
<div class="squares square3"></div>
<div class="squares square4"></div>
<!-- <div class="squares square4"></div> -->
<div class="squares square5"></div>
<div class="squares square6"></div>
<!-- <div class="squares square6"></div> -->
<div class="squares square7"></div>
<div class="container">
<div class="content-center brand">
<!-- <h1 class="h1-seo">DailyInspire•</h1> -->
<h3>{{quote}}</h3>
</div>
<div class="content-right brand">
<h6>{{author}}</h6>
<!-- height: 60%; -->
<div class="content-center brand" style="overflow-y: auto; width: 100%">
<blockquote><p style="color: white" class="blockquote blockquote-danger"> {{quote}}<br><br><small style="color: white"> - {{author}} </small></p></blockquote>
<!-- <h3><p>{{quote}}</p></h3> -->
<!-- <h6><p>{{author}}</p></h6> -->
</div>
<!-- <div class="content-right brand"> -->

<!-- </div> -->
</div>
</div>
</div>
Loading

0 comments on commit b15b48c

Please sign in to comment.