109 lines
2.7 KiB
TypeScript

import { logout } from "@/queries/authentication";
import type { NextAuthOptions } from "next-auth";
import type { JWT } from "next-auth/jwt";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: NextAuthOptions = {
pages: {
signIn: "/auth/signin",
},
session: {
strategy: "jwt",
maxAge: 30 * 60, // 30 mins
},
events: {
signOut({ token }) {
const apitoken = token.apiToken;
console.log("apitoken", apitoken);
logout({ token: apitoken as string });
},
},
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
const { email, password } = credentials as {
email: string;
password: string;
};
console.log("email and password", email, password);
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/auth/login/`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: email,
password: password,
}),
},
);
console.log("status", res.status);
const data = await res.json();
console.log({ data });
switch (res.status) {
case 200:
return { ...data.user, apiToken: data.token, expiry: data.expiry };
case 400:
throw new Error(
JSON.stringify({ message: data.message, status: res.status }),
);
case 429:
throw new Error(
JSON.stringify({ message: data.message, status: res.status }),
);
case 403:
throw new Error(
JSON.stringify({ message: data.error, status: res.status }),
);
default:
throw new Error(
JSON.stringify({
message: "FATAL: Unexprted Error occured!",
status: res.status,
}),
);
}
},
}),
],
callbacks: {
redirect: async ({ url, baseUrl }) => {
// Allows relative callback URLs
if (url.startsWith("/")) return `${baseUrl}${url}`;
return baseUrl;
},
session: async ({ session, token }) => {
const sanitizedToken = Object.keys(token).reduce((p, c) => {
// strip unnecessary properties
if (c !== "iat" && c !== "exp" && c !== "jti" && c !== "apiToken") {
Object.assign(p, { [c]: token[c] });
}
return p;
}, {});
// session.expires = token.expiry
return {
...session,
user: sanitizedToken,
apiToken: token.apiToken,
// expires: token.expiry,
};
},
jwt: ({ token, user }) => {
if (typeof user !== "undefined") {
// user has just signed in so the user object is populated
return user as unknown as JWT;
}
return token;
},
},
secret: process.env.NEXTAUTH_SECRET,
};