92 lines
2.7 KiB
TypeScript
92 lines
2.7 KiB
TypeScript
import type { NextAuthOptions } from 'next-auth'
|
||
import { NextRequest } from 'next/server'
|
||
import Steam from 'next-auth-steam'
|
||
import { prisma } from '@/app/lib/prisma'
|
||
import type { SteamProfile } from '@/app/types/steam'
|
||
|
||
export const authOptions = (req: NextRequest): NextAuthOptions => ({
|
||
secret: process.env.NEXTAUTH_SECRET,
|
||
providers: [
|
||
Steam(req, {
|
||
clientSecret: process.env.STEAM_API_KEY!,
|
||
}),
|
||
],
|
||
callbacks: {
|
||
async jwt({ token, account, profile }) {
|
||
if (account && profile) {
|
||
const steamProfile = profile as SteamProfile
|
||
const location = steamProfile.loccountrycode ?? null
|
||
|
||
await prisma.user.upsert({
|
||
where: { steamId: steamProfile.steamid },
|
||
update: {
|
||
name: steamProfile.personaname,
|
||
avatar: steamProfile.avatarfull,
|
||
...(location && { location }),
|
||
},
|
||
create: {
|
||
steamId: steamProfile.steamid,
|
||
name: steamProfile.personaname,
|
||
avatar: steamProfile.avatarfull,
|
||
location: steamProfile.loccountrycode,
|
||
isAdmin: false,
|
||
...(location && { location }),
|
||
},
|
||
})
|
||
|
||
token.steamId = steamProfile.steamid
|
||
token.name = steamProfile.personaname
|
||
token.image = steamProfile.avatarfull
|
||
}
|
||
|
||
const userInDb = await prisma.user.findUnique({
|
||
where: { steamId: token.steamId || token.sub || '' },
|
||
})
|
||
|
||
if (userInDb) {
|
||
token.team = userInDb.teamId ?? null
|
||
if (userInDb.steamId === '76561198000414190') {
|
||
token.isAdmin = true
|
||
} else {
|
||
token.isAdmin = userInDb.isAdmin ?? false
|
||
}
|
||
}
|
||
|
||
return token
|
||
},
|
||
|
||
async session({ session, token }) {
|
||
if (!token.steamId) throw new Error('steamId is missing in token')
|
||
|
||
session.user = {
|
||
...session.user,
|
||
steamId: token.steamId,
|
||
name: token.name,
|
||
image: token.image,
|
||
team: token.team ?? null,
|
||
isAdmin: token.isAdmin ?? false,
|
||
}
|
||
return session
|
||
},
|
||
|
||
redirect({ url, baseUrl }) {
|
||
const isSignIn = url.startsWith(`${baseUrl}/api/auth/signin`);
|
||
const isSignOut = url.startsWith(`${baseUrl}/api/auth/signout`);
|
||
|
||
if (isSignOut) {
|
||
return `${baseUrl}/`; // Nach Logout auf Startseite
|
||
}
|
||
|
||
// Standard-Redirect nach Login
|
||
if (isSignIn || url === baseUrl) {
|
||
return `${baseUrl}/dashboard`; // z. B. Dashboard als Startpunkt
|
||
}
|
||
|
||
return url.startsWith(baseUrl) ? url : baseUrl;
|
||
}
|
||
},
|
||
})
|
||
|
||
// ➕ Base config für `getServerSession()` ohne req
|
||
export const baseAuthOptions: NextAuthOptions = authOptions({} as NextRequest)
|