Add account settings, change password and profil edition components and auth gard and unauthorized interceptor.

This commit is contained in:
2019-01-30 21:43:57 +01:00
parent 9781bcfad9
commit 9ab6d35267
13 changed files with 455 additions and 5 deletions

View File

@@ -0,0 +1,55 @@
<h1>Paramètres</h1>
<div class="align-top">
<div class="card hoverable">
<a routerLink="/changePassword">
<div class="card-body row">
<div class="col-10">
<h4>
<i class="fa fa-lock blue-text"></i>
Mot de passe
</h4>
</div>
<div class="col-1 d-flex align-items-center text-right">
<i class="fa fa-chevron-right"></i>
</div>
</div>
<div class="card-body grey lighten-4">
Changer de mot de passe
</div>
</a>
</div>
<div class="card hoverable">
<a routerLink="/profilEdit">
<div class="card-body row">
<div class="col-10">
<h4>
<i class="fa fa-user-circle blue-text"></i>
Mes informations
</h4>
</div>
<div class="col-1 d-flex align-items-center text-right">
<i class="fa fa-chevron-right"></i>
</div>
</div>
<div class="card-body grey lighten-4">
Modifier les informations personnelles comme mon nom, mon adresse mail ou encore mon image de profil
</div>
</a>
</div>
<div class="card grey-text">
<div class="card-body row">
<div class="col-10">
<h4>
<i class="fa fa-cog"></i>
Paramètres de compte
</h4>
</div>
<div class="col-1 d-flex align-items-center text-right">
<i class="fa fa-chevron-right"></i>
</div>
</div>
<div class="card-body grey lighten-4">
Paramètres divers
</div>
</div>
</div>

View File

@@ -0,0 +1,24 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-account-settings',
templateUrl: './account-settings.component.html',
styles: [`
h4 i {
margin-right: 10px;
}
a, a:visited, a:hover {
color: black;
}
.card {
margin-right: 20px;
width: 30%;
display: inline-block;
vertical-align: top;
}
`]
})
export class AccountSettingsComponent {
}

View File

@@ -0,0 +1,61 @@
<div class="card col-md-8 offset-md-2 col-lg-6 offset-lg-3">
<div id="form" class="card-body">
<h4 class="card-title">Mot de passe</h4>
<form (ngSubmit)="onSubmit()" #changePasswordForm="ngForm">
<div class="md-form">
<input mdbActive
id="oldPassword"
name="oldPassword"
type="password"
class="form-control"
[(ngModel)]="model.oldPassword"
#oldPassword="ngModel"
data-error="Veuillez saisir votre mot de passe actuel"
data-sucess=""
required />
<label for="oldPassword">Mot de passe actuel</label>
</div>
<div class="md-form">
<input mdbActive
id="newPassword"
name="newPassword"
type="password"
class="form-control"
[(ngModel)]="model.newPassword"
#newPassword="ngModel"
data-error="Veuillez saisir votre nouveau mot de passe"
data-sucess=""
required />
<label for="newPassword">Nouveau mot de passe</label>
</div>
<div class="md-form">
<input mdbActive
id="confirmPassword"
name="confirmPassword"
type="password"
class="form-control"
[(ngModel)]="model.confirmPassword"
#confirmPassword="ngModel"
data-error="Veuillez confirmer votre nouveau mot de passe"
data-sucess=""
required />
<label for="confirmPassword">Confirmation de votre mot de passe</label>
</div>
<div class="card red lighten-2 text-center z-depth-2" *ngIf="error">
<div class="card-body">
<p class="white-text mb-0">{{error}}</p>
</div>
</div>
<div class="col submitFormArea">
<a routerLink="/accountSettings" class="indigo-text">
Annuler
</a>
<button class="float-right waves-effect waves-light indigo btn"
type="submit" [disabled]="!changePasswordForm.form.valid">
Suivant
</button>
</div>
</form>
</div>
</div>

View File

@@ -0,0 +1,36 @@
import { Component } from '@angular/core';
import { PasswordWrapper } from '../../core/entities';
import { ChangePasswordService } from './change-password.service';
@Component({
selector: 'app-change-password',
templateUrl: './change-password.component.html',
styles: [`
#form.card-body {
padding-bottom: 10px;
}
.submitFormArea {
line-height: 50px;
}
`]
})
export class ChangePasswordComponent {
model: PasswordWrapper = new PasswordWrapper('', '', '');
error: string;
constructor(
private changePasswordService: ChangePasswordService
) {}
onSubmit(): void {
if (this.model.newPassword !== this.model.confirmPassword) {
this.error = 'Les mots de passe saisis ne correspondent pas.';
} else {
this.changePasswordService.changePassword(this.model).subscribe(null, error => {
this.error = 'Le mot de passe saisi ne correspond pas au votre.';
});
}
}
}

View File

@@ -0,0 +1,15 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { PasswordWrapper } from '../../core/entities';
@Injectable()
export class ChangePasswordService {
constructor(private http: HttpClient) {}
changePassword(passwordWrapper: PasswordWrapper): Observable<any> {
return this.http.put('/api/account/changePassword', passwordWrapper);
}
}

View File

@@ -0,0 +1,60 @@
<input id="profilImageInput" type="file" (change)="uploadImage($event)" [hidden]="true">
<div class="col-md-8 offset-md-2 col-lg-6 offset-lg-3">
<div class="card">
<img id="profil-image" class="card-img-top"
(click)="triggerProfilImageChange()"
[src]="getAvatarUrl()"
alt="Card image cap"
mdbTooltip="Modifier mon image de profil"
placement="bottom">
<div id="form" class="card-body">
<form (ngSubmit)="onSubmit()" #profilEditionForm="ngForm">
<div class="md-form">
<input mdbActive
id="name"
name="name"
type="text"
class="form-control"
[(ngModel)]="model.name"
#name="ngModel"
data-error="Veuillez saisir votre nom d'utilisateur"
data-sucess=""
required />
<label for="name">Nom d'utilisateur</label>
</div>
<div class="md-form">
<input mdbActive
id="email"
name="email"
type="email"
class="form-control"
[(ngModel)]="model.email"
#email="ngModel"
data-error="Veuillez saisir votre adresse email"
data-sucess=""
required />
<label for="email">Email</label>
</div>
<div id="errorMsg" class="card red lighten-2 text-center z-depth-2">
<div class="card-body">
<p class="white-text mb-0">{{modelError}}</p>
</div>
</div>
<div id="resultMsg" class="card green lighten-2 text-center z-depth-2" >
<div class="card-body">
<p class="white-text mb-0">{{result}}</p>
</div>
</div>
<div class="col submitFormArea">
<a routerLink="/accountSettings" class="indigo-text">
Annuler
</a>
<button class="float-right waves-effect waves-light indigo btn"
type="submit" [disabled]="!profilEditionForm.form.valid">
Suivant
</button>
</div>
</form>
</div>
</div>
</div>

View File

@@ -0,0 +1,99 @@
import { Component, OnInit } from '@angular/core';
import { ProfilEditionService } from './profil-edition.service';
import { HttpEventType, HttpResponse } from '@angular/common/http';
import { User } from '../../core/entities';
import { AuthService } from '../../core/services/auth.service';
@Component({
selector: 'app-profil-edition',
templateUrl: './profil-edition.component.html',
styles: [`
#form {
padding-bottom: 10px;
}
.submitFormArea {
line-height: 50px;
}
#profil-image {
cursor: pointer;
}
#resultMsg, #errorMsg {
max-height: 0;
overflow: hidden;
transition: max-height 0.5s ease-out;
margin: 0;
}
`]
})
export class ProfilEditionComponent implements OnInit {
model: User;
selectedFiles: FileList;
currentFileUpload: File;
progress: { percentage: number } = { percentage: 0 };
modelError: string;
result: string;
constructor(
private profilEditionService: ProfilEditionService,
private authService: AuthService
) {}
ngOnInit(): void {
this.model = this.authService.getUser();
}
getAvatarUrl(): string {
return this.model.image
? `/api/images/loadAvatar/${this.model.image}`
: './assets/images/default_user.png';
}
triggerProfilImageChange(): void {
document.getElementById('profilImageInput').click();
}
uploadImage(event) {
this.selectedFiles = event.target.files;
this.progress.percentage = 0;
this.currentFileUpload = this.selectedFiles.item(0);
// This prevents error 400 if user doesn't select any file to upload and close the input file.
if (this.currentFileUpload) {
this.profilEditionService.uploadAvatarPicture(this.currentFileUpload).subscribe(result => {
if (result.type === HttpEventType.UploadProgress) {
this.progress.percentage = Math.round(100 * result.loaded / result.total);
} else if (result instanceof HttpResponse) {
console.log('File ' + result.body + ' completely uploaded!');
this.model.image = result.body as string;
this.authService.setAuthenticated(this.model);
}
this.selectedFiles = undefined;
});
}
}
onSubmit(): void {
this.profilEditionService.updateUser(this.model).subscribe(() => {
this.setMessage('Modification enregistrée.', false);
}, error => {
this.setMessage('L\'adresse mail saisie n\'est pas disponible.', true);
});
}
setMessage(message: string, error: boolean): void {
this[error ? 'modelError' : 'result'] = message;
const resultMsgDiv = document.getElementById(error ? 'errorMsg' : 'resultMsg');
resultMsgDiv.style.maxHeight = '64px';
setTimeout(() => {
resultMsgDiv.style.maxHeight = '0px';
setTimeout(() => {
this[error ? 'modelError' : 'result'] = undefined;
}, 550);
}, 3000);
}
}

View File

@@ -0,0 +1,26 @@
import { Injectable } from '@angular/core';
import {HttpClient, HttpRequest, HttpEvent} from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from '../../core/entities';
@Injectable()
export class ProfilEditionService {
constructor(private http: HttpClient) {}
uploadAvatarPicture(file: File): Observable<HttpEvent<{}>> {
const formData: FormData = new FormData();
formData.append('file', file);
return this.http.request(new HttpRequest(
'POST', '/api/images/uploadAvatar', formData, {
reportProgress: true,
responseType: 'text'
}
));
}
updateUser(user: User): Observable<any> {
return this.http.put<any>(`/api/account/`, user);
}
}

View File

@@ -2,7 +2,7 @@ import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'; import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http'; import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
// Dependencies // Dependencies
@@ -11,6 +11,9 @@ import { MDBBootstrapModule } from 'angular-bootstrap-md';
// Router // Router
import { appRoutes } from './app.routing'; import { appRoutes } from './app.routing';
// Guard
import { AuthGuard } from './core/guards/auth.guard';
// Components // Components
import { AppComponent } from './app.component'; import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component'; import { HeaderComponent } from './header/header.component';
@@ -18,6 +21,9 @@ import { LoginComponent } from './login/login.component';
import { DisconnectionComponent } from './disconnection/disconnection.component'; import { DisconnectionComponent } from './disconnection/disconnection.component';
import { HomeComponent } from './home/home.component'; import { HomeComponent } from './home/home.component';
import { MyPostsComponent } from './posts/myPosts/my-posts.component'; import { MyPostsComponent } from './posts/myPosts/my-posts.component';
import { AccountSettingsComponent } from './account-settings/account-settings.component';
import { ChangePasswordComponent } from './account-settings/change-password/change-password.component';
import { ProfilEditionComponent } from './account-settings/profil-edition/profil-edition.component';
// Reusable components // Reusable components
import { PostCardComponent } from './core/post-card/post-card.component'; import { PostCardComponent } from './core/post-card/post-card.component';
@@ -29,6 +35,9 @@ import { AuthService } from './core/services/auth.service';
import { HomeService } from './home/home.service'; import { HomeService } from './home/home.service';
import { LoginService } from './login/login.service'; import { LoginService } from './login/login.service';
import { MyPostsService } from './posts/myPosts/my-posts.service'; import { MyPostsService } from './posts/myPosts/my-posts.service';
import { ChangePasswordService } from './account-settings/change-password/change-password.service';
import { ProfilEditionService } from './account-settings/profil-edition/profil-edition.service';
import { UnauthorizedInterceptor } from './core/interceptors/unauthorized.interceptor';
@NgModule({ @NgModule({
declarations: [ declarations: [
@@ -39,7 +48,10 @@ import { MyPostsService } from './posts/myPosts/my-posts.service';
HomeComponent, HomeComponent,
PostCardComponent, PostCardComponent,
SpinnerComponent, SpinnerComponent,
MyPostsComponent MyPostsComponent,
AccountSettingsComponent,
ChangePasswordComponent,
ProfilEditionComponent
], ],
imports: [ imports: [
BrowserModule, BrowserModule,
@@ -54,11 +66,15 @@ import { MyPostsService } from './posts/myPosts/my-posts.service';
) )
], ],
providers: [ providers: [
AuthGuard,
HeaderService, HeaderService,
AuthService, AuthService,
HomeService, HomeService,
LoginService, LoginService,
MyPostsService MyPostsService,
ChangePasswordService,
ProfilEditionService,
{ provide: HTTP_INTERCEPTORS, useClass: UnauthorizedInterceptor, multi: true }
], ],
bootstrap: [AppComponent] bootstrap: [AppComponent]
}) })

View File

@@ -1,14 +1,20 @@
import { Routes } from '@angular/router'; import { Routes } from '@angular/router';
import { AuthGuard } from './core/guards/auth.guard';
import { LoginComponent } from './login/login.component'; import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component'; import { HomeComponent } from './home/home.component';
import { DisconnectionComponent } from './disconnection/disconnection.component'; import { DisconnectionComponent } from './disconnection/disconnection.component';
import { MyPostsComponent } from './posts/myPosts/my-posts.component'; import { MyPostsComponent } from './posts/myPosts/my-posts.component';
import { AccountSettingsComponent } from './account-settings/account-settings.component';
export const appRoutes: Routes = [ export const appRoutes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent }, { path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent }, { path: 'login', component: LoginComponent },
{ path: 'disconnection', component: DisconnectionComponent }, { path: 'disconnection', component: DisconnectionComponent },
{ path: 'myPosts', component: MyPostsComponent}, { path: 'myPosts', component: MyPostsComponent, canActivate: [AuthGuard] },
{ path: 'accountSettings', component: AccountSettingsComponent, canActivate: [AuthGuard] },
{ path: '**', redirectTo: '/home' } { path: '**', redirectTo: '/home' }
]; ];

View File

@@ -0,0 +1,26 @@
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let result: boolean;
if (this.authService.isAuthenticated()) {
result = true;
} else {
result = false;
this.router.navigate(['/login']);
}
return result;
}
}

View File

@@ -0,0 +1,26 @@
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';
@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private authService: AuthService
) {}
intercept(pRequest: HttpRequest<any>, pNext: HttpHandler): Observable<HttpEvent<any>> {
return pNext.handle(pRequest).pipe(catchError(err => {
if (err.status === 401) {
this.authService.setAnonymous();
this.router.navigate(['/login']);
}
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}