auth.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import NextAuth, { NextAuthOptions } from "next-auth";
  2. import CredentialsProvider from "next-auth/providers/credentials";
  3. import { bagistoFetch, /*restApiFetch*/} from "@/utils/bagisto";
  4. import { CUSTOMER_LOGIN } from "@/graphql/customer/mutations";
  5. export const authOptions: NextAuthOptions = {
  6. session: {
  7. strategy: "jwt",
  8. maxAge: 30 * 24 * 60 * 60,
  9. },
  10. providers: [
  11. // https://next-auth.js.org/configuration/providers/credentials
  12. CredentialsProvider({
  13. name: "Credentials",
  14. credentials: {
  15. username: { label: "Email", type: "text" },
  16. password: { label: "Password", type: "password" },
  17. },
  18. authorize: async (credentials): Promise<any> => {
  19. if (!credentials?.username || !credentials?.password) {
  20. throw new Error("Email and password are required.");
  21. }
  22. const input = {
  23. email: credentials.username,
  24. password: credentials.password,
  25. };
  26. const res = await bagistoFetch<any>({
  27. query: CUSTOMER_LOGIN,
  28. variables: { input },
  29. cache: "no-store",
  30. });
  31. const data = res?.body?.data?.createCustomerLogin?.customerLogin;
  32. /* 使用rest api
  33. const res = await restApiFetch<any>({
  34. api: "/customer/login",
  35. variables: { ...input },
  36. cache: "no-store",
  37. });
  38. const data = res?.body;
  39. */
  40. if (!data || !data.success || !data.token) {
  41. throw new Error(data?.message || "Invalid credentials.");
  42. }
  43. return {
  44. id: data.id, // required by NextAuth
  45. email: credentials.username,
  46. name: credentials.username, // Using email as name since firstName/lastName are missing in response
  47. apiToken: data.apiToken,
  48. accessToken: data.token, // Sanctum token
  49. role: "customer",
  50. };
  51. },
  52. }),
  53. ],
  54. //https://next-auth.js.org/configuration/callbacks
  55. callbacks: {
  56. async jwt({ token, user }) {
  57. if (user) {
  58. token.id = user.id;
  59. token.apiToken = user.apiToken;
  60. token.accessToken = user.accessToken;
  61. token.role = "customer";
  62. }
  63. return token;
  64. },
  65. async session({ session, token }) {
  66. session.user = {
  67. ...session.user,
  68. id: token.id || "",
  69. apiToken: token.apiToken,
  70. accessToken: token.accessToken,
  71. role: token.role,
  72. };
  73. return session;
  74. },
  75. },
  76. pages: {
  77. signIn: "/customer/login",
  78. error: "/login",
  79. },
  80. secret: process.env.NEXTAUTH_SECRET,
  81. };
  82. export const handler = NextAuth(authOptions);