aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/server/auth.ts
blob: 1feeec28960bc8039f4fed28a4ba45a1f055ebcf (plain) (blame)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { Adapter, AdapterUser } from "@auth/core/adapters";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { count, eq } from "drizzle-orm";
import NextAuth, {
  DefaultSession,
  getServerSession,
  NextAuthOptions,
} from "next-auth";
import { Adapter as NextAuthAdapater } from "next-auth/adapters";
import CredentialsProvider from "next-auth/providers/credentials";
import { Provider } from "next-auth/providers/index";

import { db } from "@karakeep/db";
import {
  accounts,
  sessions,
  users,
  verificationTokens,
} from "@karakeep/db/schema";
import serverConfig from "@karakeep/shared/config";
import { validatePassword } from "@karakeep/trpc/auth";
import { createUserRaw } from "@karakeep/trpc/routers/users";

type UserRole = "admin" | "user";

declare module "next-auth/jwt" {
  export interface JWT {
    user: {
      id: string;
      role: UserRole;
    } & DefaultSession["user"];
  }
}

declare module "next-auth" {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  export interface Session {
    user: {
      id: string;
      role: UserRole;
    } & DefaultSession["user"];
  }

  export interface DefaultUser {
    role: UserRole | null;
  }
}

/**
 * Returns true if the user table is empty, which indicates that this user is going to be
 * the first one. This can be racy if multiple users are created at the same time, but
 * that should be fine.
 */
async function isFirstUser(): Promise<boolean> {
  const [{ count: userCount }] = await db
    .select({ count: count() })
    .from(users);
  return userCount == 0;
}

/**
 * Returns true if the user is an admin
 */
async function isAdmin(email: string): Promise<boolean> {
  const res = await db.query.users.findFirst({
    columns: { role: true },
    where: eq(users.email, email),
  });
  return res?.role == "admin";
}

const CustomProvider = (): Adapter => {
  const adapter = DrizzleAdapter(db, {
    usersTable: users,
    accountsTable: accounts,
    sessionsTable: sessions,
    verificationTokensTable: verificationTokens,
  });

  return {
    ...adapter,
    createUser: async (user: Omit<AdapterUser, "id">) => {
      return await createUserRaw(db, {
        name: user.name ?? "",
        email: user.email,
        emailVerified: user.emailVerified,
      });
    },
  };
};

const providers: Provider[] = [
  CredentialsProvider({
    // The name to display on the sign in form (e.g. "Sign in with...")
    name: "Credentials",
    credentials: {
      email: { label: "Email", type: "email", placeholder: "Email" },
      password: { label: "Password", type: "password" },
    },
    async authorize(credentials) {
      if (!credentials) {
        return null;
      }

      try {
        return await validatePassword(
          credentials?.email,
          credentials?.password,
          db,
        );
      } catch {
        return null;
      }
    },
  }),
];

const oauth = serverConfig.auth.oauth;
if (oauth.wellKnownUrl) {
  providers.push({
    id: "custom",
    name: oauth.name,
    type: "oauth",
    wellKnown: oauth.wellKnownUrl,
    authorization: { params: { scope: oauth.scope } },
    clientId: oauth.clientId,
    clientSecret: oauth.clientSecret,
    allowDangerousEmailAccountLinking: oauth.allowDangerousEmailAccountLinking,
    idToken: true,
    checks: ["pkce", "state"],
    httpOptions: {
      timeout: oauth.timeout,
    },
    async profile(profile: Record<string, string>) {
      const [admin, firstUser] = await Promise.all([
        isAdmin(profile.email),
        isFirstUser(),
      ]);
      return {
        id: profile.sub,
        name: profile.name || profile.email,
        email: profile.email,
        image: profile.picture,
        role: admin || firstUser ? "admin" : "user",
      };
    },
  });
}

export const authOptions: NextAuthOptions = {
  // https://github.com/nextauthjs/next-auth/issues/9493
  adapter: CustomProvider() as NextAuthAdapater,
  providers: providers,
  session: {
    strategy: "jwt",
  },
  pages: {
    signIn: "/signin",
    signOut: "/signin",
    error: "/signin",
    newUser: "/signin",
  },
  callbacks: {
    async signIn({ user: credUser, credentials, profile }) {
      const email = credUser.email || profile?.email;
      if (!email) {
        throw new Error("Provider didn't provide an email during signin");
      }
      const user = await db.query.users.findFirst({
        columns: { emailVerified: true },
        where: eq(users.email, email),
      });

      if (credentials) {
        if (!user) {
          throw new Error("Invalid credentials");
        }
        if (
          serverConfig.auth.emailVerificationRequired &&
          !user.emailVerified
        ) {
          throw new Error("Please verify your email address before signing in");
        }
        return true;
      }

      // If it's a new user and signups are disabled, fail the sign in
      if (!user && serverConfig.auth.disableSignups) {
        throw new Error("Signups are disabled in server config");
      }

      // TODO: We're blindly trusting oauth providers to validate emails
      // As such, oauth users can sign in even if email verification is enabled.
      // We might want to change this in the future.

      return true;
    },
    async jwt({ token, user }) {
      if (user) {
        token.user = {
          id: user.id,
          name: user.name,
          email: user.email,
          image: user.image,
          role: user.role ?? "user",
        };
      }
      return token;
    },
    async session({ session, token }) {
      session.user = { ...token.user };
      return session;
    },
  },
};

export const authHandler = NextAuth(authOptions);

export const getServerAuthSession = () => getServerSession(authOptions);