Skip to content

Commit

Permalink
Merge pull request #18 from MarvinBo44/frontend/login-sec
Browse files Browse the repository at this point in the history
added secured routes
  • Loading branch information
MarvinBo44 authored Aug 16, 2023
2 parents c0d7851 + ccc1204 commit e34cec9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 12 deletions.
21 changes: 10 additions & 11 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,22 @@ import {Route, Routes} from 'react-router-dom'
import LoginPage from "./LoginPage/LoginPage.tsx";
import RegisterPage from "./Register/Register.tsx";
import HomePage from "./HomePage.tsx";
import ProtectedRoute from "./ProtectedRoutes/ProtectedRoute.tsx";
import {useState} from "react";

function App() {

return (
// <>
// <div>
// <WeatherData weather={weather}/>
// <AddActivity/>
// <CurrentDay weather={weather}/>
//
// </div>
// </>
const [user, setUser] = useState("")


return (
<Routes>
<Route path={"/"} element={<LoginPage/>}/>
<Route path={"/"} element={<LoginPage setUser={setUser}/>}/>
<Route path={"/register"} element={<RegisterPage/>}/>
<Route path={"/home"} element={<HomePage/>}/>

<Route element={<ProtectedRoute user={user}/>}>
<Route path={"/home"} element={<HomePage/>}/>
</Route>
</Routes>
)
}
Expand Down
7 changes: 6 additions & 1 deletion frontend/src/LoginPage/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import {ChangeEvent, FormEvent, useState} from "react";
import axios from "axios";
import {Link, useNavigate} from "react-router-dom";

export default function LoginPage(){
type Props = {
setUser: (user:string) => void
}

export default function LoginPage(loginPageProps:Props){

const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
Expand All @@ -20,6 +24,7 @@ export default function LoginPage(){
function login(event:FormEvent<HTMLFormElement>){
event.preventDefault();
axios.post("/api/user/login", undefined, {auth: {username, password}})
.then((response) => loginPageProps.setUser(response.data))
.then(() => nav("/home"))
.catch((error) => console.log(error));
}
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/ProtectedRoutes/ProtectedRoute.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {Navigate, Outlet} from "react-router-dom";


type Props = {
user: string|undefined;
}

export default function ProtectedRoute(props:Props) {

const authenticated:boolean = props.user !== undefined && props.user !== "anonymousUser" && props.user !== ""

return(
authenticated ? <Outlet/> : <Navigate to={"/"}/>
);
}

0 comments on commit e34cec9

Please sign in to comment.