Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • eosc-pillar/ffds/ffds-register-front
1 result
Show changes
Showing
with 490 additions and 21 deletions
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NbMenuItem, NbSidebarService } from '@nebular/theme';
import { AppConfiguration } from '../AppConfiguration';
import { slideInAnimation } from '../route.animation';
import { AuthService } from './services/auth.service';
import { TokenStorageService } from './services/token-storage.service';
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.scss'],
animations: [slideInAnimation]
})
export class AuthenticationComponent implements OnInit {
isLoggedIn = false;
username: string;
public static routeNamesObject = {}
constructor(private tokenStorageService: TokenStorageService) { }
ngOnInit(): void {
this.isLoggedIn = !!this.tokenStorageService.getToken();
if (this.isLoggedIn) {
const user = this.tokenStorageService.getUser();
this.username = user.username;
}
}
logout(): void {
this.tokenStorageService.signOut();
window.location.reload();
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NebularModule } from '../nebular.module';
import { BrowserModule } from '@angular/platform-browser';
import { AuthenticationComponent } from './authentication.component';
import { RouterModule } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignoutComponent } from './signout/signout.component';
import { SignupComponent } from './signup/signup.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [SigninComponent,AuthenticationComponent, SigninComponent, SignoutComponent, SignupComponent],
imports: [
CommonModule,
FormsModule,
BrowserModule,
RouterModule,
ReactiveFormsModule,
BrowserAnimationsModule,
NebularModule,
],
exports:[
SigninComponent
]
})
export class AuthenticationModule {
}
import { HTTP_INTERCEPTORS, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { TokenStorageService } from '../services/token-storage.service';
import { Observable } from 'rxjs';
const TOKEN_HEADER_KEY = 'x-access-token';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private token: TokenStorageService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let authReq = req;
const token = this.token.getToken();
if (token != null) {
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, token) });
}
return next.handle(authReq);
}
}
export const authInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];
\ No newline at end of file
......@@ -6,11 +6,12 @@ import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
_next: ActivatedRouteSnapshot,
_state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isLoggedIn();
}
......
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { TokenStorageService } from './token-storage.service';
import { map } from "rxjs/operators";
import { AppConfiguration } from 'src/app/AppConfiguration';
const AUTH_API = "http://localhost:8080/harvester/auth";
const F2DSAPI = "http://51.178.69.147"
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient, private tokenService: TokenStorageService, private appConfig:AppConfiguration) { }
login(credentials): Observable<any> {
let data: any
data = this.http.post(AUTH_API + '/signin', {
email: credentials.email,
password: credentials.password
}, httpOptions);
return data;
}
register(user): Observable<any> {
return this.http.post(AUTH_API + '/signup', {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
password: user.password
}, httpOptions);
}
getF2DSAuthToken():Observable<any> {
return this.http.post(this.appConfig.fdpurl+'/tokens', {
email: this.appConfig.fdpemail,
password: this.appConfig.fdppassword
},httpOptions);
}
public isLoggedIn() {
return this.tokenService.getToken() !== null;
}
public logout() {
this.tokenService.removeToken();
}
}
import { TestBed } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
import { TokenStorageService } from './token-storage.service';
describe('AuthGuard', () => {
let guard: AuthGuard;
describe('TokenStorageService', () => {
let service: TokenStorageService;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
service = TestBed.inject(TokenStorageService);
});
it('should be created', () => {
expect(guard).toBeTruthy();
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
const TOKEN_KEY = 'auth-token';
const USER_KEY = 'auth-user';
const F2DS_TOKEN_KEY = 'f2ds-token';
@Injectable({
providedIn: 'root'
})
export class TokenStorageService {
constructor() { }
signOut(): void {
window.sessionStorage.clear();
}
public saveToken(token: string,f2dsToken:string): void {
window.sessionStorage.removeItem(TOKEN_KEY);
window.sessionStorage.setItem(TOKEN_KEY, token);
window.sessionStorage.setItem(F2DS_TOKEN_KEY, f2dsToken);
}
public getToken(): string {
return window.sessionStorage.getItem(TOKEN_KEY);
}
public saveUser(user): void {
window.sessionStorage.removeItem(USER_KEY);
window.sessionStorage.setItem(USER_KEY, JSON.stringify(user));
}
public getUser(): any {
return JSON.parse(sessionStorage.getItem(USER_KEY));
}
public removeToken(){
window.localStorage.removeItem(TOKEN_KEY);
}
}
<div style="display: flex;justify-content: center;">
<nb-card status="info" size="small" style="width: 24em;">
<nb-card-header style="text-align: center;">Welcome to the F2DS API register</nb-card-header>
<nb-card-body class="example-items-col" style="overflow: hidden;">
<div class="col-md-12">
<div class="card card-container">
<form *ngIf="!isLoggedIn" name="formGroup" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<!--Email -->
<div class="form-group">
<label for="email">Email</label>
<nb-form-field>
<nb-icon nbPrefix icon="at-outline" pack="eva"></nb-icon>
<input nbInput fullWidth type="text" class="form-control" name="email" [(ngModel)]="formGroup.email"
required #email="ngModel" />
</nb-form-field>
<!-- Email error-->
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && email.invalid">
Email is required!
</div>
</div>
<!--Password-->
<div class="form-group">
<label for="password">Password</label>
<nb-form-field>
<input nbInput fullWidth [type]="getInputType()" class="form-control" name="password"
[(ngModel)]="formGroup.password" required minlength="6" #password="ngModel" />
<button type="button" nbSuffix nbButton ghost (click)="toggleShowPassword()">
<nb-icon [icon]="showPassword ? 'eye-outline' : 'eye-off-2-outline'" pack="eva"
[attr.aria-label]="showPassword ? 'hide password' : 'show password'">
</nb-icon>
</button>
</nb-form-field>
<!-- Password error-->
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && password.invalid">
<div *ngIf="password.errors.required">Password is required</div>
<div *ngIf="password.errors.minlength">
Password must be at least 6 characters
</div>
</div>
</div>
<br>
<div class="form-group" style="text-align: center;">
<button nbButton status="info" class="btn btn-primary btn-block">
Login
</button>
</div>
<div class="form-group">
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && isLoginFailed">
Login failed: {{ errorMessage }}
</div>
</div>
</form>
<section class="another-action" aria-label="Register" style="text-align: center; margin-top: 20px;">
Don't have an account ? <a class="text-link" routerLink="../signup">Register</a>
</section>
<!---->
<div class="alert alert-success" *ngIf="isLoggedIn">
Logged in as
</div>
</div>
</div>
</nb-card-body>
</nb-card>
</div>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
import { SigninComponent } from './signin.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
describe('SigninComponent', () => {
let component: SigninComponent;
let fixture: ComponentFixture<SigninComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
declarations: [ SigninComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
fixture = TestBed.createComponent(SigninComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
......
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { SmartHarvesterUser } from 'src/app/user/model/user';
import { AuthService } from '../services/auth.service';
import { TokenStorageService } from '../services/token-storage.service';
export interface F2DSResponse{
token:string;
}
@Component({
selector: 'app-signin',
templateUrl: './signin.component.html',
styleUrls: ['./signin.component.scss'],
})
export class SigninComponent implements OnInit {
f2dsToken: string;
isSubmitted = false;
isLoggedIn = false;
isLoginFailed = false;
errorMessage = '';
showPassword = false;
user: SmartHarvesterUser;
formGroup = new FormGroup({
email: new FormControl(''),
password: new FormControl(''),
});
constructor(private authService: AuthService, private router: Router, private tokenStorage: TokenStorageService) { }
ngOnInit(): void {
if (this.tokenStorage.getToken()) {
// Uncomment line to avoid re-authentication if token is still valid
//this.isLoggedIn = true;
}
this.authService.getF2DSAuthToken().subscribe((response:F2DSResponse) => {
if (response) this.f2dsToken = response.token;
console.log("F2ds token is : ", this.f2dsToken)
})
}
get formControls() { return this.formGroup.controls; }
onSubmit(): void {
this.authService.login(this.formGroup).subscribe(
data => {
this.tokenStorage.saveToken(data.accessToken, this.f2dsToken);
this.tokenStorage.saveUser(data);
this.isLoginFailed = false;
this.isLoggedIn = true;
console.log("User data : ", data)
this.router.navigateByUrl('/dashboard');
//this.reloadPage();
},
err => {
this.errorMessage = err.error.message;
console.error("Error : ", this.errorMessage)
this.isLoginFailed = true;
}
);
}
reloadPage(): void {
window.location.reload();
}
getInputType() {
if (this.showPassword) {
return 'text';
}
return 'password';
}
toggleShowPassword() {
this.showPassword = !this.showPassword;
}
}
<p>signout works!</p>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AccountLoginComponent } from './account.login.component';
import { SignoutComponent } from './signout.component';
describe('LoginComponent', () => {
let component: AccountLoginComponent;
let fixture: ComponentFixture<AccountLoginComponent>;
describe('SignoutComponent', () => {
let component: SignoutComponent;
let fixture: ComponentFixture<SignoutComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AccountLoginComponent ]
declarations: [ SignoutComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AccountLoginComponent);
fixture = TestBed.createComponent(SignoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
......
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-account',
templateUrl: './account.component.html',
styleUrls: ['./account.component.scss']
selector: 'app-signout',
templateUrl: './signout.component.html',
styleUrls: ['./signout.component.scss']
})
export class AccountComponent implements OnInit {
export class SignoutComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
<div style="display: flex;justify-content: center;">
<nb-card status="success" size="small" style="width: 24em;height: auto;">
<nb-card-header style="text-align: center;">Create an account to F2DS API register</nb-card-header>
<nb-card-body class="example-items-col" style="overflow: hidden;">
<div class="col-md-12">
<div class="card card-container">
<form *ngIf="!isLoggedIn" name="formGroup" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm"
novalidate>
<div class="form-group">
<label for="firstName">First Name</label>
<nb-form-field>
<input nbInput fullWidth type="text" class="form-control" name="firstName"
[(ngModel)]="formGroup.firstName" required #email="ngModel" />
</nb-form-field>
<!-- Email error-->
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && email.invalid">
First name is required!
</div>
</div>
<!--Last name-->
<div class="form-group">
<label for="firstName">Last Name</label>
<nb-form-field>
<input nbInput fullWidth type="text" class="form-control" name="lastName"
[(ngModel)]="formGroup.lastName" required #email="ngModel" />
</nb-form-field>
<!-- Email error-->
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && email.invalid">
Last name is required!
</div>
</div>
<!--Email -->
<div class="form-group">
<label for="email">Email</label>
<nb-form-field>
<nb-icon nbPrefix icon="at-outline" pack="eva"></nb-icon>
<input nbInput fullWidth type="text" class="form-control" name="email"
[(ngModel)]="formGroup.email" required #email="ngModel" />
</nb-form-field>
<!-- Email error-->
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && email.invalid">
Email is required!
</div>
</div>
<!--Password-->
<div class="form-group">
<label for="password">Password</label>
<nb-form-field>
<input nbInput fullWidth type="password" class="form-control" name="password"
[(ngModel)]="formGroup.password" required minlength="6" #password="ngModel" />
<button type="button" nbSuffix nbButton ghost (click)="toggleShowPassword()">
</button>
</nb-form-field>
<label for="password">Confirm password</label>
<nb-form-field>
<input nbInput fullWidth type="password" class="form-control" name="passwordConfirm"
[(ngModel)]="formGroup.passwordConfirm" required minlength="6" #password="ngModel" />
<button type="button" nbSuffix nbButton ghost (click)="toggleShowPassword()">
</button>
</nb-form-field>
<!-- Password error-->
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && password.invalid">
<div *ngIf="password.errors.required">Password is required</div>
<div *ngIf="password.errors.minlength">
Password must be at least 6 characters
</div>
</div>
</div>
<br>
<div class="form-group" style="text-align: center;">
<button nbButton status="success" class="btn btn-primary btn-block">
Sign Up
</button>
</div>
<div class="form-group">
<div class="alert alert-danger" role="alert" *ngIf="f.submitted && isLoginFailed">
Login failed: {{ errorMessage }}
</div>
</div>
</form>
<section class="another-action" aria-label="Register" style="text-align: center; margin-top: 20px;">
Already have an account ? <a class="text-link" routerLink="../signin">Sign In</a>
</section>
<!---->
<div class="alert alert-success" *ngIf="isLoggedIn">
Logged in as
</div>
</div>
</div>
</nb-card-body>
</nb-card>
</div>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
import { SignupComponent } from './signup.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
describe('SignupComponent', () => {
let component: SignupComponent;
let fixture: ComponentFixture<SignupComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
declarations: [ SignupComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
fixture = TestBed.createComponent(SignupComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
......