You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

78 line
2.0 KiB

  1. import { AuthOptions, Session } from "next-auth";
  2. import CredentialsProvider from "next-auth/providers/credentials";
  3. import { LOGIN_API_PATH } from "./api";
  4. export interface SessionStaff {
  5. id: number;
  6. teamId: number;
  7. isTeamLead: boolean;
  8. employType: string | null;
  9. }
  10. export interface SessionWithTokens extends Session {
  11. staff?: SessionStaff;
  12. role?: string;
  13. abilities?: string[];
  14. accessToken?: string;
  15. refreshToken?: string;
  16. isTeamLead?: boolean;
  17. }
  18. export interface ability {
  19. actionSubjectCombo: string;
  20. }
  21. export const authOptions: AuthOptions = {
  22. debug: process.env.NODE_ENV === "development",
  23. providers: [
  24. CredentialsProvider({
  25. id: "credentials",
  26. name: "Credentials",
  27. credentials: {
  28. username: { label: "Username", type: "text" },
  29. password: { label: "Password", type: "password" },
  30. },
  31. async authorize(credentials, req) {
  32. const res = await fetch(LOGIN_API_PATH, {
  33. method: "POST",
  34. body: JSON.stringify(credentials),
  35. headers: { "Content-Type": "application/json" },
  36. });
  37. const user = await res.json();
  38. if (res.ok && user) {
  39. return user;
  40. }
  41. return null;
  42. },
  43. }),
  44. ],
  45. pages: {
  46. signIn: "/login",
  47. },
  48. callbacks: {
  49. jwt(params) {
  50. // Add the data from user to the token
  51. const { token, user } = params;
  52. const newToken = { ...token, ...user };
  53. return newToken;
  54. },
  55. session({ session, token }) {
  56. const sessionWithToken: SessionWithTokens = {
  57. ...session,
  58. role: token.role as string,
  59. // Add the data from the token to the session
  60. abilities: (token.abilities as ability[]).map(
  61. (item: ability) => item.actionSubjectCombo,
  62. ) as string[],
  63. accessToken: token.accessToken as string | undefined,
  64. refreshToken: token.refreshToken as string | undefined,
  65. staff: token.staff as SessionStaff,
  66. };
  67. // console.log(sessionWithToken)
  68. return sessionWithToken;
  69. },
  70. },
  71. };