Skip to content

Commit

Permalink
feat: user auth local store
Browse files Browse the repository at this point in the history
  • Loading branch information
SilveerDusk committed May 24, 2024
1 parent a65b4b3 commit 8588f40
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 15 deletions.
27 changes: 24 additions & 3 deletions backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { groupEndpoints } from "./routes/groupRoutes";
import { basketEndpoints } from "./routes/basketRoutes";
import { itemEndpoints } from "./routes/itemRoutes";
import { loginUser } from "./auth";
import jwt from "jsonwebtoken";

const app: Express = express();
app.use(express.json());
Expand All @@ -13,7 +14,7 @@ app.use((req: Request, res: Response, next: NextFunction) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept",
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
);
res.header(
"Access-Control-Allow-Methods",
Expand All @@ -37,8 +38,28 @@ app.use("/baskets", basketEndpoints);
app.use("/items", itemEndpoints);

app.get("/", async (req: Request, res: Response) => {
const result = "Hello world!";
res.send(result);
const authHeader = req.headers["authorization"];
//Getting the 2nd part of the auth header (the token)
const token = authHeader && authHeader.split(" ")[1];

if (!token) {
console.log("No token received");
res.status(401).end();
} else {
const decoded = jwt.verify(
token,
process.env.TOKEN_SECRET as jwt.Secret,
(error, decoded) => {
if (decoded) {
console.log({ username: (decoded as any).username });
res.status(200).send({ username: (decoded as any).username });
} else {
console.log("JWT error:", error);
res.status(401).end();
}
},
);
}
});

// Error handling middleware
Expand Down
18 changes: 16 additions & 2 deletions backend/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,22 @@ router.get("/:userid", async (req: Request, res: Response) => {
res.send(user);
console.log("Sent user");
} catch (error) {
console.error("Error fetching user:", error); // Log the error for debugging
res.status(500).send("Internal Server Error");
try {
// Use findById correctly with the id parameter from the request
const user = await User.findOne({ username: req.params.userid });

// Check if group is null or undefined
if (!user) {
return res.status(404).send("No users found"); // Use return to exit the function after sending the response
}

// Send the found user
res.send(user);
console.log("Sent user");
} catch (error) {
console.error("Error fetching user:", error); // Log the error for debugging
res.status(500).send("Internal Server Error");
}
}
});

Expand Down
52 changes: 42 additions & 10 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import NavbarSignedIn from "./components/NavbarSignedIn";
import Friends_List from "./components/Friends_List_Component";
import ProfilePage from "./pages/ProfilePage";
import GroupPage from "./pages/MyGroupsPage";
import { useState } from "react";
import { IUser } from "./../../backend/models/userSchema";
import { useState, useEffect } from "react";
import jwt from "jsonwebtoken";
import { IUser } from "../../backend/models/userSchema";
import { get } from "http";

// TODO: When we integrate the frontend to use the backend, we need to use this API server: gather-app-inv.azurewebsites.net
// fetch("gather-app-inv.azurewebsites.net");
Expand All @@ -25,22 +27,52 @@ const getRandomColor = () => {
};

function App() {
const [user, setUser] = useState<IUser | null>(null); // placeholder for our authentication logic
const [token, setToken] = useState(""); // placeholder for our authentication logic
const [token, setToken] = useState(localStorage.getItem("token") ?? "");
const getUser = async () => {
if (token !== "") {
const res = await fetch("http://localhost:3001/", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
if (res.status === 200) {
const data = (await res.json()) as { username: string };
const userres = await fetch(
`http://localhost:3001/users/${data.username}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
);
if (userres.status === 200) {
const user = await userres.json();
console.log(user);
setUser(user);
}
}
}
};

console.log("Token:", token);
const userId = user?._id ?? "";
if (!userId) {
console.log("User ID is not available");
}
useEffect(() => {
getUser().then(() => {
setLoggedIn(true);
});
}, [token]);

const [user, setUser] = useState<IUser | null>(null);
const avatarColor = getRandomColor();
const [loggedIn, setLoggedIn] = useState(false);

return (
<ChakraProvider>
<Router>
<Box width="100vw" height="100vh" display="flex" flexDirection="column">
{token != "" ? (
{loggedIn ? (
<NavbarSignedIn
stateVariable={{ user, token, avatarColor }}
updateState={{ setUser, setToken }}
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const LoginPage = ({ updateState }: { updateState: any }) => {
const data = await res.json();
updateState.setToken(data.token);
updateState.setUser(data.existingUser);
localStorage.setItem("token", data.token);
console.log("Login successful!");
navigate("/");
} else {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/pages/SignupPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const SignupPage = ({
if (login.status === 200) {
const data = await login.json();
updateState.setToken(data.token);
localStorage.setItem("token", data.token);
console.log("Login successful!");
navigate("/");
} else {
Expand Down

0 comments on commit 8588f40

Please sign in to comment.