Commit 710a6681 authored by kasmiii's avatar kasmiii
Browse files

[FRONT-END]login

parent 9914b265
......@@ -6,6 +6,9 @@ import com.example.server.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
......@@ -38,4 +41,15 @@ public class ServerApplication {
public void emptyDataBase(){
repository.deleteAll();
}
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*").allowedHeaders("*").allowedOrigins("*").allowedMethods("*")
.allowCredentials(true);
}
};
}
}
package com.example.server.config.security;
import com.example.server.filter.JwtFilter;
import com.example.server.model.user.User;
import com.example.server.model.user.UserEntity;
import com.example.server.services.CustomUserDetailsService;
import com.example.server.utils.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
......@@ -15,15 +14,10 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
......@@ -38,8 +32,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder(){
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
......@@ -51,6 +46,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.cors().disable();
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/admin/**").hasRole(Const.ADMIN)
......@@ -59,9 +55,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/api/post/**").authenticated()
.antMatchers("/api/comment/**").authenticated()
.antMatchers("/api/users/login").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api").permitAll()
.and().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);;
http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
;
}
}
......@@ -6,8 +6,6 @@ import com.example.server.model.user.UserEntity;
import com.example.server.services.user.UserService;
import com.example.server.utils.JwtUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
......@@ -43,6 +41,7 @@ public class UserController {
} catch (Exception ex) {
throw new Exception("invalid username/password");
}
System.out.println("Token generated:: "+jwtUtil.generateToken(authRequest.getUserName()));
return jwtUtil.generateToken(authRequest.getUserName());
}
......@@ -62,14 +61,14 @@ public class UserController {
return new ResponseEntity<>("Deleted successfully !", HttpStatus.OK);
}
@GetMapping()
@GetMapping("/all")
public ResponseEntity<List<User>> getAll() {
return new ResponseEntity<>(userService.findAll(), HttpStatus.OK);
}
@DeleteMapping()
public ResponseEntity<?> deleteAll(){
public ResponseEntity<?> deleteAll() {
userService.deleteAll();
return ResponseEntity.ok("All users Deleted successfully");
return ResponseEntity.ok("All users Deleted successfully");
}
}
......@@ -12,6 +12,7 @@
<a routerLink="/signup">Créer un compte </a>
</div>
</form>
<h4>your token is:{{token}}</h4>
</div>
</div>
</div>
\ No newline at end of file
</div>
import { Component, OnInit } from '@angular/core';
import {Component, OnInit} from '@angular/core';
import {JwtClientService} from "../services/jwt-client.service";
import {Observable} from "rxjs";
@Component({
selector: 'app-login',
......@@ -7,9 +9,26 @@ import { Component, OnInit } from '@angular/core';
})
export class LoginComponent implements OnInit {
constructor() { }
token: string = "";
authRequest: any = {
"userName": "kasmi",
"password": "kasmi1997"
};
constructor(private jwtClientService: JwtClientService) {
}
ngOnInit(): void {
this.getAccessToken(this.authRequest);
}
public getAccessToken(authRequest: any) {
const response$ = this.jwtClientService.generateToken(authRequest);
// @ts-ignore
response$.subscribe(data => {
console.log("Token " + data);
this.token = data;
});
}
}
import { TestBed } from '@angular/core/testing';
import { JwtClientService } from './jwt-client.service';
describe('JwtClientService', () => {
let service: JwtClientService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(JwtClientService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class JwtClientService {
baseUrl: string = "http://localhost:8000/api/users";
constructor(private http: HttpClient) {
}
// @ts-ignore
public generateToken(request: any) {
this.http.post<string>(this.baseUrl + "/login", request, {responseType: 'text' as 'json'});
}
public welcome(token: string) {
const tokenStr = 'Bearer ' + token;
// get list of users when user is authenticated...
const headers = new HttpHeaders();
headers.set('Authorization', tokenStr);
return this.http.get(this.baseUrl + "/all", {headers, responseType: "text" as 'json'});
}
}
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