Skip to content

Commit

Permalink
feat: remove required login
Browse files Browse the repository at this point in the history
  • Loading branch information
69pmb authored and pierre-marie broca committed Oct 26, 2023
1 parent d58de20 commit 90f9660
Show file tree
Hide file tree
Showing 13 changed files with 162 additions and 84 deletions.
6 changes: 0 additions & 6 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,39 +10,34 @@ const routes: Routes = [
import('./application-modules/dashboard/dashboard.module').then(
m => m.DashboardModule
),
canActivate: [AuthGard],
},
{
path: 'movie',
loadChildren: () =>
import('./application-modules/movie-detail/movie-detail.module').then(
m => m.MovieDetailModule
),
canActivate: [AuthGard],
},
{
path: 'serie',
loadChildren: () =>
import('./application-modules/serie-detail/serie-detail.module').then(
m => m.SerieDetailModule
),
canActivate: [AuthGard],
},
{
path: 'person',
loadChildren: () =>
import('./application-modules/person-detail/person-detail.module').then(
m => m.PersonDetailModule
),
canActivate: [AuthGard],
},
{
path: 'release',
loadChildren: () =>
import('./application-modules/release/release.module').then(
m => m.ReleaseModule
),
canActivate: [AuthGard],
},
{
path: 'datas',
Expand All @@ -58,7 +53,6 @@ const routes: Routes = [
import('./application-modules/discover/discover.module').then(
m => m.DiscoverModule
),
canActivate: [AuthGard],
},
{
path: 'tags',
Expand Down
10 changes: 5 additions & 5 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {filter} from 'rxjs/operators';
import {Router, NavigationStart, NavigationEnd} from '@angular/router';
import {Router, NavigationStart} from '@angular/router';
import {Component, OnInit} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

Expand All @@ -8,6 +8,7 @@ import {TabsService} from './service/tabs.service';
import {AuthService} from './service/auth.service';
import {MyDatasService} from './service/my-datas.service';
import {MyTagsService} from './service/my-tags.service';
import {MenuService} from './service/menu.service';

@Component({
selector: 'app-root',
Expand All @@ -21,7 +22,8 @@ export class AppComponent implements OnInit {
private auth: AuthService,
private myDatasService: MyDatasService<Data>,
private myTagsService: MyTagsService,
private translate: TranslateService
private translate: TranslateService,
private menuService: MenuService
) {}

ngOnInit(): void {
Expand All @@ -30,9 +32,7 @@ export class AppComponent implements OnInit {
.subscribe((event: NavigationStart) => {
this.tabsService.onNavigation(event);
});
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(() => window.scrollTo(0, 0));
this.menuService.event$.subscribe(() => window.scrollTo(0, 0));
this.auth.getCurrentUser(false);
this.auth.user$.subscribe(user => {
if (user) {
Expand Down
30 changes: 16 additions & 14 deletions src/app/app.gards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import {
RouterStateSnapshot,
} from '@angular/router';
import {Injectable, OnDestroy} from '@angular/core';
import {Subscription} from 'rxjs';
import {Observable, Subscription, of} from 'rxjs';
import {map} from 'rxjs/operators';

import {AuthService} from './service/auth.service';

Expand All @@ -21,23 +22,24 @@ export class AuthGard implements CanActivate, OnDestroy {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> {
): Observable<boolean> {
console.log('canActivate', state.url);
try {
return this.auth.isAuthenticated().then(isAuth => {
console.log('isAuth', isAuth);
if (!isAuth) {
console.log('not isAuthenticated');
this.router.navigate(['/login']);
return false;
}
console.log('logged');
// this.router.navigate([state.url]);
return true;
});
return this.auth.isAuthenticated().pipe(
map(isAuth => {
console.log('isAuth', isAuth);
if (!isAuth) {
console.log('not isAuthenticated');
this.auth.redirectToLogin(state.url);
return false;
}
console.log('logged');
return true;
})
);
} catch (err) {
console.log(err);
return new Promise(() => {});
return of(false);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<h2>{{ 'login.connect.title' | translate }}:</h2>
<h2 *ngIf="!(redirect$ | async)">{{ 'login.connect.title' | translate }}:</h2>
<h2 *ngIf="redirect$ | async">{{ 'login.connect.redirect' | translate }}:</h2>
<div class="connect-content">
<form #connectForm="ngForm">
<mat-error>{{ message }}</mat-error>
Expand Down Expand Up @@ -43,6 +44,9 @@ <h2>{{ 'login.connect.title' | translate }}:</h2>
</mat-form-field>

<div class="connect-footer">
<button class="btn btn-outline-primary" (click)="cancel()">
{{ 'global.cancel' | translate }}
</button>
<button
type="submit"
class="btn btn-outline-primary"
Expand Down
41 changes: 32 additions & 9 deletions src/app/application-modules/login/connect/connect.component.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import * as crypto from 'crypto-js';
import {TranslateService} from '@ngx-translate/core';

import {AuthService} from '../../../service/auth.service';
import {TitleService} from '../../../service/title.service';
import {map} from 'rxjs/operators';
import {Constants} from '../../../constant/constants';
import {Subscription, combineLatest} from 'rxjs';

@Component({
selector: 'app-connect',
templateUrl: './connect.component.html',
styleUrls: ['./connect.component.scss'],
})
export class ConnectComponent implements OnInit {
export class ConnectComponent implements OnInit, OnDestroy {
name: string;
password: string;
message: string;
subs: Subscription[] = [];
redirect$ = this.active.queryParams.pipe(
map(q => q[Constants.LOGIN_REDIRECT_URL])
);

constructor(
private auth: AuthService,
private router: Router,
private translate: TranslateService,
private title: TitleService
private title: TitleService,
private active: ActivatedRoute
) {}

ngOnInit(): void {
Expand All @@ -29,16 +37,31 @@ export class ConnectComponent implements OnInit {

login(): void {
if (this.name && this.password) {
this.auth
.login(this.name, crypto.SHA512(this.password).toString())
.then(isAuth => {
this.subs.push(
combineLatest([
this.redirect$,
this.auth.login(this.name, crypto.SHA512(this.password).toString()),
]).subscribe(([redirect, isAuth]) => {
if (isAuth) {
this.message = this.translate.instant('login.connect.connected');
this.router.navigateByUrl('/');
this.router.navigateByUrl(redirect ?? '/');
} else {
this.message = this.translate.instant('login.connect.wrong');
}
});
})
);
}
}

cancel(): void {
this.subs.push(
this.redirect$.subscribe(redirect =>
this.router.navigateByUrl(redirect ?? '/')
)
);
}

ngOnDestroy(): void {
this.subs.forEach(sub => sub.unsubscribe());
}
}
2 changes: 2 additions & 0 deletions src/app/constant/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ export class Constants {

static readonly TRANSLATION_KEY_REGEX =
/^[a-z]+[a-z_-]*[a-z]+\.[a-z._-]*[a-z]+$/;

static readonly LOGIN_REDIRECT_URL = 'redirect';
}
61 changes: 38 additions & 23 deletions src/app/service/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {BehaviorSubject} from 'rxjs';
import {BehaviorSubject, Observable, from} from 'rxjs';
import {Router} from '@angular/router';
import {Injectable} from '@angular/core';
import jwt_decode from 'jwt-decode';
Expand All @@ -12,6 +12,8 @@ import {UtilsService} from './utils.service';
import {Utils} from '../shared/utils';
import {Dropbox} from '../constant/dropbox';
import {User} from '../model/user';
import {Constants} from '../constant/constants';
import {map, catchError, tap} from 'rxjs/operators';

@Injectable({
providedIn: 'root',
Expand Down Expand Up @@ -60,16 +62,19 @@ export class AuthService {
return new Promise(resolve => resolve(undefined));
}

isAuthenticated(): Promise<User> {
isAuthenticated(): Observable<User> {
console.log('isAuthenticated');
let user = this.user$.getValue();
if (!user || !user.id) {
user = AuthService.decodeToken();
if (!user || !user.id) {
return this.reject(true);
}
}
return new Promise(resolve => resolve(user));
return this.user$.pipe(
map(user => {
if (!user || !user.id) {
user = AuthService.decodeToken();
if (!user || !user.id) {
return undefined;
}
}
return user;
})
);
}

/**
Expand Down Expand Up @@ -101,21 +106,22 @@ export class AuthService {
}
}

login(name: string, password: string): Promise<User> {
return this.getUserFile()
.then((users: User[]) => {
const found_user = users.find(
login(name: string, password: string): Observable<boolean> {
return from(this.getUserFile()).pipe(
map((users: User[]) =>
users.find(
(user: User) => user.name === name && user.password === password
);
if (found_user) {
AuthService.setToken(AuthService.createToken(found_user));
this.user$.next(found_user);
return found_user;
} else {
return this.reject(false);
)
),
tap(user => {
if (user) {
AuthService.setToken(AuthService.createToken(user));
this.user$.next(user);
}
})
.catch(err => this.serviceUtils.handlePromiseError(err, this.toast));
}),
map(u => !!u),
catchError(err => this.serviceUtils.handlePromiseError(err, this.toast))
);
}

checkAnswer(name: string, answer: string): Promise<boolean> {
Expand Down Expand Up @@ -233,4 +239,13 @@ export class AuthService {
this.user$.next(undefined);
this.router.navigate(['/login']);
}

redirectToLogin(url: string): void {
localStorage.removeItem('token');
const param = {};
param[Constants.LOGIN_REDIRECT_URL] = url;
this.router.navigate(['/login/connect'], {
queryParams: param,
});
}
}
10 changes: 9 additions & 1 deletion src/app/service/menu.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import {BehaviorSubject} from 'rxjs';
import {Injectable} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
import {filter, map, shareReplay} from 'rxjs/operators';

@Injectable({
providedIn: 'root',
})
export class MenuService {
visible$ = new BehaviorSubject<boolean>(true);
scrollTo$ = new BehaviorSubject<number>(0);
event$ = this.router.events.pipe(
filter((e): e is NavigationEnd => e instanceof NavigationEnd),
shareReplay(1)
);

constructor() {}
url$ = this.event$.pipe(map(e => e.url));

constructor(private router: Router) {}
}
Loading

0 comments on commit 90f9660

Please sign in to comment.