correction flow 5
This commit is contained in:
parent
d368e07e97
commit
71d3670a6f
@ -1,14 +1,6 @@
|
|||||||
import NextAuth, { NextAuthOptions } from "next-auth";
|
import NextAuth, { NextAuthOptions } from "next-auth";
|
||||||
import KeycloakProvider from "next-auth/providers/keycloak";
|
import KeycloakProvider from "next-auth/providers/keycloak";
|
||||||
|
|
||||||
interface RocketChatLoginResponse {
|
|
||||||
status: string;
|
|
||||||
data: {
|
|
||||||
authToken: string;
|
|
||||||
userId: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
declare module "next-auth" {
|
declare module "next-auth" {
|
||||||
interface Session {
|
interface Session {
|
||||||
user: {
|
user: {
|
||||||
@ -22,8 +14,6 @@ declare module "next-auth" {
|
|||||||
role: string[];
|
role: string[];
|
||||||
};
|
};
|
||||||
accessToken: string;
|
accessToken: string;
|
||||||
rocketChatToken: string;
|
|
||||||
rocketChatUserId: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface JWT {
|
interface JWT {
|
||||||
@ -34,22 +24,6 @@ declare module "next-auth" {
|
|||||||
username: string;
|
username: string;
|
||||||
first_name: string;
|
first_name: string;
|
||||||
last_name: string;
|
last_name: string;
|
||||||
rocketChatToken: string;
|
|
||||||
rocketChatUserId: string;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
declare module "next-auth/jwt" {
|
|
||||||
interface JWT {
|
|
||||||
accessToken: string;
|
|
||||||
refreshToken: string;
|
|
||||||
accessTokenExpires: number;
|
|
||||||
role: string[];
|
|
||||||
username: string;
|
|
||||||
first_name: string;
|
|
||||||
last_name: string;
|
|
||||||
rocketChatToken: string;
|
|
||||||
rocketChatUserId: string;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,72 +41,29 @@ export const authOptions: NextAuthOptions = {
|
|||||||
first_name: profile.given_name ?? '',
|
first_name: profile.given_name ?? '',
|
||||||
last_name: profile.family_name ?? '',
|
last_name: profile.family_name ?? '',
|
||||||
username: profile.preferred_username ?? profile.email?.split('@')[0] ?? '',
|
username: profile.preferred_username ?? profile.email?.split('@')[0] ?? '',
|
||||||
role: profile.groups || [],
|
role: profile.groups ?? [],
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
callbacks: {
|
callbacks: {
|
||||||
async jwt({ token, account, profile }) {
|
async jwt({ token, account, profile }) {
|
||||||
console.log('JWT callback called with:', { token, account, profile });
|
|
||||||
|
|
||||||
// Initial sign in
|
|
||||||
if (account && profile) {
|
if (account && profile) {
|
||||||
// Set user data from profile
|
token.accessToken = account.access_token;
|
||||||
token.username = profile.preferred_username || '';
|
token.refreshToken = account.refresh_token;
|
||||||
token.first_name = profile.given_name || '';
|
token.accessTokenExpires = account.expires_at! * 1000;
|
||||||
token.last_name = profile.family_name || '';
|
token.role = (profile as any).groups ?? [];
|
||||||
token.role = profile.groups || [];
|
token.username = (profile as any).preferred_username ?? profile.email?.split('@')[0] ?? '';
|
||||||
token.accessToken = account.access_token || '';
|
token.first_name = (profile as any).given_name ?? '';
|
||||||
token.refreshToken = account.refresh_token || '';
|
token.last_name = (profile as any).family_name ?? '';
|
||||||
token.accessTokenExpires = account.expires_at ? account.expires_at * 1000 : Date.now() + 60 * 60 * 1000;
|
return token;
|
||||||
|
|
||||||
// Create or update Leantime user
|
|
||||||
try {
|
|
||||||
const leantimeResponse = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'x-api-key': process.env.LEANTIME_API_KEY!,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
method: 'leantime.rpc.Users.Users.addUser',
|
|
||||||
jsonrpc: '2.0',
|
|
||||||
id: 1,
|
|
||||||
params: {
|
|
||||||
values: {
|
|
||||||
firstname: token.first_name,
|
|
||||||
lastname: token.last_name,
|
|
||||||
username: token.username,
|
|
||||||
email: profile.email,
|
|
||||||
role: token.role.includes('admin') ? 'admin' : 'user',
|
|
||||||
password: Math.random().toString(36).slice(-8), // Generate a random password
|
|
||||||
status: 'a', // Active status
|
|
||||||
source: 'keycloak',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const responseData = await leantimeResponse.json();
|
|
||||||
console.log('Leantime response:', responseData);
|
|
||||||
|
|
||||||
if (!leantimeResponse.ok || !responseData.result) {
|
|
||||||
console.error('Failed to create/update Leantime user:', responseData);
|
|
||||||
} else {
|
|
||||||
console.log('Successfully created/updated Leantime user with ID:', responseData.result);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error creating/updating Leantime user:', error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return previous token if it's not expired
|
// Return previous token if not expired
|
||||||
if (Date.now() < (token.accessTokenExpires as number)) {
|
if (Date.now() < (token.accessTokenExpires as number)) {
|
||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Token refresh case
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
|
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
|
||||||
@ -145,7 +76,7 @@ export const authOptions: NextAuthOptions = {
|
|||||||
grant_type: "refresh_token",
|
grant_type: "refresh_token",
|
||||||
client_id: process.env.KEYCLOAK_CLIENT_ID!,
|
client_id: process.env.KEYCLOAK_CLIENT_ID!,
|
||||||
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
||||||
refresh_token: token.refreshToken,
|
refresh_token: token.refreshToken as string,
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@ -171,25 +102,22 @@ export const authOptions: NextAuthOptions = {
|
|||||||
throw new Error("RefreshAccessTokenError");
|
throw new Error("RefreshAccessTokenError");
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
session.accessToken = token.accessToken;
|
||||||
...session,
|
session.user = {
|
||||||
accessToken: token.accessToken,
|
|
||||||
user: {
|
|
||||||
...session.user,
|
...session.user,
|
||||||
id: token.sub as string,
|
id: token.sub as string,
|
||||||
first_name: token.first_name || '',
|
first_name: token.first_name ?? '',
|
||||||
last_name: token.last_name || '',
|
last_name: token.last_name ?? '',
|
||||||
username: token.username || '',
|
username: token.username ?? '',
|
||||||
role: token.role || [],
|
role: token.role ?? [],
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
return session;
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
events: {
|
events: {
|
||||||
async signOut({ token }) {
|
async signOut({ token }) {
|
||||||
if (token.refreshToken) {
|
if (token.refreshToken) {
|
||||||
try {
|
try {
|
||||||
// Logout from Keycloak
|
|
||||||
await fetch(
|
await fetch(
|
||||||
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/logout`,
|
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/logout`,
|
||||||
{
|
{
|
||||||
@ -204,34 +132,6 @@ export const authOptions: NextAuthOptions = {
|
|||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Delete user from Leantime
|
|
||||||
if (token.username) {
|
|
||||||
const leantimeResponse = await fetch(`${process.env.LEANTIME_API_URL}/api/jsonrpc`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'x-api-key': process.env.LEANTIME_API_KEY!,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
method: 'leantime.rpc.Users.Users.deleteUser',
|
|
||||||
jsonrpc: '2.0',
|
|
||||||
id: 1,
|
|
||||||
params: {
|
|
||||||
id: token.username
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const responseData = await leantimeResponse.json();
|
|
||||||
console.log('Leantime delete response:', responseData);
|
|
||||||
|
|
||||||
if (!leantimeResponse.ok || !responseData.result) {
|
|
||||||
console.error('Failed to delete Leantime user:', responseData);
|
|
||||||
} else {
|
|
||||||
console.log('Successfully deleted Leantime user');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error during logout:", error);
|
console.error("Error during logout:", error);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user