Commit 32523a86 authored by kasmiii's avatar kasmiii
Browse files

Merge remote-tracking branch 'origin/main' into main

# Conflicts:
#	server/src/main/java/com/example/server/controller/UserController.java
#	webapp/src/app/app.module.ts
#	webapp/src/app/login/login.component.ts
parents a20be97c 094fd3d6
......@@ -20,7 +20,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/gkz-stomp-endpoint")
.setAllowedOrigins("http://127.0.0.1:4200")
.setAllowedOrigins("http://127.0.0.1:4200", "http://localhost:4200")
.withSockJS();
}
}
......@@ -2,7 +2,10 @@ package com.example.server.controller;
import com.example.server.config.websocket.Message;
import com.example.server.model.user.User;
import com.example.server.model.user.UserEntity;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
......@@ -12,7 +15,9 @@ public class SocketController {
@MessageMapping("/test")
@SendTo("/api/hi")
public Message greeting(User user) {
public Message greeting(UserEntity user) {
Logger logger = LoggerFactory.getLogger(SocketController.class);
logger.info("Message reçu ! " + user.getLastName());
return new Message("Hi, " + user.getLastName() + "!");
}
}
......@@ -12,8 +12,6 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
......@@ -29,7 +27,7 @@ public class UserController {
@Autowired
private AuthenticationManager authenticationManager;
@PostMapping("/add")
@PostMapping()
public ResponseEntity<User> add(@RequestBody UserEntity user) throws JsonProcessingException {
return new ResponseEntity<>(userService.add(user), HttpStatus.CREATED);
}
......@@ -43,7 +41,7 @@ public class UserController {
} catch (Exception ex) {
throw new Exception("invalid username/password");
}
// System.out.println("Token generated:: " + jwtUtil.generateToken(authRequest.getUserName()));
System.out.println("Token generated:: " + jwtUtil.generateToken(authRequest.getUserName()));
return jwtUtil.generateToken(authRequest.getUserName());
}
......@@ -63,11 +61,8 @@ public class UserController {
return new ResponseEntity<>("Deleted successfully !", HttpStatus.OK);
}
@GetMapping("/all")
public ResponseEntity<List<User>> getAll() {//Authentication authentication
// UserDetails userDetails=(UserDetails) authentication.getDetails();
// System.out.println("Authenticated user is:: "+userDetails.getUsername());
// System.out.println(authentication.getDetails());
@GetMapping()
public ResponseEntity<List<User>> getAll() {
return new ResponseEntity<>(userService.findAll(), HttpStatus.OK);
}
......
......@@ -20,6 +20,7 @@
"@angular/router": "~12.2.0",
"@stomp/stompjs": "^6.1.2",
"net": "^1.0.2",
"ngx-cookie-service": "^13.0.0",
"ngx-toastr": "^14.1.4",
"rxjs": "~6.6.0",
"sockjs-client": "^1.5.2",
......
......@@ -16,10 +16,11 @@ import { SignupComponent } from './signup/signup.component';
import { QuestionComponent } from './question/question.component';
import { PostDetailsComponent } from './post-details/post-details.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { ToastrModule } from 'ngx-toastr';
import {JwtClientService} from "./services/jwt-client.service";
import {AuthInterceptor} from "./services/auth-interceptor.service";
import { CookieService } from 'ngx-cookie-service';
import { SignoutComponent } from './signout/signout.component';
@NgModule({
declarations: [
......@@ -34,7 +35,8 @@ import {AuthInterceptor} from "./services/auth-interceptor.service";
LoginComponent,
SignupComponent,
QuestionComponent,
PostDetailsComponent
PostDetailsComponent,
SignoutComponent
],
imports: [
HttpClientModule,
......@@ -45,9 +47,7 @@ import {AuthInterceptor} from "./services/auth-interceptor.service";
FormsModule,
ReactiveFormsModule
],
providers: [JwtClientService,
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
],
providers: [JwtClientService, CookieService],
bootstrap: [AppComponent]
})
export class AppModule { }
......@@ -12,8 +12,9 @@
<ul class="nav navbar-nav navbar-right">
<li><a routerLink="/home" routerLinkActive="active">Home</a></li>
<li><a routerLink="/test" routerLinkActive="active">Test socket</a></li>
<li><a routerLink="/login" routerLinkActive="active">Se connecter</a></li>
<li><a routerLink="/signup" routerLinkActive="active">Créer un compte</a></li>
<li *ngIf="!isAuth"><a routerLink="/login" routerLinkActive="active">Se connecter</a></li>
<li *ngIf="!isAuth"><a routerLink="/signup" routerLinkActive="active">Créer un compte</a></li>
<li (click)="logout()" *ngIf="isAuth"><a routerLinkActive="active">Se déconnecter</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
......
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { JwtClientService } from '../services/jwt-client.service';
@Component({
selector: 'app-header',
......@@ -6,10 +8,16 @@ import { Component, OnInit } from '@angular/core';
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor() { }
isAuth:boolean = false;
constructor(private jwtService: JwtClientService, private router: Router) { }
ngOnInit(): void {
this.jwtService.refresh();
this.isAuth = JwtClientService.isAuth;
}
logout() {
this.jwtService.disconnect()
window.location.reload()
}
}
......@@ -2,9 +2,8 @@ import {Component, OnInit} from '@angular/core';
import {JwtClientService} from "../services/jwt-client.service";
import {FormBuilder, Validators} from "@angular/forms";
import {HttpClient} from "@angular/common/http";
import { ToastrService } from 'ngx-toastr';
import {Router} from "@angular/router";
import {Global} from "../global-classes/global";
import {catchError} from "rxjs/operators";
@Component({
selector: 'app-login',
......@@ -12,14 +11,14 @@ import {catchError} from "rxjs/operators";
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: any;
// token: string = "";
token: string = "";
baseUrl: string = "http://127.0.0.1:8000/api/users";
constructor(private jwtClientService: JwtClientService,
private fb: FormBuilder,
private http: HttpClient,
private router: Router) {
private router: Router,
private toastr: ToastrService) {
}
ngOnInit(): void {
......@@ -30,6 +29,11 @@ export class LoginComponent implements OnInit {
}
public login() {
console.log("state => ", JwtClientService.isAuth)
if (JwtClientService.isAuth) {
this.router.navigate(["/home"])
return;
}
const authRequest = {
userName: this.loginForm.value["username"],
password: this.loginForm.value["password"]
......@@ -39,11 +43,14 @@ export class LoginComponent implements OnInit {
.subscribe(
data => {
console.warn("Token " + data);
Global.TOKEN = data;
this.router.navigate(["/home"]);
this.router.navigate(["/"]);
this.jwtClientService.connect(data.toString())
this.toastr.success("Bon retour parmis nous " + authRequest.userName + " !")
},
// catchError()
error => console.log("There is an error occurred: " + error)
error => {
console.log("There is an error occurred: " + error)
this.toastr.error("Identifiant ou mot de passe invalide !")
}
);
}
......
......@@ -30,7 +30,7 @@ export class MessagetestComponent implements OnInit {
}
connect() {
const socket = new SockJS('http://localhost:8000/gkz-stomp-endpoint');
const socket = new SockJS('http://127.0.0.1:8000/gkz-stomp-endpoint');
// @ts-ignore
this.stompClient = Stomp.over(socket);
......@@ -42,6 +42,7 @@ export class MessagetestComponent implements OnInit {
// @ts-ignore
_this.stompClient.subscribe('/api/hi', function (response){
console.log("Server response", response)
_this.showGreeting(JSON.parse(response.body));
});
});
......
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs";
import { CookieService } from 'ngx-cookie-service';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class JwtClientService {
public static isAuth: boolean = false;
public static currentToken : string = "";
baseUrl: string = "http://127.0.0.1:8000/api/users";
constructor(private http: HttpClient) {
constructor(private http: HttpClient,
private cookie: CookieService) {
}
// @ts-ignore
......@@ -17,6 +22,17 @@ export class JwtClientService {
this.http.post<Observable<string>>(this.baseUrl + "/login", request);
}
public refresh() {
const expiration = parseInt(this.cookie.get('expiration'));
if(expiration > Date.now()) {
JwtClientService.isAuth = true;
JwtClientService.currentToken = this.cookie.get('currentToken');
this.cookie.set('expiration', (Date.now() + 1000*60*10)+'');
} else {
this.disconnect();
}
JwtClientService.isAuth = this.cookie.get('isAuth') == 'true'
}
public welcome(token: string) {
const tokenStr = 'Bearer ' + token;
// get list of users when user is authenticated...
......@@ -24,4 +40,21 @@ export class JwtClientService {
headers.set('Authorization', tokenStr);
return this.http.get(this.baseUrl + "/all", {headers, responseType: "text" as 'json'});
}
public connect(userToken: string) {
this.cookie.set('isAuth', 'true');
this.cookie.set('currentToken', userToken);
this.cookie.set('expiration', (Date.now() + 1000*60*10)+'');
JwtClientService.isAuth = true;
JwtClientService.currentToken = userToken;
}
public disconnect() {
this.cookie.delete('isAuth')
this.cookie.delete('currentToken')
this.cookie.delete('expiration')
JwtClientService.isAuth = false;
JwtClientService.currentToken = "";
}
}
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SignoutComponent } from './signout.component';
describe('SignoutComponent', () => {
let component: SignoutComponent;
let fixture: ComponentFixture<SignoutComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ SignoutComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SignoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { JwtClientService } from '../services/jwt-client.service';
@Component({
selector: 'app-signout',
templateUrl: './signout.component.html',
styleUrls: ['./signout.component.css']
})
export class SignoutComponent implements OnInit {
constructor(private jwtService: JwtClientService, private router: Router) { }
ngOnInit(): void {
this.jwtService.disconnect();
this.router.onSameUrlNavigation = 'reload';
this.router.navigateByUrl('/home');
// window.location.replace(window.location.host + "/home")
}
}
Markdown is supported
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