feat: add nextauth config
This commit is contained in:
parent
ae7f66aa78
commit
44c19d2813
12
auth.d.ts
vendored
Normal file
12
auth.d.ts
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
import { DefaultSession } from "next-auth";
|
||||
|
||||
declare module "next-auth" {
|
||||
export interface User extends Partial<DefaultSession<User>> {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
user: User;
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
import NextAuth, { User } from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import axios, { AxiosError } from "axios";
|
||||
import axios from "axios";
|
||||
import { jwtDecode } from "jwt-decode";
|
||||
|
||||
const handler = NextAuth({
|
||||
@ -11,37 +11,58 @@ const handler = NextAuth({
|
||||
password: {},
|
||||
},
|
||||
async authorize(credentials) {
|
||||
let user: User | null = null;
|
||||
|
||||
const response = axios({
|
||||
method: 'post',
|
||||
url: 'private-docs-api.intside.co/users/login/',
|
||||
data: {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
'private-docs-api.intside.co/users/login/',
|
||||
{
|
||||
email: credentials?.email,
|
||||
password: credentials?.password,
|
||||
}
|
||||
})
|
||||
.then(function (response: any) {
|
||||
const { user_id } = jwtDecode(response.access_token) as {
|
||||
user_id: string;
|
||||
};
|
||||
)
|
||||
|
||||
const { access_token, refresh_token } = response.data;
|
||||
const { id } = jwtDecode(access_token) as { id: string };
|
||||
|
||||
|
||||
})
|
||||
.catch(function (error) {
|
||||
if (error instanceof AxiosError) {
|
||||
if (error.status === 401) {
|
||||
return {
|
||||
id: id,
|
||||
email: credentials?.email,
|
||||
access_token: access_token,
|
||||
refresh_token: refresh_token
|
||||
} as User;
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error)) {
|
||||
if (error.response?.status === 401) {
|
||||
throw new Error("Email ou mot de passe incorrect");
|
||||
} else {
|
||||
throw new Error(error.message, error);
|
||||
}
|
||||
throw new Error(error.response?.data?.message || error.message);
|
||||
}
|
||||
throw new Error("Une erreur est survenue");
|
||||
});
|
||||
}
|
||||
},
|
||||
})
|
||||
]
|
||||
],
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
if (user) {
|
||||
token.access_token = user.access_token;
|
||||
token.refresh_token = user.refresh_token;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
return {
|
||||
...session,
|
||||
user: {
|
||||
...session.user,
|
||||
...token,
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
secret: process.env.AUTH_SECRET ?? "",
|
||||
});
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user