Files
zitadel/apps/login/src/app/api/otp/set/route.ts

73 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-04-04 13:50:54 +02:00
import {
getMostRecentSessionCookie,
getSessionCookieById,
getSessionCookieByLoginName,
2024-08-08 08:58:54 +02:00
} from "@zitadel/next";
2024-05-13 16:17:12 -04:00
import { setSessionAndUpdateCookie } from "@/utils/session";
2024-04-04 13:50:54 +02:00
import { NextRequest, NextResponse, userAgent } from "next/server";
2024-08-06 09:34:45 +02:00
import { Checks } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
2024-07-25 23:16:07 -04:00
import { PlainMessage } from "@zitadel/client";
2024-04-04 13:50:54 +02:00
export async function POST(request: NextRequest) {
const body = await request.json();
if (body) {
2024-04-16 15:33:14 +02:00
const { loginName, sessionId, organization, authRequestId, code, method } =
body;
2024-04-04 13:50:54 +02:00
2024-08-08 08:58:54 +02:00
const recentPromise = sessionId
2024-08-08 09:28:59 +02:00
? getSessionCookieById({ sessionId }).catch((error) => {
2024-04-04 13:50:54 +02:00
return Promise.reject(error);
})
: loginName
2024-08-08 09:24:03 +02:00
? getSessionCookieByLoginName({ loginName, organization }).catch(
2024-05-13 16:17:12 -04:00
(error) => {
return Promise.reject(error);
},
)
: getMostRecentSessionCookie().catch((error) => {
return Promise.reject(error);
});
2024-04-04 13:50:54 +02:00
return recentPromise
.then((recent) => {
const checks: PlainMessage<Checks> = {};
2024-04-16 15:33:14 +02:00
if (method === "time-based") {
checks.totp = {
code,
};
} else if (method === "sms") {
checks.otpSms = {
code,
};
} else if (method === "email") {
checks.otpEmail = {
code,
};
}
2024-04-04 13:50:54 +02:00
return setSessionAndUpdateCookie(
recent,
2024-04-16 15:33:14 +02:00
checks,
2024-04-04 13:50:54 +02:00
undefined,
2024-05-13 16:17:12 -04:00
authRequestId,
2024-04-04 13:50:54 +02:00
).then((session) => {
return NextResponse.json({
sessionId: session.id,
factors: session.factors,
challenges: session.challenges,
});
});
})
.catch((error) => {
return NextResponse.json({ details: error }, { status: 500 });
});
} else {
return NextResponse.json(
{ details: "Request body is missing" },
2024-05-13 16:17:12 -04:00
{ status: 400 },
2024-04-04 13:50:54 +02:00
);
}
}