274 lines
8.4 KiB
TypeScript
274 lines
8.4 KiB
TypeScript
import NextAuth, { NextAuthOptions } from "next-auth";
|
|
import KeycloakProvider from "next-auth/providers/keycloak";
|
|
|
|
interface RocketChatLoginResponse {
|
|
status: string;
|
|
data: {
|
|
authToken: string;
|
|
userId: string;
|
|
};
|
|
}
|
|
|
|
declare module "next-auth" {
|
|
interface Session {
|
|
user: {
|
|
id: string;
|
|
name?: string | null;
|
|
email?: string | null;
|
|
image?: string | null;
|
|
username: string;
|
|
first_name: string;
|
|
last_name: string;
|
|
role: string[];
|
|
};
|
|
accessToken: string;
|
|
rocketChatToken: string;
|
|
rocketChatUserId: string;
|
|
}
|
|
|
|
interface JWT {
|
|
accessToken: string;
|
|
refreshToken: string;
|
|
accessTokenExpires: number;
|
|
role: string[];
|
|
username: string;
|
|
first_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;
|
|
}
|
|
}
|
|
|
|
export const authOptions: NextAuthOptions = {
|
|
providers: [
|
|
KeycloakProvider({
|
|
clientId: process.env.KEYCLOAK_CLIENT_ID!,
|
|
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
|
issuer: process.env.KEYCLOAK_ISSUER!,
|
|
profile(profile) {
|
|
// Filter out system roles and only keep valid user roles
|
|
const validRoles = (profile.groups || [])
|
|
.filter((role: string) =>
|
|
!role.startsWith('default-roles-') &&
|
|
!['offline_access', 'uma_authorization'].includes(role)
|
|
);
|
|
|
|
return {
|
|
id: profile.sub,
|
|
name: profile.name ?? profile.preferred_username,
|
|
email: profile.email,
|
|
first_name: profile.given_name ?? '',
|
|
last_name: profile.family_name ?? '',
|
|
username: profile.preferred_username ?? profile.email?.split('@')[0] ?? '',
|
|
role: validRoles,
|
|
}
|
|
},
|
|
}),
|
|
],
|
|
callbacks: {
|
|
async jwt({ token, account, profile }) {
|
|
console.log('JWT callback called with:', { token, account, profile });
|
|
|
|
// Initial sign in
|
|
if (account && profile) {
|
|
// Get user info from Rocket.Chat using the admin token
|
|
const userInfoResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.info?username=${token.username}`, {
|
|
headers: {
|
|
'X-Auth-Token': process.env.ROCKET_CHAT_ADMIN_TOKEN as string,
|
|
'X-User-Id': process.env.ROCKET_CHAT_ADMIN_USER_ID as string,
|
|
},
|
|
});
|
|
|
|
if (!userInfoResponse.ok) {
|
|
console.error('Failed to get user info:', {
|
|
status: userInfoResponse.status,
|
|
statusText: userInfoResponse.statusText,
|
|
username: token.username
|
|
});
|
|
return token;
|
|
}
|
|
|
|
const userInfo = await userInfoResponse.json();
|
|
console.log('User info response:', userInfo);
|
|
|
|
if (!userInfo.user || !userInfo.user._id) {
|
|
console.error('Invalid user info response:', userInfo);
|
|
return token;
|
|
}
|
|
|
|
// Set the user's Rocket.Chat ID
|
|
token.rocketChatUserId = userInfo.user._id;
|
|
console.log('Set Rocket.Chat user ID:', token.rocketChatUserId);
|
|
|
|
// Get personal access tokens for the user
|
|
const tokensResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.getPersonalAccessTokens`, {
|
|
headers: {
|
|
'X-Auth-Token': process.env.ROCKET_CHAT_ADMIN_TOKEN as string,
|
|
'X-User-Id': process.env.ROCKET_CHAT_ADMIN_USER_ID as string,
|
|
},
|
|
});
|
|
|
|
if (!tokensResponse.ok) {
|
|
console.error('Failed to get personal access tokens:', {
|
|
status: tokensResponse.status,
|
|
statusText: tokensResponse.statusText,
|
|
username: token.username
|
|
});
|
|
return token;
|
|
}
|
|
|
|
const tokensData = await tokensResponse.json();
|
|
console.log('Personal access tokens response:', tokensData);
|
|
|
|
// Find existing token or create a new one
|
|
let personalAccessToken = tokensData.tokens?.find((t: any) => t.name === 'NextAuth');
|
|
if (!personalAccessToken) {
|
|
console.log('No existing token found, creating new one');
|
|
const createTokenResponse = await fetch(`${process.env.ROCKET_CHAT_URL}/api/v1/users.generatePersonalAccessToken`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-Auth-Token': process.env.ROCKET_CHAT_ADMIN_TOKEN as string,
|
|
'X-User-Id': process.env.ROCKET_CHAT_ADMIN_USER_ID as string,
|
|
},
|
|
body: JSON.stringify({
|
|
tokenName: 'NextAuth',
|
|
bypassTwoFactor: true,
|
|
}),
|
|
});
|
|
|
|
if (!createTokenResponse.ok) {
|
|
console.error('Failed to create personal access token:', {
|
|
status: createTokenResponse.status,
|
|
statusText: createTokenResponse.statusText,
|
|
username: token.username
|
|
});
|
|
return token;
|
|
}
|
|
|
|
const createTokenData = await createTokenResponse.json();
|
|
console.log('Create token response:', createTokenData);
|
|
personalAccessToken = createTokenData.token;
|
|
}
|
|
|
|
// Set the personal access token
|
|
token.rocketChatToken = personalAccessToken.token;
|
|
console.log('Set Rocket.Chat token:', token.rocketChatToken);
|
|
|
|
return token;
|
|
}
|
|
|
|
// Return previous token if it has Rocket.Chat credentials
|
|
if (token.rocketChatToken && token.rocketChatUserId) {
|
|
return token;
|
|
}
|
|
|
|
// Token refresh case
|
|
if (Date.now() < (token.accessTokenExpires as number)) {
|
|
return token;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/token`,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
body: new URLSearchParams({
|
|
grant_type: "refresh_token",
|
|
client_id: process.env.KEYCLOAK_CLIENT_ID!,
|
|
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
|
refresh_token: token.refreshToken,
|
|
}),
|
|
}
|
|
);
|
|
|
|
const tokens = await response.json();
|
|
|
|
if (!response.ok) throw tokens;
|
|
|
|
return {
|
|
...token,
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token ?? token.refreshToken,
|
|
accessTokenExpires: Date.now() + tokens.expires_in * 1000,
|
|
};
|
|
} catch (error) {
|
|
console.error("Error refreshing token:", error);
|
|
return { ...token, error: "RefreshAccessTokenError" };
|
|
}
|
|
},
|
|
|
|
async session({ session, token }) {
|
|
if (token.error) {
|
|
throw new Error("RefreshAccessTokenError");
|
|
}
|
|
|
|
console.log('Session callback token:', {
|
|
hasRocketChatToken: !!token.rocketChatToken,
|
|
hasRocketChatUserId: !!token.rocketChatUserId,
|
|
token: token
|
|
});
|
|
|
|
return {
|
|
...session,
|
|
accessToken: token.accessToken,
|
|
rocketChatToken: token.rocketChatToken || '',
|
|
rocketChatUserId: token.rocketChatUserId || '',
|
|
user: {
|
|
...session.user,
|
|
id: token.sub as string,
|
|
first_name: token.first_name || '',
|
|
last_name: token.last_name || '',
|
|
username: token.username || '',
|
|
role: token.role || [],
|
|
},
|
|
};
|
|
},
|
|
},
|
|
events: {
|
|
async signOut({ token }) {
|
|
if (token.refreshToken) {
|
|
try {
|
|
await fetch(
|
|
`${process.env.KEYCLOAK_BASE_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/logout`,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
},
|
|
body: new URLSearchParams({
|
|
client_id: process.env.KEYCLOAK_CLIENT_ID!,
|
|
client_secret: process.env.KEYCLOAK_CLIENT_SECRET!,
|
|
refresh_token: token.refreshToken as string,
|
|
}),
|
|
}
|
|
);
|
|
} catch (error) {
|
|
console.error("Error during logout:", error);
|
|
}
|
|
}
|
|
},
|
|
},
|
|
};
|
|
|
|
const handler = NextAuth(authOptions);
|
|
export { handler as GET, handler as POST };
|
|
|