Skip to content

Commit 40b4841

Browse files
committed
Verify a user's auth state
1 parent 4f60321 commit 40b4841

File tree

5 files changed

+44
-28
lines changed

5 files changed

+44
-28
lines changed

backend/user-service/app.ts

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,27 +12,15 @@ dotenv.config();
1212

1313
const file = fs.readFileSync("./swagger.yml", "utf-8");
1414
const swaggerDocument = yaml.parse(file);
15-
const origin = process.env.ORIGINS
15+
const allowedOrigins = process.env.ORIGINS
1616
? process.env.ORIGINS.split(",")
1717
: ["http://localhost:5173", "http://127.0.0.1:5173"];
18-
1918
const app = express();
2019

2120
app.use(express.urlencoded({ extended: true }));
2221
app.use(express.json());
23-
app.use(
24-
cors({
25-
origin: origin,
26-
credentials: true,
27-
})
28-
); // config cors so that front-end can use
29-
app.options(
30-
"*",
31-
cors({
32-
origin: ["http://localhost:5173", "http://127.0.0.1:5173"],
33-
credentials: true,
34-
})
35-
);
22+
app.use(cors({ origin: allowedOrigins, credentials: true })); // config cors so that front-end can use
23+
app.options("*", cors({ origin: allowedOrigins, credentials: true }));
3624

3725
// To handle CORS Errors
3826
app.use((req: Request, res: Response, next: NextFunction) => {

backend/user-service/controller/auth-controller.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,11 @@ export async function handleLogin(
2323
}
2424

2525
const accessToken = jwt.sign(
26-
{
27-
id: user.id,
28-
},
26+
{ id: user.id },
2927
process.env.JWT_SECRET as string,
30-
{
31-
expiresIn: "7d",
32-
}
28+
{ expiresIn: "7d" }
3329
);
30+
console.log(accessToken);
3431
return res.status(200).json({
3532
message: "User logged in",
3633
data: { accessToken, user: formatUserResponse(user) },

backend/user-service/middleware/basic-access-control.ts

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import jwt from "jsonwebtoken";
33
import { findUserById as _findUserById } from "../model/repository";
44
import { AuthenticatedRequest } from "../types/request";
55

6-
export function verifyAccessToken(req: AuthenticatedRequest, res: Response, next: NextFunction) {
6+
export function verifyAccessToken(
7+
req: AuthenticatedRequest,
8+
res: Response,
9+
next: NextFunction
10+
) {
711
const authHeader = req.headers["authorization"];
812
if (!authHeader) {
913
return res.status(401).json({ message: "Authentication failed" });
@@ -25,22 +29,36 @@ export function verifyAccessToken(req: AuthenticatedRequest, res: Response, next
2529
req.user = {
2630
id: dbUser.id,
2731
username: dbUser.username,
32+
firstName: dbUser.firstName,
33+
lastName: dbUser.lastName,
2834
email: dbUser.email,
35+
biography: dbUser.biography,
36+
profilePictureUrl: dbUser.profilePictureUrl,
2937
isAdmin: dbUser.isAdmin,
3038
};
3139
next();
3240
});
3341
}
3442

35-
export function verifyIsAdmin(req: AuthenticatedRequest, res: Response, next: NextFunction) {
43+
export function verifyIsAdmin(
44+
req: AuthenticatedRequest,
45+
res: Response,
46+
next: NextFunction
47+
) {
3648
if (req.user?.isAdmin) {
3749
next();
3850
} else {
39-
return res.status(403).json({ message: "Not authorized to access this resource" });
51+
return res
52+
.status(403)
53+
.json({ message: "Not authorized to access this resource" });
4054
}
4155
}
4256

43-
export function verifyIsOwnerOrAdmin(req: AuthenticatedRequest, res: Response, next: NextFunction) {
57+
export function verifyIsOwnerOrAdmin(
58+
req: AuthenticatedRequest,
59+
res: Response,
60+
next: NextFunction
61+
) {
4462
if (req.user?.isAdmin) {
4563
return next();
4664
}
@@ -52,5 +70,7 @@ export function verifyIsOwnerOrAdmin(req: AuthenticatedRequest, res: Response, n
5270
return next();
5371
}
5472

55-
return res.status(403).json({ message: "Not authorized to access this resource" });
73+
return res
74+
.status(403)
75+
.json({ message: "Not authorized to access this resource" });
5676
}

frontend/src/contexts/AuthContext.tsx

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/* eslint-disable react-refresh/only-export-components */
22

3-
import { createContext, useContext, useState } from "react";
3+
import { createContext, useContext, useEffect, useState } from "react";
4+
import { userClient } from "../utils/api";
45

56
type User = {
67
id: string;
@@ -27,6 +28,16 @@ const AuthProvider: React.FC<{ children?: React.ReactNode }> = (props) => {
2728
const { children } = props;
2829
const [user, setUser] = useState<User | null>(null);
2930

31+
useEffect(() => {
32+
const accessToken = localStorage.getItem("token");
33+
userClient
34+
.get("/auth/verify-token", {
35+
headers: { Authorization: `Bearer ${accessToken}` },
36+
})
37+
.then((res) => setUser(res.data.data))
38+
.catch((_err) => setUser(null));
39+
}, []);
40+
3041
// TODO
3142
const signup = () => {};
3243

frontend/src/utils/api.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import axios from "axios";
22

3-
const usersUrl = "http://localhost:3001/api/";
3+
const usersUrl = "http://localhost:3001/api";
44
const questionsUrl = "http://localhost:3000/api/questions";
55

66
export const questionClient = axios.create({

0 commit comments

Comments
 (0)