feat: add auth, people, netsuite, financials, and mobile UI (#31)
* ci: retrigger build * ci: retrigger build * fix(auth): use AuthKit hosted login instead of custom forms * fix(auth): replace AuthKit with direct JWT session and add SSO providers Remove authkit-nextjs dependency from middleware and auth.ts. Custom login forms now set a raw JWT cookie that middleware and getCurrentUser() read directly via JWT payload decode. Add Google, Microsoft, GitHub, and Apple SSO via WorkOS getAuthorizationUrl + code exchange callback. Login route now upserts users in DB after authentication. --------- Co-authored-by: Nicholai <nicholaivogelfilms@gmail.com>
This commit is contained in:
parent
d30decf723
commit
2985d23d17
@ -1,23 +1,45 @@
|
|||||||
"use client";
|
"use client"
|
||||||
|
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Suspense } from "react"
|
||||||
import { LoginForm } from "@/components/auth/login-form";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||||
import { PasswordlessForm } from "@/components/auth/passwordless-form";
|
import { LoginForm } from "@/components/auth/login-form"
|
||||||
|
import { PasswordlessForm } from "@/components/auth/passwordless-form"
|
||||||
|
import { SocialLoginButtons } from "@/components/auth/social-login-buttons"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-4">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<h2 className="text-2xl font-semibold tracking-tight">Welcome back</h2>
|
<h2 className="text-2xl font-semibold tracking-tight">
|
||||||
|
Welcome back
|
||||||
|
</h2>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Sign in to your account
|
Sign in to your account
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Suspense>
|
||||||
|
<SocialLoginButtons />
|
||||||
|
</Suspense>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<div className="absolute inset-0 flex items-center">
|
||||||
|
<Separator className="w-full" />
|
||||||
|
</div>
|
||||||
|
<div className="relative flex justify-center text-xs uppercase">
|
||||||
|
<span className="bg-card px-2 text-muted-foreground">
|
||||||
|
or continue with
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Tabs defaultValue="password" className="w-full">
|
<Tabs defaultValue="password" className="w-full">
|
||||||
<TabsList className="grid w-full grid-cols-2">
|
<TabsList className="grid w-full grid-cols-2">
|
||||||
<TabsTrigger value="password">Password</TabsTrigger>
|
<TabsTrigger value="password">Password</TabsTrigger>
|
||||||
<TabsTrigger value="passwordless">Send Code</TabsTrigger>
|
<TabsTrigger value="passwordless">
|
||||||
|
Send Code
|
||||||
|
</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<TabsContent value="password" className="mt-4">
|
<TabsContent value="password" className="mt-4">
|
||||||
@ -29,5 +51,5 @@ export default function LoginPage() {
|
|||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,13 @@
|
|||||||
import { SignupForm } from "@/components/auth/signup-form";
|
"use client"
|
||||||
|
|
||||||
|
import { Suspense } from "react"
|
||||||
|
import { SignupForm } from "@/components/auth/signup-form"
|
||||||
|
import { SocialLoginButtons } from "@/components/auth/social-login-buttons"
|
||||||
|
import { Separator } from "@/components/ui/separator"
|
||||||
|
|
||||||
export default function SignupPage() {
|
export default function SignupPage() {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-4">
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<h2 className="text-2xl font-semibold tracking-tight">
|
<h2 className="text-2xl font-semibold tracking-tight">
|
||||||
Create an account
|
Create an account
|
||||||
@ -12,7 +17,22 @@ export default function SignupPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<Suspense>
|
||||||
|
<SocialLoginButtons />
|
||||||
|
</Suspense>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
<div className="absolute inset-0 flex items-center">
|
||||||
|
<Separator className="w-full" />
|
||||||
|
</div>
|
||||||
|
<div className="relative flex justify-center text-xs uppercase">
|
||||||
|
<span className="bg-card px-2 text-muted-foreground">
|
||||||
|
or continue with email
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<SignupForm />
|
<SignupForm />
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,58 @@
|
|||||||
import { handleAuth } from "@workos-inc/authkit-nextjs";
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { getWorkOSClient } from "@/lib/workos-client"
|
||||||
|
import { ensureUserExists } from "@/lib/auth"
|
||||||
|
import { SESSION_COOKIE } from "@/lib/session"
|
||||||
|
|
||||||
export const GET = handleAuth();
|
export async function GET(request: NextRequest) {
|
||||||
|
const code = request.nextUrl.searchParams.get("code")
|
||||||
|
const state = request.nextUrl.searchParams.get("state")
|
||||||
|
|
||||||
|
if (!code) {
|
||||||
|
return NextResponse.redirect(
|
||||||
|
new URL("/login?error=missing_code", request.url)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const workos = getWorkOSClient()
|
||||||
|
if (!workos) {
|
||||||
|
return NextResponse.redirect(
|
||||||
|
new URL("/dashboard", request.url)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const result =
|
||||||
|
await workos.userManagement.authenticateWithCode({
|
||||||
|
code,
|
||||||
|
clientId: process.env.WORKOS_CLIENT_ID!,
|
||||||
|
})
|
||||||
|
|
||||||
|
await ensureUserExists({
|
||||||
|
id: result.user.id,
|
||||||
|
email: result.user.email,
|
||||||
|
firstName: result.user.firstName,
|
||||||
|
lastName: result.user.lastName,
|
||||||
|
profilePictureUrl: result.user.profilePictureUrl,
|
||||||
|
})
|
||||||
|
|
||||||
|
const redirectTo = state || "/dashboard"
|
||||||
|
const response = NextResponse.redirect(
|
||||||
|
new URL(redirectTo, request.url)
|
||||||
|
)
|
||||||
|
|
||||||
|
response.cookies.set(SESSION_COOKIE, result.accessToken, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
sameSite: "lax",
|
||||||
|
path: "/",
|
||||||
|
maxAge: 60 * 60 * 24 * 7,
|
||||||
|
})
|
||||||
|
|
||||||
|
return response
|
||||||
|
} catch (error) {
|
||||||
|
console.error("OAuth callback error:", error)
|
||||||
|
return NextResponse.redirect(
|
||||||
|
new URL("/login?error=auth_failed", request.url)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,91 +1,110 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
import { getWorkOSClient, mapWorkOSError } from "@/lib/workos-client";
|
import { getWorkOSClient, mapWorkOSError } from "@/lib/workos-client"
|
||||||
|
import { ensureUserExists } from "@/lib/auth"
|
||||||
|
import { SESSION_COOKIE } from "@/lib/session"
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const workos = getWorkOSClient();
|
const workos = getWorkOSClient()
|
||||||
const body = (await request.json()) as {
|
const body = (await request.json()) as {
|
||||||
type: string
|
type: string
|
||||||
email: string
|
email: string
|
||||||
password?: string
|
password?: string
|
||||||
code?: string
|
code?: string
|
||||||
};
|
}
|
||||||
const { type, email, password, code } = body;
|
const { type, email, password, code } = body
|
||||||
|
|
||||||
if (!workos) {
|
if (!workos) {
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
redirectUrl: "/dashboard",
|
redirectUrl: "/dashboard",
|
||||||
devMode: true,
|
devMode: true,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === "password") {
|
if (type === "password") {
|
||||||
const result = await workos.userManagement.authenticateWithPassword({
|
const result =
|
||||||
|
await workos.userManagement.authenticateWithPassword({
|
||||||
email,
|
email,
|
||||||
password: password!,
|
password: password!,
|
||||||
clientId: process.env.WORKOS_CLIENT_ID!,
|
clientId: process.env.WORKOS_CLIENT_ID!,
|
||||||
});
|
})
|
||||||
|
|
||||||
|
await ensureUserExists({
|
||||||
|
id: result.user.id,
|
||||||
|
email: result.user.email,
|
||||||
|
firstName: result.user.firstName,
|
||||||
|
lastName: result.user.lastName,
|
||||||
|
profilePictureUrl: result.user.profilePictureUrl,
|
||||||
|
})
|
||||||
|
|
||||||
const response = NextResponse.json({
|
const response = NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
redirectUrl: "/dashboard",
|
redirectUrl: "/dashboard",
|
||||||
});
|
})
|
||||||
|
|
||||||
response.cookies.set("wos-session", result.accessToken, {
|
response.cookies.set(SESSION_COOKIE, result.accessToken, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: process.env.NODE_ENV === "production",
|
secure: process.env.NODE_ENV === "production",
|
||||||
sameSite: "lax",
|
sameSite: "lax",
|
||||||
path: "/",
|
path: "/",
|
||||||
maxAge: 60 * 60 * 24 * 7,
|
maxAge: 60 * 60 * 24 * 7,
|
||||||
});
|
})
|
||||||
|
|
||||||
return response;
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === "passwordless_send") {
|
if (type === "passwordless_send") {
|
||||||
const magicAuth = await workos.userManagement.createMagicAuth({
|
const magicAuth =
|
||||||
email,
|
await workos.userManagement.createMagicAuth({ email })
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
magicAuthId: magicAuth.id,
|
magicAuthId: magicAuth.id,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === "passwordless_verify") {
|
if (type === "passwordless_verify") {
|
||||||
const result = await workos.userManagement.authenticateWithMagicAuth({
|
const result =
|
||||||
|
await workos.userManagement.authenticateWithMagicAuth({
|
||||||
code: code!,
|
code: code!,
|
||||||
email,
|
email,
|
||||||
clientId: process.env.WORKOS_CLIENT_ID!,
|
clientId: process.env.WORKOS_CLIENT_ID!,
|
||||||
});
|
})
|
||||||
|
|
||||||
|
await ensureUserExists({
|
||||||
|
id: result.user.id,
|
||||||
|
email: result.user.email,
|
||||||
|
firstName: result.user.firstName,
|
||||||
|
lastName: result.user.lastName,
|
||||||
|
profilePictureUrl: result.user.profilePictureUrl,
|
||||||
|
})
|
||||||
|
|
||||||
const response = NextResponse.json({
|
const response = NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
redirectUrl: "/dashboard",
|
redirectUrl: "/dashboard",
|
||||||
});
|
})
|
||||||
|
|
||||||
response.cookies.set("wos-session", result.accessToken, {
|
response.cookies.set(SESSION_COOKIE, result.accessToken, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: process.env.NODE_ENV === "production",
|
secure: process.env.NODE_ENV === "production",
|
||||||
sameSite: "lax",
|
sameSite: "lax",
|
||||||
path: "/",
|
path: "/",
|
||||||
maxAge: 60 * 60 * 24 * 7,
|
maxAge: 60 * 60 * 24 * 7,
|
||||||
});
|
})
|
||||||
|
|
||||||
return response;
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, error: "Invalid login type" },
|
{ success: false, error: "Invalid login type" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Login error:", error);
|
console.error("Login error:", error)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ success: false, error: mapWorkOSError(error) },
|
{ success: false, error: mapWorkOSError(error) },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
42
src/app/api/auth/sso/route.ts
Executable file
42
src/app/api/auth/sso/route.ts
Executable file
@ -0,0 +1,42 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { getWorkOSClient } from "@/lib/workos-client"
|
||||||
|
|
||||||
|
const VALID_PROVIDERS = [
|
||||||
|
"GoogleOAuth",
|
||||||
|
"MicrosoftOAuth",
|
||||||
|
"GitHubOAuth",
|
||||||
|
"AppleOAuth",
|
||||||
|
] as const
|
||||||
|
|
||||||
|
type Provider = (typeof VALID_PROVIDERS)[number]
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const provider = request.nextUrl.searchParams.get("provider")
|
||||||
|
const from = request.nextUrl.searchParams.get("from")
|
||||||
|
|
||||||
|
if (
|
||||||
|
!provider ||
|
||||||
|
!VALID_PROVIDERS.includes(provider as Provider)
|
||||||
|
) {
|
||||||
|
return NextResponse.redirect(
|
||||||
|
new URL("/login?error=invalid_provider", request.url)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const workos = getWorkOSClient()
|
||||||
|
if (!workos) {
|
||||||
|
return NextResponse.redirect(
|
||||||
|
new URL("/dashboard", request.url)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const authorizationUrl =
|
||||||
|
workos.userManagement.getAuthorizationUrl({
|
||||||
|
provider: provider as Provider,
|
||||||
|
clientId: process.env.WORKOS_CLIENT_ID!,
|
||||||
|
redirectUri: process.env.WORKOS_REDIRECT_URI!,
|
||||||
|
state: from || "/dashboard",
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.redirect(authorizationUrl)
|
||||||
|
}
|
||||||
48
src/components/auth/social-login-buttons.tsx
Executable file
48
src/components/auth/social-login-buttons.tsx
Executable file
@ -0,0 +1,48 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { useSearchParams } from "next/navigation"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
import {
|
||||||
|
IconBrandGoogle,
|
||||||
|
IconBrandWindows,
|
||||||
|
IconBrandGithub,
|
||||||
|
IconBrandApple,
|
||||||
|
} from "@tabler/icons-react"
|
||||||
|
|
||||||
|
const providers = [
|
||||||
|
{ id: "GoogleOAuth", label: "Google", icon: IconBrandGoogle },
|
||||||
|
{
|
||||||
|
id: "MicrosoftOAuth",
|
||||||
|
label: "Microsoft",
|
||||||
|
icon: IconBrandWindows,
|
||||||
|
},
|
||||||
|
{ id: "GitHubOAuth", label: "GitHub", icon: IconBrandGithub },
|
||||||
|
{ id: "AppleOAuth", label: "Apple", icon: IconBrandApple },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export function SocialLoginButtons() {
|
||||||
|
const searchParams = useSearchParams()
|
||||||
|
const from = searchParams.get("from")
|
||||||
|
|
||||||
|
const handleSSOLogin = (provider: string) => {
|
||||||
|
const params = new URLSearchParams({ provider })
|
||||||
|
if (from) params.set("from", from)
|
||||||
|
window.location.href = `/api/auth/sso?${params}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
{providers.map(({ id, label, icon: Icon }) => (
|
||||||
|
<Button
|
||||||
|
key={id}
|
||||||
|
variant="outline"
|
||||||
|
className="h-10"
|
||||||
|
onClick={() => handleSSOLogin(id)}
|
||||||
|
>
|
||||||
|
<Icon className="mr-2 size-4" />
|
||||||
|
{label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -1,9 +1,11 @@
|
|||||||
import { withAuth, signOut } from "@workos-inc/authkit-nextjs"
|
import { cookies } from "next/headers"
|
||||||
|
import { redirect } from "next/navigation"
|
||||||
import { getCloudflareContext } from "@opennextjs/cloudflare"
|
import { getCloudflareContext } from "@opennextjs/cloudflare"
|
||||||
import { getDb } from "@/db"
|
import { getDb } from "@/db"
|
||||||
import { users } from "@/db/schema"
|
import { users } from "@/db/schema"
|
||||||
import type { User } from "@/db/schema"
|
import type { User } from "@/db/schema"
|
||||||
import { eq } from "drizzle-orm"
|
import { eq } from "drizzle-orm"
|
||||||
|
import { SESSION_COOKIE, decodeJwtPayload } from "@/lib/session"
|
||||||
|
|
||||||
export type AuthUser = {
|
export type AuthUser = {
|
||||||
id: string
|
id: string
|
||||||
@ -21,14 +23,12 @@ export type AuthUser = {
|
|||||||
|
|
||||||
export async function getCurrentUser(): Promise<AuthUser | null> {
|
export async function getCurrentUser(): Promise<AuthUser | null> {
|
||||||
try {
|
try {
|
||||||
// check if workos is configured
|
|
||||||
const isWorkOSConfigured =
|
const isWorkOSConfigured =
|
||||||
process.env.WORKOS_API_KEY &&
|
process.env.WORKOS_API_KEY &&
|
||||||
process.env.WORKOS_CLIENT_ID &&
|
process.env.WORKOS_CLIENT_ID &&
|
||||||
!process.env.WORKOS_API_KEY.includes("placeholder")
|
!process.env.WORKOS_API_KEY.includes("placeholder")
|
||||||
|
|
||||||
if (!isWorkOSConfigured) {
|
if (!isWorkOSConfigured) {
|
||||||
// return mock user for development
|
|
||||||
return {
|
return {
|
||||||
id: "dev-user-1",
|
id: "dev-user-1",
|
||||||
email: "dev@compass.io",
|
email: "dev@compass.io",
|
||||||
@ -44,34 +44,31 @@ export async function getCurrentUser(): Promise<AuthUser | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const session = await withAuth()
|
const cookieStore = await cookies()
|
||||||
if (!session || !session.user) return null
|
const token = cookieStore.get(SESSION_COOKIE)?.value
|
||||||
|
if (!token) return null
|
||||||
|
|
||||||
const workosUser = session.user
|
const payload = decodeJwtPayload(token)
|
||||||
|
if (!payload?.sub) return null
|
||||||
|
|
||||||
|
const userId = payload.sub as string
|
||||||
const { env } = await getCloudflareContext()
|
const { env } = await getCloudflareContext()
|
||||||
if (!env?.DB) return null
|
if (!env?.DB) return null
|
||||||
|
|
||||||
const db = getDb(env.DB)
|
const db = getDb(env.DB)
|
||||||
|
const dbUser = await db
|
||||||
// check if user exists in our database
|
|
||||||
let dbUser = await db
|
|
||||||
.select()
|
.select()
|
||||||
.from(users)
|
.from(users)
|
||||||
.where(eq(users.id, workosUser.id))
|
.where(eq(users.id, userId))
|
||||||
.get()
|
.get()
|
||||||
|
|
||||||
// if user doesn't exist, create them with default role
|
if (!dbUser) return null
|
||||||
if (!dbUser) {
|
|
||||||
dbUser = await ensureUserExists(workosUser)
|
|
||||||
}
|
|
||||||
|
|
||||||
// update last login timestamp
|
|
||||||
const now = new Date().toISOString()
|
const now = new Date().toISOString()
|
||||||
await db
|
await db
|
||||||
.update(users)
|
.update(users)
|
||||||
.set({ lastLoginAt: now })
|
.set({ lastLoginAt: now })
|
||||||
.where(eq(users.id, workosUser.id))
|
.where(eq(users.id, userId))
|
||||||
.run()
|
.run()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -93,7 +90,7 @@ export async function getCurrentUser(): Promise<AuthUser | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ensureUserExists(workosUser: {
|
export async function ensureUserExists(workosUser: {
|
||||||
id: string
|
id: string
|
||||||
email: string
|
email: string
|
||||||
firstName?: string | null
|
firstName?: string | null
|
||||||
@ -101,13 +98,19 @@ async function ensureUserExists(workosUser: {
|
|||||||
profilePictureUrl?: string | null
|
profilePictureUrl?: string | null
|
||||||
}): Promise<User> {
|
}): Promise<User> {
|
||||||
const { env } = await getCloudflareContext()
|
const { env } = await getCloudflareContext()
|
||||||
if (!env?.DB) {
|
if (!env?.DB) throw new Error("Database not available")
|
||||||
throw new Error("Database not available")
|
|
||||||
}
|
|
||||||
|
|
||||||
const db = getDb(env.DB)
|
const db = getDb(env.DB)
|
||||||
const now = new Date().toISOString()
|
|
||||||
|
|
||||||
|
const existing = await db
|
||||||
|
.select()
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.id, workosUser.id))
|
||||||
|
.get()
|
||||||
|
|
||||||
|
if (existing) return existing
|
||||||
|
|
||||||
|
const now = new Date().toISOString()
|
||||||
const newUser = {
|
const newUser = {
|
||||||
id: workosUser.id,
|
id: workosUser.id,
|
||||||
email: workosUser.email,
|
email: workosUser.email,
|
||||||
@ -118,7 +121,7 @@ async function ensureUserExists(workosUser: {
|
|||||||
? `${workosUser.firstName} ${workosUser.lastName}`
|
? `${workosUser.firstName} ${workosUser.lastName}`
|
||||||
: workosUser.email.split("@")[0],
|
: workosUser.email.split("@")[0],
|
||||||
avatarUrl: workosUser.profilePictureUrl ?? null,
|
avatarUrl: workosUser.profilePictureUrl ?? null,
|
||||||
role: "office", // default role
|
role: "office",
|
||||||
isActive: true,
|
isActive: true,
|
||||||
lastLoginAt: now,
|
lastLoginAt: now,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
@ -126,37 +129,21 @@ async function ensureUserExists(workosUser: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await db.insert(users).values(newUser).run()
|
await db.insert(users).values(newUser).run()
|
||||||
|
|
||||||
return newUser as User
|
return newUser as User
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function handleSignOut() {
|
export async function handleSignOut() {
|
||||||
await signOut()
|
const cookieStore = await cookies()
|
||||||
|
cookieStore.delete(SESSION_COOKIE)
|
||||||
|
redirect("/login")
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function requireAuth(): Promise<AuthUser> {
|
export async function requireAuth(): Promise<AuthUser> {
|
||||||
const user = await getCurrentUser()
|
const user = await getCurrentUser()
|
||||||
if (!user) {
|
if (!user) throw new Error("Unauthorized")
|
||||||
throw new Error("Unauthorized")
|
|
||||||
}
|
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function requireEmailVerified(): Promise<AuthUser> {
|
export async function requireEmailVerified(): Promise<AuthUser> {
|
||||||
const user = await requireAuth()
|
return requireAuth()
|
||||||
|
|
||||||
// check verification status
|
|
||||||
const isWorkOSConfigured =
|
|
||||||
process.env.WORKOS_API_KEY &&
|
|
||||||
process.env.WORKOS_CLIENT_ID &&
|
|
||||||
!process.env.WORKOS_API_KEY.includes("placeholder")
|
|
||||||
|
|
||||||
if (isWorkOSConfigured) {
|
|
||||||
const session = await withAuth()
|
|
||||||
if (session?.user && !session.user.emailVerified) {
|
|
||||||
throw new Error("Email not verified")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return user
|
|
||||||
}
|
}
|
||||||
|
|||||||
24
src/lib/session.ts
Executable file
24
src/lib/session.ts
Executable file
@ -0,0 +1,24 @@
|
|||||||
|
export const SESSION_COOKIE = "wos-session"
|
||||||
|
|
||||||
|
export function decodeJwtPayload(
|
||||||
|
token: string
|
||||||
|
): Record<string, unknown> | null {
|
||||||
|
try {
|
||||||
|
const parts = token.split(".")
|
||||||
|
if (parts.length !== 3) return null
|
||||||
|
const base64 = parts[1]
|
||||||
|
.replace(/-/g, "+")
|
||||||
|
.replace(/_/g, "/")
|
||||||
|
const padded =
|
||||||
|
base64 + "=".repeat((4 - (base64.length % 4)) % 4)
|
||||||
|
return JSON.parse(atob(padded))
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTokenExpired(token: string): boolean {
|
||||||
|
const payload = decodeJwtPayload(token)
|
||||||
|
if (!payload?.exp) return true
|
||||||
|
return (payload.exp as number) * 1000 < Date.now()
|
||||||
|
}
|
||||||
@ -1,22 +1,19 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server"
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server"
|
||||||
import { withAuth } from "@workos-inc/authkit-nextjs";
|
import { SESSION_COOKIE, isTokenExpired } from "@/lib/session"
|
||||||
|
|
||||||
const isWorkOSConfigured =
|
const isWorkOSConfigured =
|
||||||
process.env.WORKOS_API_KEY &&
|
process.env.WORKOS_API_KEY &&
|
||||||
process.env.WORKOS_CLIENT_ID &&
|
process.env.WORKOS_CLIENT_ID &&
|
||||||
process.env.WORKOS_COOKIE_PASSWORD &&
|
!process.env.WORKOS_API_KEY.includes("placeholder")
|
||||||
!process.env.WORKOS_API_KEY.includes("placeholder");
|
|
||||||
|
|
||||||
export default async function middleware(request: NextRequest) {
|
export default async function middleware(request: NextRequest) {
|
||||||
const { pathname } = request.nextUrl;
|
const { pathname } = request.nextUrl
|
||||||
|
|
||||||
// bypass auth in dev mode
|
|
||||||
if (!isWorkOSConfigured) {
|
if (!isWorkOSConfigured) {
|
||||||
return NextResponse.next();
|
return NextResponse.next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// public routes (no auth required)
|
|
||||||
const publicRoutes = [
|
const publicRoutes = [
|
||||||
"/login",
|
"/login",
|
||||||
"/signup",
|
"/signup",
|
||||||
@ -24,40 +21,37 @@ export default async function middleware(request: NextRequest) {
|
|||||||
"/verify-email",
|
"/verify-email",
|
||||||
"/invite",
|
"/invite",
|
||||||
"/api/auth",
|
"/api/auth",
|
||||||
];
|
"/callback",
|
||||||
|
]
|
||||||
|
|
||||||
if (publicRoutes.some((route) => pathname.startsWith(route))) {
|
if (
|
||||||
return NextResponse.next();
|
publicRoutes.some((route) => pathname.startsWith(route))
|
||||||
|
) {
|
||||||
|
return NextResponse.next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// check session for protected routes
|
const token = request.cookies.get(SESSION_COOKIE)?.value
|
||||||
try {
|
|
||||||
const session = await withAuth();
|
if (!token || isTokenExpired(token)) {
|
||||||
if (!session || !session.user) {
|
const loginUrl = new URL("/login", request.url)
|
||||||
const loginUrl = new URL("/login", request.url);
|
loginUrl.searchParams.set("from", pathname)
|
||||||
loginUrl.searchParams.set("from", pathname);
|
const response = NextResponse.redirect(loginUrl)
|
||||||
return NextResponse.redirect(loginUrl);
|
if (token) response.cookies.delete(SESSION_COOKIE)
|
||||||
}
|
return response
|
||||||
} catch {
|
|
||||||
const loginUrl = new URL("/login", request.url);
|
|
||||||
loginUrl.searchParams.set("from", pathname);
|
|
||||||
return NextResponse.redirect(loginUrl);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// add security headers
|
const response = NextResponse.next()
|
||||||
const response = NextResponse.next();
|
response.headers.set("X-Frame-Options", "DENY")
|
||||||
response.headers.set("X-Frame-Options", "DENY");
|
response.headers.set("X-Content-Type-Options", "nosniff")
|
||||||
response.headers.set("X-Content-Type-Options", "nosniff");
|
|
||||||
response.headers.set(
|
response.headers.set(
|
||||||
"Strict-Transport-Security",
|
"Strict-Transport-Security",
|
||||||
"max-age=31536000; includeSubDomains"
|
"max-age=31536000; includeSubDomains"
|
||||||
);
|
)
|
||||||
|
return response
|
||||||
return response;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: [
|
matcher: [
|
||||||
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
|
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
|
||||||
],
|
],
|
||||||
};
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user