All files / lib auth.ts

0% Statements 0/26
0% Branches 0/18
0% Functions 0/3
0% Lines 0/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 type { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { MongooseAdapter } from "./auth-adapter";
import AuditLog from "@/models/AuditLog";
import { connectDB } from "./mongodb";
 
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
  throw new Error("Missing Google OAuth credentials");
}
 
if (!process.env.NEXTAUTH_SECRET) {
  throw new Error("Missing NEXTAUTH_SECRET");
}
 
export const authOptions: NextAuthOptions = {
  adapter: MongooseAdapter(),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code",
        },
      },
    }),
  ],
  session: {
    strategy: "database",
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  pages: {
    signIn: "/auth/signin",
    error: "/auth/error",
  },
  callbacks: {
    async session({ session, user }) {
      if (session.user) {
        session.user.id = user.id;
        session.user.role = (user as { role?: string }).role || "member";
      }
      return session;
    },
    async signIn({ user, account }) {
      // Log login event
      if (user && account) {
        try {
          await connectDB();
          await AuditLog.create({
            entityType: "session",
            entityId: user.id,
            action: "login",
            userId: user.id,
            payload: {
              provider: account.provider,
              timestamp: new Date().toISOString(),
            },
          });
        } catch (error) {
          console.error("Failed to create audit log:", error);
        }
      }
      return true;
    },
  },
  events: {
    async signOut({ session, token }) {
      // Log logout event
      try {
        await connectDB();
        const userId = session?.user?.id || token?.sub;
        if (userId) {
          await AuditLog.create({
            entityType: "session",
            entityId: userId,
            action: "logout",
            userId: userId,
            payload: {
              timestamp: new Date().toISOString(),
            },
          });
        }
      } catch (error) {
        console.error("Failed to create audit log:", error);
      }
    },
  },
  debug: process.env.NODE_ENV === "development",
};