-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.js
78 lines (76 loc) · 2.29 KB
/
middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
import isRecipeAuthor from "@middleware/isRecipeAuthor";
export default withAuth(
async function middleware(req) {
if (req.nextUrl.pathname.startsWith("/api/recipes")) {
if (req.method == "DELETE" && req.nextUrl.pathname.includes("/reviews")) {
const isAuthorized =
req?.nextauth?.token?.user_id ===
req.nextUrl.searchParams.get("author_id");
// console.log(isAuthorized);
if (isAuthorized) {
return NextResponse.next();
} else {
return NextResponse.json(
{ message: "Unauthorized" },
{ status: 401 }
);
}
// Allow deletion of any recipe by the author of recipe
// const isAuthorized = false;
}
if (req.method == "PUT") {
const data = await req.json();
const isAuthotrized = isRecipeAuthor(
data?.author,
req?.nextauth?.token?.user_id
);
if (isAuthotrized) {
return NextResponse.next();
} else {
return NextResponse.redirect(new URL("/not-authorized", req.url));
}
}
if (req.method == "DELETE") {
// Allow deletion of any recipe by the author of recipe
const isAuthorized =
req?.nextauth?.token?.user_id ===
req.nextUrl.searchParams.get("author_id");
// const isAuthorized = false;
if (isAuthorized) {
return NextResponse.next();
} else {
return NextResponse.json(
{ message: "Unauthorized" },
{ status: 401 }
);
}
}
} else if (req.nextUrl.pathname.startsWith("/api/users")) {
if (req.method == "PUT") {
const data = await req.json();
const isAuthotrized = data?.email === req?.nextauth?.token?.email;
if (isAuthotrized) {
return NextResponse.next();
} else {
return NextResponse.redirect(new URL("/not-authorized", req.url));
}
} else {
return NextResponse.next();
}
} else {
return NextResponse.next();
}
},
{
callbacks: {
authorized: ({ token }) => {
!!token;
},
},
}
);
export const config = {
matcher: ["/api/:path*"],
};