Skip to content
Snippets Groups Projects
Commit c5c0e2e3 authored by Paulo's avatar Paulo
Browse files

refactor(auth): Ajout de la fonctionalité de authentification (imcomplet)

parent 7b053bd3
No related branches found
No related tags found
No related merge requests found
Showing
with 369 additions and 98 deletions
......@@ -9412,6 +9412,11 @@
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"dev": true
},
"ng2-cookies": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/ng2-cookies/-/ng2-cookies-1.0.12.tgz",
"integrity": "sha1-Pz5hPgE3sGSbcFxngHS0vQgUnMw="
},
"ngx-filesaver": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/ngx-filesaver/-/ngx-filesaver-9.0.0.tgz",
......
......@@ -24,6 +24,7 @@
"@nebular/auth": "^6.2.1",
"@nebular/theme": "^5.1.0",
"file-saver": "^2.0.2",
"ng2-cookies": "^1.0.12",
"ngx-filesaver": "^9.0.0",
"rxjs": "^6.5.5",
"stream": "0.0.2",
......
......@@ -15,7 +15,7 @@
badgePosition="right"
nbContextMenuTag="my-context-menu">
</nb-user>
<button routerLink="/auth/login" nbContextMenuPlacement="right" outline nbButton >Login</button>
<button routerLink="/login" nbContextMenuPlacement="right" outline nbButton >Login</button>
</nb-layout-header>
......
<h1 style="text-align:center">AAI EOSC-Pillar</h1>
<nb-card status="info" style="width: 50%;height: auto; margin: auto;" >
<nb-card-header style="text-align: center;">Welcome to the API register</nb-card-header>
<nb-card-body class="example-items-col">
<h3>AAI EOSC-Pillar (to integrate)</h3>
<div class="login" style="text-align: center;">
<h2 class="login-header">Log in</h2>
<form [formGroup]="loginForm" class="login-container" (ngSubmit)="login()">
<mat-card class="example-card">
<mat-card-header>
<mat-card-title>Login</mat-card-title>
</mat-card-header>
<mat-card-content>
<form class="example-form">
<table class="example-full-width" cellspacing="0">
<tr>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="Username" [(ngModel)]="username" name="username" required>
</mat-form-field>
</td>
</tr>
<tr>
<td><mat-form-field class="example-full-width">
<input matInput placeholder="Password" [(ngModel)]="password" type="password" name="password" required>
</mat-form-field></td>
</tr>
<tr>
<td>
<a routerLink="/user" routerLinkActive="active">Register</a>
</td>
</tr>
</table>
</form>
<mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button (click)="login()" color="primary">Login</button>
</mat-card-actions>
</mat-card>
<p [ngClass]="{ 'has-error': isSubmitted && formControls.email.errors }">
<label class="label" for="email">Email:</label>
<input style="margin: auto;" type="email" nbInput shape="semi-round" placeholder="Email" formControlName="email">
</p>
<div *ngIf="isSubmitted && formControls.email.errors" class="help-block">
<div *ngIf="formControls.email.errors.required">Email is required</div>
</div>
<p [ngClass]="{ 'has-error': isSubmitted && formControls.password.errors }">
<label class="label" for="passord">Password:</label>
<input type="password" nbInput shape="semi-round" placeholder="Password" formControlName="password">
</p>
<div *ngIf="isSubmitted && formControls.password.errors" class="help-block">
<div *ngIf="formControls.password.errors.required">Password is required</div>
</div>
<p>
<input type="submit" nbButton shape="rectangle" status="info" value="Log in" style="width: auto;height: auto;">
</p>
</form>
</div>
</nb-card-body>
</nb-card>
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);
body {
background: #456;
font-family: 'Open Sans', sans-serif;
}
.has-error input[type="email"],
.has-error input[type="password"] {
border-color: rgb(216, 12, 12);
color: rgb(230, 14, 14);
}
label {
width: auto;
}
\ No newline at end of file
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { AuthService } from './services/auth.service';
@Component({
selector: 'app-login',
......@@ -7,23 +9,42 @@ import {Router} from '@angular/router';
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
isSubmitted = false;
public isLoggedIn = false;
constructor(private router: Router) { }
username: string;
password: string;
constructor(private authService: AuthService, private router: Router, private formBuilder: FormBuilder) { }
ngOnInit(): void {
//Create form
this.loginForm = this.formBuilder.group({
email: ['', Validators.required],
password: ['', Validators.required]
});
//Check crendentials
this.isLoggedIn = this.authService.checkCredentials();
ngOnInit() {
}
login() : void {
if(this.username == 'admin' && this.password == 'admin'){
this.router.navigate(["/"]);
}else {
alert("Invalid credentials");
}
get formControls() { return this.loginForm.controls; }
login() {
const val = this.loginForm.value;
if (val.email && val.password) {
this.authService.login(val.email, val.password)
.subscribe(
() => {
console.log("User is logged in");
this.router.navigateByUrl('/');
}
);
}
}
}
export interface authObj {
"username": string,
"email": string
}
\ No newline at end of file
import { TestBed } from '@angular/core/testing';
import { AuthGuard } from './auth.guard';
describe('AuthGuard', () => {
let guard: AuthGuard;
beforeEach(() => {
TestBed.configureTestingModule({});
guard = TestBed.inject(AuthGuard);
});
it('should be created', () => {
expect(guard).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isLoggedIn();
}
}
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(AuthService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { shareReplay,catchError } from "rxjs/operators";
import { User } from 'src/app/user/model/user';
import { Cookie } from 'ng2-cookies';
@Injectable({
providedIn: 'root'
})
export class AuthService {
public clientId = 'newClient';
public redirectUri = 'http://localhost:8089/';
constructor(private http: HttpClient) { }
retrieveToken(code) {
let params = new URLSearchParams();
params.append('grant_type','authorization_code');
params.append('client_id', this.clientId);
params.append('client_secret', 'newClientSecret');
params.append('redirect_uri', this.redirectUri);
params.append('code',code);
let headers =
new HttpHeaders({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'});
this.http.post('http://localhost:8083/auth/smartharvester/protocol/openid-connect/token',
params.toString(), { headers: headers })
.subscribe( data => this.saveToken(data), err => alert('Invalid Credentials'));
}
login(email:string, password:string ) {
return this.http.post<User>('/api/login', {email, password})
.pipe(
// defaults to all values so we set it to just keep and replay last one
shareReplay(1))
}
saveToken(token) {
let expireDate = new Date().getTime() + (1000 * token.expires_in);
Cookie.set("access_token", token.access_token, expireDate);
console.log('Obtained Access token');
window.location.href = 'http://localhost:8089';
}
getResource(resourceUrl) : Observable<any> {
var headers = new HttpHeaders({
'Content-type': 'application/x-www-form-urlencoded; charset=utf-8',
'Authorization': 'Bearer '+ Cookie.get('access_token')});
return this.http.get(resourceUrl, { headers: headers })
.pipe(
catchError(
(error:any) => Observable.throw(error.json().error || 'Server error')
)
);
}
checkCredentials() {
return Cookie.check('access_token');
}
logout() {
let token = Cookie.get('id_token');
Cookie.delete('access_token');
Cookie.delete('id_token');
let logoutURL = "http://localhost:8083/auth/smartharvester/protocol/openid-connect/logout?id_token_hint="
+ token
+ "&post_logout_redirect_uri=" + this.redirectUri;
window.location.href = logoutURL;
}
public isLoggedIn(){
return localStorage.getItem('ACCESS_TOKEN') !== null;
}
}
<h3>AAI EOSC-Pillar (to integrate)</h3>
<mat-card class="example-card">
<mat-card-header>
<mat-card-title>Login</mat-card-title>
</mat-card-header>
<mat-card-content>
<form class="example-form">
<table class="example-full-width" cellspacing="0">
<tr>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="Username" [(ngModel)]="username" name="username" required>
</mat-form-field>
</td>
</tr>
<tr>
<td><mat-form-field class="example-full-width">
<input matInput placeholder="Password" [(ngModel)]="password" type="password" name="password" required>
</mat-form-field></td>
</tr>
<tr>
<td>
<a routerLink="/user" routerLinkActive="active">Register</a>
</td>
</tr>
</table>
</form>
<mat-spinner [style.display]="showSpinner ? 'block' : 'none'"></mat-spinner>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button (click)="login()" color="primary">Login</button>
</mat-card-actions>
</mat-card>
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
username: string;
password: string;
ngOnInit() {
}
login() : void {
if(this.username == 'admin' && this.password == 'admin'){
this.router.navigate(["/"]);
}else {
alert("Invalid credentials");
}
}
}
<nb-card>
<nb-card-body class="example-items-col">
<form [formGroup]="searchForm">
<form [formGroup]="searchForm" (ngSubmit)="simpleSearch(searchForm.value)">
<label for="search">Search by title or description</label>
<input id="search" type="text" nbInput shape="round" placeholder="Search" formControlName="searchTerm">
<input id="search" type="text"
nbInput
shape="round"
placeholder="Search"
formControlName="inputSearchTerm"
required>
<span>
<button status="info" href="#" nbButton type="submit" (click)="simpleSearch(searchForm.value.searchTerm)" value="Search">
<button status="info" href="#"
nbButton type="submit"
value="Search"
[disabled]="!searchForm.valid">
<nb-icon icon="search-outline"></nb-icon> Search
</button>
</span>
<ng-template [ngTemplateOutlet]="results.length > 0 ? dataFound : dataNotFound"></ng-template>
</form>
</nb-card-body>
</nb-card>
<div *ngIf="results.length > 0; else notFound" class="w3-container">
<p>Found {{results.length}} entries for search term {{searchForm.value.searchTerm}}</p>
<table class="w3-table-all w3-card-4">
<thead>
<thead style="background-color: #3366ff">
<th style="text-align: center;">Uri (DOI)</th>
<th style="text-align: center;">Title</th>
<th style="text-align: center;">Description</th>
......@@ -31,6 +39,10 @@
</table>
</div>
<ng-template #notFound>
<div *ngIf="submited && results.length == 0">No results found for search {{searchForm.value.searchTerm}}</div>
<ng-template #dataFound>
<p>Found {{results.length}} entries for search term <b><i>{{searchedTerm}}</i></b></p>
</ng-template>
<ng-template #dataNotFound>
<p *ngIf="!firstTime">No results found for search <b><i>{{searchedTerm}}</i></b></p>
</ng-template>
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ParseXmlService } from '../services/parse-xml.service';
import { FormControl, FormGroup } from '@angular/forms';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
export interface formData{
[key: string]: string;
}
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
public results: string[][] = [];
public results: string[] = [];
firstTime = true;
searchForm;
searchedTerm;
searchForm = new FormGroup({
searchTerm: new FormControl()
});
submited: boolean;
constructor(
private http: HttpClient,
private parserService: ParseXmlService
) { }
constructor(private parserService: ParseXmlService, private formBuilder: FormBuilder) {
this.searchForm = this.formBuilder.group({
inputSearchTerm: '',
});
}
ngOnInit(): void {
}
......@@ -37,39 +38,32 @@ export class SearchComponent implements OnInit {
setTimeout(() => this.loading = false, 2000);
}
simpleSearch(term:string){
//effectuer une recherche plein text en SPARL sur la BDD Blazegraph
//curl -X POST -H 'Accept: application/rdf+xml' -i 'http://10.6.10.9:8888/blazegraph/sparql' --data 'query=SELECT * where {?s a <http://www.w3.org/ns/dcat#Dataset> }'
let query: string;
// query ='query=SELECT * where {?s a <http://www.w3.org/ns/dcat#Dataset> }'
this.results = []
this.submited = false;
query=
'query=PREFIX dcat: <http://www.w3.org/ns/dcat#>\n\
PREFIX dcterms: <http://purl.org/dc/terms/>\n\
SELECT ?title ?description ?uri \n\
where {\n\
?dataset a dcat:Dataset ;\n\
dcterms:title ?title ;\n\
dcterms:description ?description; \n\
dcat:keyword ?uri ; \n\
FILTER (contains( ?description, "'+ term +'") || contains( ?title, "'+ term +'"))\n\
.\n\
}'
this.parserService.getXmlResult(query).subscribe(
data=>{
if (data){
data.results.bindings.forEach(element => {
this.results.push(element);
});
}
})
this.searchForm.reset();
this.submited = true;
simpleSearch(formData){
this.firstTime = false;
//curl -X POST -H 'Accept: application/rdf+xml' -i 'http://10.6.10.9:8888/blazegraph/sparql' --data 'query=SELECT * where {?s a <http://www.w3.org/ns/dcat#Dataset> }'
let term = formData["inputSearchTerm"]
this.searchedTerm = term;
let query='query=PREFIX dcat: <http://www.w3.org/ns/dcat#>\n\
PREFIX dcterms: <http://purl.org/dc/terms/>\n\
SELECT ?title ?description ?uri \n\
where {\n\?dataset a dcat:Dataset ;\n\
dcterms:title ?title ;\n\
dcterms:description ?description; \n\
dcat:keyword ?uri ; \n\
FILTER (contains( ?description, "' +
term +'") || contains( ?title, "'+ term +'"))\n\.\n\
}'
this.parserService.getXmlResult(query).subscribe(
data=>{
if (data){
this.results = [];
data.results.bindings.forEach(element => {
this.results.push(element);
});
}
})
this.searchForm.reset();
}
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment