Changeset 6eba109


Ignore:
Timestamp:
08/17/22 16:21:10 (2 years ago)
Author:
unknown <mlviktor23@…>
Branches:
main
Children:
702ca77
Parents:
800779d
Message:

implemented authentication in react

Files:
4 added
12 edited

Legend:

Unmodified
Added
Removed
  • reactapp/src/App.js

    r800779d r6eba109  
    22import SearchResults from "./Pages/SearchResults";
    33import Login from "./Pages/Login";
    4 import { BrowserRouter, Routes, Route } from "react-router-dom";
     4import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
    55import Home from "./Pages/Home";
     6import User from "./Pages/User";
     7import { useEffect, useState, useMemo } from "react";
     8import AuthApi from "./api/AuthApi";
     9import Cookies from "js-cookie";
    610
    711export default function App() {
     12  const [auth, setAuth] = useState(false);
     13  const variableAuth = useMemo(() => ({ auth, setAuth }), [auth]);
     14
     15  const readCookie = () => {
     16    const session = Cookies.get("JSESSIONID");
     17    if (session) {
     18      setAuth(true); // go stava true ako postoi takvo cookie (zasto auth=false na sekoe renderiranje)
     19    }
     20  };
     21
     22  useEffect(() => {
     23    readCookie();
     24  }, []);
     25
     26  const ProtectedRoute = ({ auth, children }) => {
     27    if (!auth) {
     28      return <Navigate to="/login" replace />;
     29    }
     30    return children;
     31  };
     32
    833  return (
    9     <BrowserRouter>
    10       <Routes>
    11         <Route path="/" element={<Home />}>
    12           <Route path="login" element={<Login />}></Route>
    13           <Route path="professor">
    14             <Route path=":professorId" element={<Professor />} />
     34    <AuthApi.Provider value={variableAuth}>
     35      <BrowserRouter>
     36        <Routes>
     37          <Route path="/" element={<Home />}>
     38            <Route path="login" element={<Login />}></Route>
     39            <Route path="professor">
     40              <Route path=":professorId" element={<Professor />} />
     41            </Route>
     42            <Route path="search" element={<SearchResults />}></Route>
     43            <Route
     44              path="user"
     45              element={
     46                <ProtectedRoute auth={auth}>
     47                  <User />
     48                </ProtectedRoute>
     49              }
     50            ></Route>
    1551          </Route>
    16           <Route path="search" element={<SearchResults />}></Route>
    17         </Route>
    18       </Routes>
    19     </BrowserRouter>
     52        </Routes>
     53      </BrowserRouter>
     54    </AuthApi.Provider>
    2055  );
    2156}
  • reactapp/src/Components/Search.js

    r800779d r6eba109  
    1515
    1616  useEffect(() => {
    17     const url = `http://192.168.0.17:8080/public/professors/nameContains/${transliterate(
     17    const url = `http://192.168.0.18:8080/public/professors/nameContains/${transliterate(
    1818      query
    1919    )}`;
  • reactapp/src/Pages/Home.js

    r800779d r6eba109  
    2020      </a>{" "}
    2121      <Search />
     22      <div style={{ marginTop: "140px" }}></div>
    2223      <Outlet />
    2324    </MainWrapper>
  • reactapp/src/Pages/Login.js

    r800779d r6eba109  
    1 import React, { useRef, useState, useEffect } from "react";
     1import React, { useRef, useState, useEffect, useContext } from "react";
     2import { Navigate } from "react-router-dom";
     3import AuthApi from "../api/AuthApi";
    24import axios from "../api/axios";
     5import Cookies from "js-cookie";
    36const LOGIN_URL = "/login";
    47
    58const Login = () => {
     9  const { auth, setAuth } = useContext(AuthApi);
    610  const userRef = useRef();
    711  const errRef = useRef();
     
    1014  const [password, setPassword] = useState("");
    1115  const [errMsg, setErrMsg] = useState("");
    12   const [success, setSuccess] = useState(false);
    1316
    1417  useEffect(() => {
    1518    userRef.current.focus();
    1619  }, []);
    17 
    18   useEffect(() => {
    19     setErrMsg("");
    20   }, [username, password]);
    2120
    2221  const handleSubmit = async (e) => {
     
    3332      }
    3433    );
     34    if (!response.request.responseURL.includes("error")) {
     35      // ako NE redirektira na /login?error
     36      Cookies.set("JSESSIONID", response.data.sessionId);
     37      setAuth(true);
     38      setErrMsg("");
     39    } else {
     40      setErrMsg("Погрешно корисиничко име и/или лозинка");
     41    }
     42
    3543    setUsername("");
    3644    setPassword("");
    37     setSuccess(true);
    3845  };
    3946
    40   return success ? (
     47  const handleLogout = () => {
     48    setAuth(false);
     49    Cookies.remove("JSESSIONID");
     50  };
     51
     52  return auth ? (
     53    /*
    4154    <div style={{ marginTop: "140px" }}>
    4255      <h1>Успешна најава!</h1>
    4356      <br />
    4457      <p>
    45         <a href="/">Оди на почетната страница</a>
     58        <a href="/user">Оди на protected</a>
    4659      </p>
     60      <button onClick={handleLogout}>Одјави се</button>
    4761    </div>
     62    */
     63    <Navigate to="/user" />
    4864  ) : (
    4965    <div style={{ marginTop: "140px" }}>
  • reactapp/src/Pages/Professor.js

    r800779d r6eba109  
    1818
    1919  useEffect(() => {
    20     const url = `http://192.168.0.17:8080/public/professor/${params.professorId}`;
     20    const url = `http://192.168.0.18:8080/public/professor/${params.professorId}`;
    2121
    2222    const fetchData = async () => {
  • reactapp/src/api/axios.js

    r800779d r6eba109  
    22
    33export default axios.create({
    4   baseURL: "http://192.168.0.17:8080",
     4  baseURL: "http://192.168.0.18:8080",
    55});
  • springapp/src/main/java/mk/profesori/springapp/Controller/PublicController.java

    r800779d r6eba109  
    11package mk.profesori.springapp.Controller;
    22
     3import java.util.Collections;
    34import java.util.List;
     5import java.util.Map;
    46import java.util.Optional;
    57
     
    2123@RestController
    2224@RequestMapping("/public")
    23 @CrossOrigin(origins = { "http://192.168.0.17:3000", "http://192.168.0.24:3000" })
     25@CrossOrigin(origins = { "http://192.168.0.18:3000", "http://192.168.0.24:3000" })
    2426public class PublicController {
    2527
     
    9597        return mainService.getCityById(cityId); // vrakja grad spored id
    9698    }
     99
     100    @RequestMapping(value = "/loginSuccessRegular", method = RequestMethod.GET)
     101    public Map<String, String> loginSuccessRegular(@RequestParam String sessionId) {
     102        return Collections.singletonMap("sessionId", sessionId);
     103    }
     104
     105    @RequestMapping(value = "/loginSuccessModerator", method = RequestMethod.GET)
     106    public Map<String, String> loginSuccessModerator(@RequestParam String sessionId) {
     107        return Collections.singletonMap("sessionId", sessionId);
     108    }
    97109}
  • springapp/src/main/java/mk/profesori/springapp/Controller/SecureController.java

    r800779d r6eba109  
    11package mk.profesori.springapp.Controller;
     2
     3import java.util.Collections;
     4import java.util.Map;
    25
    36import org.springframework.beans.factory.annotation.Autowired;
     
    58import org.springframework.security.core.annotation.CurrentSecurityContext;
    69import org.springframework.security.core.context.SecurityContext;
     10import org.springframework.security.core.userdetails.UserDetails;
    711import org.springframework.web.bind.annotation.CrossOrigin;
    812import org.springframework.web.bind.annotation.PathVariable;
     
    1014import org.springframework.web.bind.annotation.RequestMapping;
    1115import org.springframework.web.bind.annotation.RequestMethod;
     16import org.springframework.web.bind.annotation.RequestParam;
    1217import org.springframework.web.bind.annotation.RestController;
    1318
     
    1520
    1621import mk.profesori.springapp.Model.CustomUserDetails;
     22import mk.profesori.springapp.Service.CustomUserDetailsService;
    1723import mk.profesori.springapp.Service.MainService;
    1824
    1925@RestController
    2026@RequestMapping("/secure")
    21 @CrossOrigin(origins = { "http://192.168.0.17:3000", "http://192.168.0.24:3000" })
     27@CrossOrigin(origins = { "http://192.168.0.18:3000", "http://192.168.0.24:3000" })
    2228public class SecureController {
    2329
    2430    @Autowired
    2531    private MainService mainService;
     32    @Autowired
     33    CustomUserDetailsService customUserDetailsService;
    2634
    2735    @RequestMapping(value = "/professor/{professorId}/addOpinion", method = RequestMethod.POST)
     
    5260    }
    5361
     62    @RequestMapping(value = "/user", method = RequestMethod.GET)
     63    public UserDetails getUserDetails(@CurrentSecurityContext SecurityContext context) {
     64
     65        Authentication authentication = context.getAuthentication();
     66        if (authentication != null && authentication.getPrincipal() instanceof CustomUserDetails) {
     67            CustomUserDetails currentUser = (CustomUserDetails) authentication.getPrincipal();
     68            return customUserDetailsService.loadUserByUsername(currentUser.getEmail());
     69        }
     70
     71        return null;
     72    }
     73
    5474}
  • springapp/src/main/java/mk/profesori/springapp/Model/CustomUserDetails.java

    r800779d r6eba109  
    5353    private Set<ConfirmationToken> confirmationTokens = new HashSet<>();
    5454    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
    55     private List<Post> authoredPosts = new ArrayList<>();
     55    private Set<Post> authoredPosts = new HashSet<>();
    5656
    5757    public CustomUserDetails(String fullName, String username, String email, String password, UserRole userRole) {
     
    9999    }
    100100
    101     List<Post> getAuthoredPosts() {
     101    public Set<Post> getAuthoredPosts() {
    102102        return this.authoredPosts;
    103103    }
  • springapp/src/main/java/mk/profesori/springapp/Security/SecurityConfiguration.java

    r800779d r6eba109  
    1010import org.springframework.security.crypto.password.PasswordEncoder;
    1111import org.springframework.security.web.SecurityFilterChain;
     12import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
    1213import org.springframework.web.servlet.config.annotation.CorsRegistry;
    1314import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
     
    3637            @Override
    3738            public void addCorsMappings(CorsRegistry registry) {
    38                 registry.addMapping("/**").allowedOrigins("http://192.168.0.17:3000", "http://192.168.0.24:3000");
     39                registry.addMapping("/**").allowedOrigins("http://192.168.0.18:3000", "http://192.168.0.24:3000")
     40                        .allowCredentials(true);
    3941            }
    4042        };
     43    }
     44
     45    @Bean
     46    public AuthenticationSuccessHandler customAuthenticationSuccessHandler() {
     47        return new CustomAuthenticationSuccessHandler();
    4148    }
    4249
     
    5461                .antMatchers("/registration/**").permitAll()
    5562                .and()
    56                 .formLogin();
     63                .formLogin().successHandler(customAuthenticationSuccessHandler());
    5764
    5865        return http.build();
  • springapp/src/main/java/mk/profesori/springapp/Service/RegistrationService.java

    r800779d r6eba109  
    2525    private final EmailSender emailSender;
    2626    private final UserRepository userRepository;
    27    
     27
    2828    public String register(RegistrationRequest request) {
    2929
    3030        boolean isValidEmail = emailValidator.test(request.getEmail());
    31         if(!isValidEmail) throw new IllegalStateException("Invalid email");
     31        if (!isValidEmail)
     32            throw new IllegalStateException("Invalid email");
    3233
    3334        boolean isValidPassword = passwordValidator.test(request.getPassword());
    34         if(!isValidPassword) throw new IllegalStateException("Invalid password");
     35        if (!isValidPassword)
     36            throw new IllegalStateException("Invalid password");
    3537
    3638        boolean isValidUsername = usernameValidator.test(request.getUsername());
    37         if(!isValidUsername) throw new IllegalStateException("Invalid username");
     39        if (!isValidUsername)
     40            throw new IllegalStateException("Invalid username");
    3841
    3942        boolean emailExists = userRepository.findByEmail(request.getEmail()).isPresent();
    40         if(emailExists) {
    41             if(!userRepository.findByEmail(request.getEmail()).get().isEnabled()) {
    42                 String tokenToResend = customUserDetailsService.createToken(userRepository.findByEmail(request.getEmail()).get());
    43                 String link = "http://192.168.0.17:8080/registration/confirm?token=" + tokenToResend;
     43        if (emailExists) {
     44            if (!userRepository.findByEmail(request.getEmail()).get().isEnabled()) {
     45                String tokenToResend = customUserDetailsService
     46                        .createToken(userRepository.findByEmail(request.getEmail()).get());
     47                String link = "http://192.168.0.18:8080/registration/confirm?token=" + tokenToResend;
    4448                emailSender.send(request.getEmail(), emailSender.buildEmail(request.getUsername(), link));
    45                 return tokenToResend; 
     49                return tokenToResend;
    4650            } else {
    47             throw new IllegalStateException("Email is taken");
     51                throw new IllegalStateException("Email is taken");
    4852            }
    4953        }
    5054
    5155        boolean usernameExists = userRepository.findByUsername(request.getUsername()).isPresent();
    52         if(usernameExists) {
     56        if (usernameExists) {
    5357            throw new IllegalStateException("Username is taken");
    5458        }
    5559
    5660        String token = customUserDetailsService.signUp(
    57             new CustomUserDetails(
    58                 request.getFullName(),
    59                 request.getUsername(),
    60                 request.getEmail(),
    61                 request.getPassword(),
    62                 UserRole.REGULAR
    63             )
    64             );
    65        
    66         String link = "http://192.168.0.17:8080/registration/confirm?token=" + token;
    67        
     61                new CustomUserDetails(
     62                        request.getFullName(),
     63                        request.getUsername(),
     64                        request.getEmail(),
     65                        request.getPassword(),
     66                        UserRole.REGULAR));
     67
     68        String link = "http://192.168.0.18:8080/registration/confirm?token=" + token;
     69
    6870        emailSender.send(request.getEmail(), emailSender.buildEmail(request.getUsername(), link));
    69        
     71
    7072        return token;
    7173    }
     
    7577        ConfirmationToken confirmationToken = confirmationTokenService
    7678                .getToken(token)
    77                 .orElseThrow(() ->
    78                         new IllegalStateException("Token not found"));
     79                .orElseThrow(() -> new IllegalStateException("Token not found"));
    7980
    8081        if (confirmationToken.getConfirmedAt() != null) {
  • springapp/src/main/resources/application.properties

    r800779d r6eba109  
    77spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
    88spring.jpa.properties.hibernate.format_sql=true
    9 server.address=192.168.0.17
     9server.address=192.168.0.18
    1010spring.mail.host=192.168.0.24
    1111spring.mail.username=mailuser
Note: See TracChangeset for help on using the changeset viewer.