FPSMS-frontend
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.
 
 
 

65 lines
1.8 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 SessionWithTokens extends Session {
  5. accessToken: string | null;
  6. refreshToken?: string;
  7. abilities: string[];
  8. id?: string | null
  9. }
  10. export const authOptions: AuthOptions = {
  11. debug: process.env.NODE_ENV === "development",
  12. providers: [
  13. CredentialsProvider({
  14. id: "credentials",
  15. name: "Credentials",
  16. credentials: {
  17. username: { label: "Username", type: "text" },
  18. password: { label: "Password", type: "password" },
  19. },
  20. async authorize(credentials, req) {
  21. const res = await fetch(LOGIN_API_PATH, {
  22. method: "POST",
  23. body: JSON.stringify(credentials),
  24. headers: { "Content-Type": "application/json" },
  25. });
  26. const user = await res.json();
  27. if (res.ok && user) {
  28. return user;
  29. }
  30. return null;
  31. },
  32. }),
  33. ],
  34. pages: {
  35. signIn: "/login",
  36. },
  37. callbacks: {
  38. jwt(params) {
  39. // Add the data from user to the token
  40. const { token, user } = params;
  41. const newToken = { ...token, ...user };
  42. return newToken;
  43. },
  44. session({ session, token }) {
  45. const sessionWithToken: SessionWithTokens = {
  46. ...session,
  47. // Add the data from the token to the session
  48. id: token.id as string | undefined,
  49. accessToken: token.accessToken as string | null,
  50. refreshToken: token.refreshToken as string | undefined,
  51. abilities: token.abilities as string[]
  52. };
  53. if (sessionWithToken.user) {
  54. sessionWithToken.user.abilities = token.abilities as string[];
  55. }
  56. return sessionWithToken;
  57. },
  58. },
  59. };