Skip to content

Commit

Permalink
chore():multiple refactos
Browse files Browse the repository at this point in the history
  • Loading branch information
Thibaut-Mouton committed Apr 16, 2024
1 parent 80b92a8 commit 4a22937
Show file tree
Hide file tree
Showing 29 changed files with 410 additions and 361 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/npm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ jobs:
with:
node-version: 20.x
- name: build
run: npm run build --prefix frontend-web
run: npm run build --prefix ./frontend-web
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
![maven build status](https://github.com/Thibaut-Mouton/react-spring-messenger-project/workflows/maven/badge.svg?branch=master)
![npm build status](https://github.com/Thibaut-Mouton/react-spring-messenger-project/workflows/npm/badge.svg?branch=master)
![maven build status](https://github.com/Thibaut-Mouton/react-spring-messenger-project/workflows/build-back/badge.svg?branch=master)
![npm build status](https://github.com/Thibaut-Mouton/react-spring-messenger-project/workflows/build-front/badge.svg?branch=master)

<p align="center">
<img src="/assets/react.png" alt="React logo"/>
Expand Down

This file was deleted.

17 changes: 5 additions & 12 deletions backend/src/main/java/com/mercure/config/JwtWebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public class JwtWebConfig extends OncePerRequestFilter {
private JwtUtil jwtUtil;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException, ServletException {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String jwtToken = null;
String username;
Cookie cookie = WebUtils.getCookie(request, StaticVariable.SECURE_COOKIE);
Expand All @@ -38,17 +38,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}
if (jwtToken != null) {
username = jwtUtil.getUserNameFromJwtToken(jwtToken);
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
} catch (Exception ex) {
//this is very important, since it guarantees the user is not authenticated at all
filterChain.doFilter(request, response);
SecurityContextHolder.clearContext();
return;
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
filterChain.doFilter(request, response);
Expand Down
65 changes: 34 additions & 31 deletions backend/src/main/java/com/mercure/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,56 @@
package com.mercure.config;

import com.mercure.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
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.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Autowired
public JwtWebConfig jwtWebConfig;

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
// .csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.ignoringRequestMatchers("/api/csrf"))
.cors(Customizer.withDefaults())
.authorizeHttpRequests((request) -> request
.requestMatchers("/api").permitAll()
.requestMatchers("/api/csrf").permitAll()
.requestMatchers("/api/auth").permitAll()
.requestMatchers("/api/**").authenticated())
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtWebConfig, UsernamePasswordAuthenticationFilter.class);
return http.build();
}

@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(new CustomUserDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}

// @Bean
// public CorsConfigurationSource corsConfigurationSource() {
// CorsConfiguration configuration = new CorsConfiguration();
Expand All @@ -30,34 +62,5 @@ public PasswordEncoder passwordEncoder() {
// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// source.registerCorsConfiguration("/**", configuration);
// return source;
// }

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.authorizeHttpRequests((auth) -> auth.anyRequest().permitAll());
return http.build();
}

// protected void configure(HttpSecurity http) throws Exception {
// http.cors().and()
// .csrf()
// .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
// .and()
// .authorizeRequests()
// .antMatchers("/api/auth").permitAll()
// .antMatchers("/api/user/register").permitAll()
// .antMatchers("/ws").permitAll()
// .antMatchers("/static/**").permitAll()
// .antMatchers("/images/**").permitAll()
// .antMatchers("/").permitAll()
// .anyRequest().authenticated()
// .and()
// .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
// .and()
// .sessionManagement()
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// http.addFilterBefore(jwtWebConfig, UsernamePasswordAuthenticationFilter.class);
// }
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.*;

@RestController
@CrossOrigin
public class ApiController {

private final Logger log = LoggerFactory.getLogger(ApiController.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.mercure.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -8,8 +10,12 @@
@RequestMapping(value = "/")
public class PingController {

private final Logger log = LoggerFactory.getLogger(PingController.class);


@GetMapping
public String testRoute() {
log.debug("Ping base route");
return "Server status OK";
}
}
1 change: 1 addition & 0 deletions backend/src/main/java/com/mercure/utils/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public class JwtUtil implements Serializable {

public static final long JWT_TOKEN_VALIDITY = 1000 * 3600 * 365;

// TODO generate key
public static final String JWT_TOKEN = "d95d7dc9-0d56-4ef3-8d03-263c23b5bce5";

// retrieve username from jwt token
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import {Button, Container, CssBaseline, Grid, Typography} from "@mui/material"
import React, {useContext, useEffect, useState} from "react"
import {useThemeContext} from "../../context/theme-context"
import {CustomTextField} from "../partials/custom-material-textfield"
import {HttpService} from "../../service/http-service"
import {HttpGroupService} from "../../service/http-group-service"
import {AlertAction, AlertContext} from "../../context/AlertContext"

export const CreateGroupComponent = () => {
const [groupName, setGroupName] = useState("")
const {theme} = useThemeContext()
const httpService = new HttpService()
const httpService = new HttpGroupService()
const {dispatch} = useContext(AlertContext)!

useEffect(() => {
Expand Down Expand Up @@ -65,7 +65,7 @@ export const CreateGroupComponent = () => {
return (
<div className={theme}
style={{
height: "calc(100% - 46px)",
height: "calc(100% - 64px)",
textAlign: "center",
paddingTop: "40px"
}}>
Expand Down
9 changes: 6 additions & 3 deletions frontend-web/src/components/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import {Box, Card, CardContent, Grid, Typography} from "@mui/material"
import React, {useContext, useEffect} from "react"
import {generateColorMode} from "./utils/enable-dark-mode"
import {useThemeContext} from "../context/theme-context"
import {LoginComponent} from "./login/login-component"
import {FooterComponent} from "./partials/footer-component"
import {AuthUserContext} from "../context/AuthContext"
import {LoginComponent} from "./login/LoginComponent"

export const HomeComponent = (): React.JSX.Element => {
const {theme} = useThemeContext()
Expand All @@ -18,7 +18,7 @@ export const HomeComponent = (): React.JSX.Element => {
<div className={generateColorMode(theme)}
style={{
width: "100%",
height: "calc(100% - 46px)",
height: "calc(100% - 64px)",
textAlign: "center"
}}>
<Box p={2}>
Expand All @@ -35,7 +35,10 @@ export const HomeComponent = (): React.JSX.Element => {
<Typography variant="h5" gutterBottom>
Simple, fast and secure
</Typography>
<div>FastLiteMessage allow to communicate with other people, create groups, make serverless video calls in an easy way. Log into your account or register to start using FastLiteMessage.</div>
<div>FastLiteMessage allow to communicate with other people, create groups, make
serverless video calls in an easy way. Log into your account or register to start
using FastLiteMessage.
</div>
<FooterComponent/>
</CardContent>
</Card>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import {Link, redirect} from "react-router-dom"
import {useThemeContext} from "../../context/theme-context"
import {generateIconColorMode, generateLinkColorMode} from "../utils/enable-dark-mode"
import {CustomTextField} from "../partials/custom-material-textfield"
import {HttpService} from "../../service/http-service"
import {HttpGroupService} from "../../service/http-group-service"
import {LoaderContext} from "../../context/loader-context"
import {AlertAction, AlertContext} from "../../context/AlertContext"

export const LoginComponent: React.FunctionComponent = () => {
export function LoginComponent(): React.JSX.Element {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")

const {dispatch} = useContext(AlertContext)!
const {setLoading} = useContext(LoaderContext)
const {theme} = useThemeContext()
const httpService = new HttpService()
const httpService = new HttpGroupService()

useEffect(() => {
document.title = "Login | FLM"
Expand Down Expand Up @@ -73,7 +73,7 @@ export const LoginComponent: React.FunctionComponent = () => {
return (
<div className={theme}
style={{
height: "calc(100% - 46px)",
height: "calc(100% - 64px)",
width: "100%"
}}>
<div className={"main-register-form"}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import React, {useContext, useState} from "react"
import {getPayloadSize} from "../../utils/string-size-calculator"
import {TransportModel} from "../../interface-contract/transport-model"
import {TransportActionEnum} from "../../utils/transport-action-enum"
import {HttpService} from "../../service/http-service"
import {HttpGroupService} from "../../service/http-group-service"
import HighlightOffIcon from "@mui/icons-material/HighlightOff"
import {WebSocketContext} from "../../context/WebsocketContext"
import {AuthUserContext} from "../../context/AuthContext"
Expand Down Expand Up @@ -74,7 +74,7 @@ export function CreateMessageComponent({groupUrl}: CreateMessageComponentProps):
setMessage("")
}
if (file !== null) {
const httpService = new HttpService()
const httpService = new HttpGroupService()
const formData = new FormData()
formData.append("file", file)
formData.append("userId", String(user?.id || 0))
Expand Down
Loading

0 comments on commit 4a22937

Please sign in to comment.