fix(auth): ensure telegramId is a string for consistent handling

- Updated the signIn calls in both Auth and useAuth functions to convert telegramId to a string.
- Modified the JWT callback to store telegramId as a string in the token.
- Enhanced session handling to correctly assign telegramId from the token to the session user.
- Added type definitions for telegramId in next-auth to ensure proper type handling.
This commit is contained in:
vchikalkin 2025-09-10 17:47:03 +03:00
parent 4139aa918d
commit c9187816a1
4 changed files with 18 additions and 7 deletions

View File

@ -22,7 +22,7 @@ export default function Auth() {
signIn('telegram', {
callbackUrl: '/profile',
redirect: false,
telegramId: user?.id,
telegramId: user?.id?.toString(),
});
});
}

View File

@ -29,7 +29,7 @@ function useAuth() {
signIn('telegram', {
callbackUrl: '/profile',
redirect: false,
telegramId: initDataUser.id,
telegramId: initDataUser.id.toString(),
}).then(() => redirect('/profile'));
}
}, [initDataUser?.id, status]);

View File

@ -4,15 +4,15 @@ import CredentialsProvider from 'next-auth/providers/credentials';
export const authOptions: AuthOptions = {
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
if (user?.telegramId) {
token.telegramId = user.telegramId;
}
return token;
},
async session({ session, token }) {
if (token?.id && session?.user) {
session.user.telegramId = token.id as number;
if (token?.telegramId && session?.user) {
session.user.telegramId = token.telegramId as number;
}
return session;
@ -27,7 +27,12 @@ export const authOptions: AuthOptions = {
throw new Error('Invalid Telegram ID');
}
return { id: telegramId };
const parsedTelegramId = Number.parseInt(telegramId, 10);
if (Number.isNaN(parsedTelegramId)) {
throw new TypeError('Invalid Telegram ID format');
}
return { id: parsedTelegramId.toString(), telegramId: parsedTelegramId };
},
credentials: {
telegramId: { label: 'Telegram ID', type: 'text' },

View File

@ -12,3 +12,9 @@ declare module 'next-auth' {
telegramId?: null | number;
}
}
declare module 'next-auth/jwt' {
interface JWT {
telegramId?: number;
}
}