Skip to content

Commit

Permalink
Post-login redirects for slack
Browse files Browse the repository at this point in the history
  • Loading branch information
archessmn committed Oct 15, 2024
1 parent 0c13727 commit 901a7e8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
9 changes: 6 additions & 3 deletions app/login/slack/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { getSlackUserInfo } from "@/lib/auth/slack";
import {
cookieName,
getCurrentUserOrNull,
loginOrCreateUserSlack,
} from "@/lib/auth/server";
Expand All @@ -9,9 +10,11 @@ import { env } from "@/lib/env";
export const dynamic = "force-dynamic";

export async function GET(req: NextRequest): Promise<NextResponse> {
const cookies = req.cookies;
const redirect = cookies.get(`${cookieName}.redirect`);

const searchParams = req.nextUrl.searchParams;
const code = searchParams.get("code");
const redirect = searchParams.get("redirect");

if (typeof code !== "string" || code === null) {
return new NextResponse(
Expand All @@ -22,11 +25,11 @@ export async function GET(req: NextRequest): Promise<NextResponse> {
);
}

const slackUserInfo = await getSlackUserInfo(code, redirect);
const slackUserInfo = await getSlackUserInfo(code);
let user = await getCurrentUserOrNull(req);
user = await loginOrCreateUserSlack(slackUserInfo);

var url = new URL(redirect ?? "/user/me", env.PUBLIC_URL!);
var url = new URL(redirect?.value ?? "/user/me", env.PUBLIC_URL!);

if (!url.href.startsWith(env.PUBLIC_URL!)) url = new URL(env.PUBLIC_URL!);

Expand Down
6 changes: 2 additions & 4 deletions lib/auth/slack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,14 @@ export type SlackTokenJson = {
picture: string;
};

export async function getSlackUserInfo(code: string, redirect?: string | null) {
export async function getSlackUserInfo(code: string) {
invariant(isSlackEnabled, "Slack is not enabled");
const slackApp = await slackApiConnection();
const tokenResponse = await slackApp.client.openid.connect.token({
client_id: env.SLACK_CLIENT_ID || "",
client_secret: env.SLACK_CLIENT_SECRET || "",
code: code,
redirect_uri: `${env.PUBLIC_URL}/login/slack/callback${
redirect ? "?redirect=" + redirect : ""
}`,
redirect_uri: `${env.PUBLIC_URL}/login/slack/callback`,
});
const token = jwtDecode(tokenResponse.id_token!) as SlackTokenJson;
return token;
Expand Down

0 comments on commit 901a7e8

Please sign in to comment.