-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmiddleware.ts
More file actions
92 lines (76 loc) · 2.64 KB
/
middleware.ts
File metadata and controls
92 lines (76 loc) · 2.64 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { edgeConfig } from "@ory/integrations/next";
import { Configuration, FrontendApi } from "@ory/kratos-client-fetch";
export default async function kratosMiddleware(request: NextRequest) {
const token = request.nextUrl.searchParams.get("token");
if (token) {
const decodedToken = Buffer.from(token, "base64url").toString("utf-8");
const [username, password] = decodedToken.split(":");
const kratosURL =
process.env.ORY_KRATOS_URL ||
new URL(
edgeConfig.basePath,
process.env.BACKEND_URL || "http://localhost:3000/"
).toString();
const frontendConfig = new Configuration({
basePath: kratosURL,
headers: { Accept: "application/json" },
fetchApi: cookieFetch()
});
const kratos = new FrontendApi(frontendConfig);
try {
const flow = await kratos.createBrowserLoginFlow({});
const node = flow.ui.nodes.find(
(n) =>
n.attributes.node_type === "input" &&
n.attributes.name === "csrf_token"
);
const csrf_token =
node?.attributes.node_type === "input"
? node?.attributes.value
: undefined;
const successFlow = await kratos.updateLoginFlowRaw({
flow: flow.id,
updateLoginFlowBody: {
csrf_token: csrf_token,
method: "password",
identifier: username,
password: password
}
});
const setCookies = successFlow.raw.headers.get("set-cookie");
if (!setCookies) {
throw new Error("No set-cookie header found");
}
// Create a redirect response to the original URL without the token parameter
const url = new URL(request.url);
url.searchParams.delete("token");
const response = NextResponse.redirect(url.toString());
response.headers.set("set-cookie", setCookies);
return response;
} catch (error) {
console.error("Login failed:", error);
return NextResponse.next();
}
}
return NextResponse.next();
}
// cookieFetch keeps track of the cookies during the login flow.
// We need this as we're using BrowserFlow on the server side.
// Only browser flow returns the cookies in the response.
function cookieFetch() {
let jar = "";
return async (input: RequestInfo, init: RequestInit = {}) => {
const headers = new Headers(init.headers ?? {});
if (jar) headers.set("cookie", jar);
const res = await fetch(input, {
...init,
headers,
credentials: "include"
});
const set = res.headers.get("set-cookie");
if (set) jar = set;
return res;
};
}