Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions pw/pw-jwt-oauth/client/src/app/home/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ <h1>{{message}}</h1>
<td>{{currentNew.author}}</td>
<td>{{currentNew.category}}</td>
<td>{{currentNew.content}}</td>
<td><button class="btn" (click)="addLike(currentNew)"><img src="assets/styles/ktheme/img/like.png" /> {{currentNew.likes}}</button></td>
<td><button class="btn" (click)="deleteNews(currentNew)"><img src="assets/styles/ktheme/img/delete.png"/></button></td>
<td><button *ngIf="principal.isAuthenticated()" class="btn" (click)="addLike(currentNew)"><img src="assets/styles/ktheme/img/like.png" /> {{currentNew.likes}}</button></td> <!-- Si jamais l'utilisateur est connecté, il peut liker les posts -->
<td><button *ngIf="principal.isAdmin()" class="btn" (click)="deleteNews(currentNew)"><img src="assets/styles/ktheme/img/delete.png"/></button></td> <!-- Si jamais l'utilisateur est un admin, il peut liker les posts -->
<!-- *ngIf permet de poser des conditions à la présence de la balise -->
</tr>
<tr class="gradeA">
<tr class="gradeA" *ngIf="principal.isUser()">
<td><input type="text" [(ngModel)]="nextNews.author" placeholder="author"/></td>
<td><input type="text" [(ngModel)]="nextNews.category" placeholder="category"/></td>
<td><input type="text" [(ngModel)]="nextNews.content" placeholder="content"/></td>
Expand Down
4 changes: 2 additions & 2 deletions pw/pw-jwt-oauth/client/src/app/home/home.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

import {Principal} from '../services/auth/principal.service'; //On fait le lien à principal.service pour avoir les fonctions isAdmin, IsUser...
import { NewsService } from '../services/newsService';
import { News } from '../beans/news';

Expand All @@ -15,7 +15,7 @@ export class Home implements OnInit {
newsOfTheDay: News = {};
nextNews: News = {};

constructor(private newsService: NewsService) {}
constructor(private newsService: NewsService, public principal: Principal) {} //On veut pouvoir savoir les permissions de l'utilisateur

ngOnInit() {
this.updateNews();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,20 @@ export class JwtInterceptor implements HttpInterceptor {
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {

let token = this.ng2localStorage.retrieve('authenticationToken') || this.ng2sessionStorage.retrieve('authenticationToken'); // On récupère le token sur le local storage du client ou bien sur la session deja existante
// retrieve jwt token from client storage (local or session) with the key 'authenticationToken'
// let token = this.ng2localStorage.retrieve(....) || this.ng2sessionStorage.retrieve(....);
// verify token is present
// if (...){
// if (...){
// set authorization header in the request with the token : 'Authorization: Bearer __token__'
if (token){ /*On créer cette entête de requete si le token existe ( c'est à dire si c'est un utilisateur qui est sur la page et s'est login au site)*/
req = req.clone({
setHeaders: { /*Création du pattern de l'entête de la requete*/
Authorization: 'Bearer '+token /*Création de la requete avec de "type" bearer + token de l'utilisateur*/
}
});
}
// req = req.clone({
// setHeaders: {
// Authorization: ....
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,16 @@ export class AuthServerProvider {
// store the jwt in the credentials ( use storeAuthenticationToken )
// this.storeAuthenticationToken(.....);
// return the jwt
let bearerToken = resp.headers.get('Authorization'); // On récupère notre Bearer token de l'entête de requete crée dans auth-jwt.interceptor.ts
if (bearerToken && bearerToken.slice(0, 7) === 'Bearer ') { /*Si le bearerToken existe et qu'on a bien le format bearer + token alors on peut continuer*/
let jwt = bearerToken.slice(7, bearerToken.length); /*on récupère ainsi le token jwt de l'utilisateur via slice() */
this.storeAuthenticationToken(jwt, rememberMe); /*On garde le token en place avec un système de rememberMe*/
return jwt; /*On retourne le token jwt de l'utilisateur pour prouver son authenticité*/
}
return resp;
}


loginWithToken(jwt: string, rememberMe: boolean) {
if (jwt) {
this.storeAuthenticationToken(jwt, rememberMe);
Expand Down
23 changes: 23 additions & 0 deletions pw/pw-jwt-oauth/client/src/app/services/auth/principal.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,29 @@ export class Principal {
return this.authenticated;
}

//Si l'utilsateur est connecté et qu'il fait parti des utilisateurs et qu'il n'est PAS admin, return true sinon return false
isUser(): boolean {

if (this._identity && ( this._identity.authorities.indexOf("ROLE_USER")!==-1 || this._identity.authorities.indexOf("ROLE_ADMIN")!== -1 ))
{
return true;
}
else
{
return false; //Sinon return false
}
}

//Si l'utilisateur est connecté et qu'il appartient aux admins, return true
isAdmin(): boolean {

if (this._identity && this._identity.authorities.indexOf("ROLE_ADMIN") !== -1) {
return true;
} else {
return false; //Sinon return false
}
}

isIdentityResolved(): boolean {
return this._identity !== undefined;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,19 @@ protected void configure(HttpSecurity http) throws Exception {
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/news/like/**").authenticated() //Permet de dire que pour acceder à /api/news/like/** il faut d'abord s'authentifier au site, donc une personne sans compte ou pas connectée ne pourra pas liker un post.
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/account/reset_password/init").permitAll()
.antMatchers("/api/account/reset_password/finish").permitAll()
.antMatchers("/api/profile-info").permitAll()
.antMatchers("/api/**").permitAll() // authenticated() <== for tests!! //TODO remove it
//.antMatchers("/api/**").permitAll() // authenticated() <== for tests!! //TODO remove it
.antMatchers("/management/health").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/v2/api-docs/**").hasAuthority(AuthoritiesConstants.ADMIN)
// .and()
// .apply(securityConfigurerAdapter())
.and()
.apply(securityConfigurerAdapter())
;
// TODO uncomment this line to activate JWT filter

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package com.worldline.bookstore.web.rest;

import com.worldline.bookstore.domain.News;

import com.worldline.bookstore.security.AuthoritiesConstants;
import com.worldline.bookstore.repository.NewsRepository;
import com.worldline.bookstore.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.security.access.annotation.Secured; /* On importe ce package afin de pouvoir sécuriser des méthodes ou des classes */
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
Expand Down Expand Up @@ -42,7 +42,7 @@ public NewsResource(NewsRepository newsRepository) {
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/news")

@Secured({ AuthoritiesConstants.USER}) /*On protège la méthode createNews avec @Secured(), tout les personnes ayant le rôle USER peuvent créer une news */
public ResponseEntity<News> createNews(@Valid @RequestBody News news) throws URISyntaxException {
log.debug("REST request to save News : {}", news);
if (news.getId() != null) {
Expand All @@ -68,7 +68,7 @@ public ResponseEntity<News> createNews(@Valid @RequestBody News news) throws URI
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/news")

@Secured({ AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN })/*On protège la méthode update avec @Secured(), tout les personnes ayant le rôle USER et ADMIN peuvent l'utiliser*/
public ResponseEntity<News> updateNews(@Valid @RequestBody News news) throws URISyntaxException {
log.debug("REST request to update News : {}", news);
if (news.getId() == null) {
Expand All @@ -86,7 +86,7 @@ public ResponseEntity<News> updateNews(@Valid @RequestBody News news) throws URI
* @return the ResponseEntity with status 200 (OK) and the list of news in body
*/
@GetMapping("/news")

/*Tout le monde peut voir les news */
public List<News> getAllNews() {
log.debug("REST request to get all News");
List<News> news = newsRepository.findAll();
Expand All @@ -101,7 +101,6 @@ public List<News> getAllNews() {
* with status 404 (Not Found)
*/
@GetMapping("/news/{id}")

public ResponseEntity<News> getNews(@PathVariable Long id) {
log.debug("REST request to get News : {}", id);
var optNews = newsRepository.findById(id);
Expand All @@ -115,7 +114,7 @@ public ResponseEntity<News> getNews(@PathVariable Long id) {
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/news/{id}")

@Secured({AuthoritiesConstants.ADMIN}) /*Seuls les admins peuvent supprimer une news */
public ResponseEntity<Void> deleteNews(@PathVariable Long id) {
log.debug("REST request to delete News : {}", id);
newsRepository.deleteById(id);
Expand All @@ -131,7 +130,6 @@ public ResponseEntity<Void> deleteNews(@PathVariable Long id) {
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/news/like/{id}")

public ResponseEntity<News> addLikeforNews(@PathVariable Long id) throws URISyntaxException {
log.debug("REST request to add like to News : {}", id);
var optNews = newsRepository.findById(id);
Expand Down