Changeset 6eba109
- Timestamp:
- 08/17/22 16:21:10 (2 years ago)
- Branches:
- main
- Children:
- 702ca77
- Parents:
- 800779d
- Files:
-
- 4 added
- 12 edited
Legend:
- Unmodified
- Added
- Removed
-
reactapp/src/App.js
r800779d r6eba109 2 2 import SearchResults from "./Pages/SearchResults"; 3 3 import Login from "./Pages/Login"; 4 import { BrowserRouter, Routes, Route } from "react-router-dom";4 import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"; 5 5 import Home from "./Pages/Home"; 6 import User from "./Pages/User"; 7 import { useEffect, useState, useMemo } from "react"; 8 import AuthApi from "./api/AuthApi"; 9 import Cookies from "js-cookie"; 6 10 7 11 export 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 8 33 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> 15 51 </Route> 16 <Route path="search" element={<SearchResults />}></Route> 17 </Route> 18 </Routes> 19 </BrowserRouter> 52 </Routes> 53 </BrowserRouter> 54 </AuthApi.Provider> 20 55 ); 21 56 } -
reactapp/src/Components/Search.js
r800779d r6eba109 15 15 16 16 useEffect(() => { 17 const url = `http://192.168.0.1 7:8080/public/professors/nameContains/${transliterate(17 const url = `http://192.168.0.18:8080/public/professors/nameContains/${transliterate( 18 18 query 19 19 )}`; -
reactapp/src/Pages/Home.js
r800779d r6eba109 20 20 </a>{" "} 21 21 <Search /> 22 <div style={{ marginTop: "140px" }}></div> 22 23 <Outlet /> 23 24 </MainWrapper> -
reactapp/src/Pages/Login.js
r800779d r6eba109 1 import React, { useRef, useState, useEffect } from "react"; 1 import React, { useRef, useState, useEffect, useContext } from "react"; 2 import { Navigate } from "react-router-dom"; 3 import AuthApi from "../api/AuthApi"; 2 4 import axios from "../api/axios"; 5 import Cookies from "js-cookie"; 3 6 const LOGIN_URL = "/login"; 4 7 5 8 const Login = () => { 9 const { auth, setAuth } = useContext(AuthApi); 6 10 const userRef = useRef(); 7 11 const errRef = useRef(); … … 10 14 const [password, setPassword] = useState(""); 11 15 const [errMsg, setErrMsg] = useState(""); 12 const [success, setSuccess] = useState(false);13 16 14 17 useEffect(() => { 15 18 userRef.current.focus(); 16 19 }, []); 17 18 useEffect(() => {19 setErrMsg("");20 }, [username, password]);21 20 22 21 const handleSubmit = async (e) => { … … 33 32 } 34 33 ); 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 35 43 setUsername(""); 36 44 setPassword(""); 37 setSuccess(true);38 45 }; 39 46 40 return success ? ( 47 const handleLogout = () => { 48 setAuth(false); 49 Cookies.remove("JSESSIONID"); 50 }; 51 52 return auth ? ( 53 /* 41 54 <div style={{ marginTop: "140px" }}> 42 55 <h1>Успешна најава!</h1> 43 56 <br /> 44 57 <p> 45 <a href="/ ">Оди на почетната страница</a>58 <a href="/user">Оди на protected</a> 46 59 </p> 60 <button onClick={handleLogout}>Одјави се</button> 47 61 </div> 62 */ 63 <Navigate to="/user" /> 48 64 ) : ( 49 65 <div style={{ marginTop: "140px" }}> -
reactapp/src/Pages/Professor.js
r800779d r6eba109 18 18 19 19 useEffect(() => { 20 const url = `http://192.168.0.1 7:8080/public/professor/${params.professorId}`;20 const url = `http://192.168.0.18:8080/public/professor/${params.professorId}`; 21 21 22 22 const fetchData = async () => { -
reactapp/src/api/axios.js
r800779d r6eba109 2 2 3 3 export default axios.create({ 4 baseURL: "http://192.168.0.1 7:8080",4 baseURL: "http://192.168.0.18:8080", 5 5 }); -
springapp/src/main/java/mk/profesori/springapp/Controller/PublicController.java
r800779d r6eba109 1 1 package mk.profesori.springapp.Controller; 2 2 3 import java.util.Collections; 3 4 import java.util.List; 5 import java.util.Map; 4 6 import java.util.Optional; 5 7 … … 21 23 @RestController 22 24 @RequestMapping("/public") 23 @CrossOrigin(origins = { "http://192.168.0.1 7:3000", "http://192.168.0.24:3000" })25 @CrossOrigin(origins = { "http://192.168.0.18:3000", "http://192.168.0.24:3000" }) 24 26 public class PublicController { 25 27 … … 95 97 return mainService.getCityById(cityId); // vrakja grad spored id 96 98 } 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 } 97 109 } -
springapp/src/main/java/mk/profesori/springapp/Controller/SecureController.java
r800779d r6eba109 1 1 package mk.profesori.springapp.Controller; 2 3 import java.util.Collections; 4 import java.util.Map; 2 5 3 6 import org.springframework.beans.factory.annotation.Autowired; … … 5 8 import org.springframework.security.core.annotation.CurrentSecurityContext; 6 9 import org.springframework.security.core.context.SecurityContext; 10 import org.springframework.security.core.userdetails.UserDetails; 7 11 import org.springframework.web.bind.annotation.CrossOrigin; 8 12 import org.springframework.web.bind.annotation.PathVariable; … … 10 14 import org.springframework.web.bind.annotation.RequestMapping; 11 15 import org.springframework.web.bind.annotation.RequestMethod; 16 import org.springframework.web.bind.annotation.RequestParam; 12 17 import org.springframework.web.bind.annotation.RestController; 13 18 … … 15 20 16 21 import mk.profesori.springapp.Model.CustomUserDetails; 22 import mk.profesori.springapp.Service.CustomUserDetailsService; 17 23 import mk.profesori.springapp.Service.MainService; 18 24 19 25 @RestController 20 26 @RequestMapping("/secure") 21 @CrossOrigin(origins = { "http://192.168.0.1 7:3000", "http://192.168.0.24:3000" })27 @CrossOrigin(origins = { "http://192.168.0.18:3000", "http://192.168.0.24:3000" }) 22 28 public class SecureController { 23 29 24 30 @Autowired 25 31 private MainService mainService; 32 @Autowired 33 CustomUserDetailsService customUserDetailsService; 26 34 27 35 @RequestMapping(value = "/professor/{professorId}/addOpinion", method = RequestMethod.POST) … … 52 60 } 53 61 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 54 74 } -
springapp/src/main/java/mk/profesori/springapp/Model/CustomUserDetails.java
r800779d r6eba109 53 53 private Set<ConfirmationToken> confirmationTokens = new HashSet<>(); 54 54 @OneToMany(mappedBy = "author", cascade = CascadeType.ALL) 55 private List<Post> authoredPosts = new ArrayList<>();55 private Set<Post> authoredPosts = new HashSet<>(); 56 56 57 57 public CustomUserDetails(String fullName, String username, String email, String password, UserRole userRole) { … … 99 99 } 100 100 101 List<Post> getAuthoredPosts() {101 public Set<Post> getAuthoredPosts() { 102 102 return this.authoredPosts; 103 103 } -
springapp/src/main/java/mk/profesori/springapp/Security/SecurityConfiguration.java
r800779d r6eba109 10 10 import org.springframework.security.crypto.password.PasswordEncoder; 11 11 import org.springframework.security.web.SecurityFilterChain; 12 import org.springframework.security.web.authentication.AuthenticationSuccessHandler; 12 13 import org.springframework.web.servlet.config.annotation.CorsRegistry; 13 14 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; … … 36 37 @Override 37 38 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); 39 41 } 40 42 }; 43 } 44 45 @Bean 46 public AuthenticationSuccessHandler customAuthenticationSuccessHandler() { 47 return new CustomAuthenticationSuccessHandler(); 41 48 } 42 49 … … 54 61 .antMatchers("/registration/**").permitAll() 55 62 .and() 56 .formLogin() ;63 .formLogin().successHandler(customAuthenticationSuccessHandler()); 57 64 58 65 return http.build(); -
springapp/src/main/java/mk/profesori/springapp/Service/RegistrationService.java
r800779d r6eba109 25 25 private final EmailSender emailSender; 26 26 private final UserRepository userRepository; 27 27 28 28 public String register(RegistrationRequest request) { 29 29 30 30 boolean isValidEmail = emailValidator.test(request.getEmail()); 31 if(!isValidEmail) throw new IllegalStateException("Invalid email"); 31 if (!isValidEmail) 32 throw new IllegalStateException("Invalid email"); 32 33 33 34 boolean isValidPassword = passwordValidator.test(request.getPassword()); 34 if(!isValidPassword) throw new IllegalStateException("Invalid password"); 35 if (!isValidPassword) 36 throw new IllegalStateException("Invalid password"); 35 37 36 38 boolean isValidUsername = usernameValidator.test(request.getUsername()); 37 if(!isValidUsername) throw new IllegalStateException("Invalid username"); 39 if (!isValidUsername) 40 throw new IllegalStateException("Invalid username"); 38 41 39 42 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; 44 48 emailSender.send(request.getEmail(), emailSender.buildEmail(request.getUsername(), link)); 45 return tokenToResend; 49 return tokenToResend; 46 50 } else { 47 throw new IllegalStateException("Email is taken");51 throw new IllegalStateException("Email is taken"); 48 52 } 49 53 } 50 54 51 55 boolean usernameExists = userRepository.findByUsername(request.getUsername()).isPresent(); 52 if (usernameExists) {56 if (usernameExists) { 53 57 throw new IllegalStateException("Username is taken"); 54 58 } 55 59 56 60 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 68 70 emailSender.send(request.getEmail(), emailSender.buildEmail(request.getUsername(), link)); 69 71 70 72 return token; 71 73 } … … 75 77 ConfirmationToken confirmationToken = confirmationTokenService 76 78 .getToken(token) 77 .orElseThrow(() -> 78 new IllegalStateException("Token not found")); 79 .orElseThrow(() -> new IllegalStateException("Token not found")); 79 80 80 81 if (confirmationToken.getConfirmedAt() != null) { -
springapp/src/main/resources/application.properties
r800779d r6eba109 7 7 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect 8 8 spring.jpa.properties.hibernate.format_sql=true 9 server.address=192.168.0.1 79 server.address=192.168.0.18 10 10 spring.mail.host=192.168.0.24 11 11 spring.mail.username=mailuser
Note:
See TracChangeset
for help on using the changeset viewer.