- Updated the authentication logic in both Auth and useAuth functions to redirect unregistered users to the '/unregistered' page. - Enhanced error handling in the authOptions to check for user registration status using the Telegram ID. - Improved the matcher configuration in middleware to exclude the '/unregistered' route from authentication checks.
72 lines
2.1 KiB
TypeScript
72 lines
2.1 KiB
TypeScript
import { getClientWithToken } from '@repo/graphql/apollo/client';
|
|
import * as GQL from '@repo/graphql/types';
|
|
import { type AuthOptions } from 'next-auth';
|
|
import CredentialsProvider from 'next-auth/providers/credentials';
|
|
|
|
export const authOptions: AuthOptions = {
|
|
callbacks: {
|
|
async jwt({ token, user }) {
|
|
if (user?.telegramId) {
|
|
token.telegramId = user.telegramId;
|
|
}
|
|
|
|
return token;
|
|
},
|
|
async session({ session, token }) {
|
|
if (token?.telegramId && session?.user) {
|
|
session.user.telegramId = token.telegramId as number;
|
|
}
|
|
|
|
return session;
|
|
},
|
|
},
|
|
providers: [
|
|
CredentialsProvider({
|
|
async authorize(credentials) {
|
|
const { telegramId } = credentials ?? {};
|
|
|
|
if (!telegramId) {
|
|
throw new Error('Invalid Telegram ID');
|
|
}
|
|
|
|
const parsedTelegramId = Number.parseInt(telegramId, 10);
|
|
if (Number.isNaN(parsedTelegramId)) {
|
|
throw new TypeError('Invalid Telegram ID format');
|
|
}
|
|
|
|
try {
|
|
// Проверяем, зарегистрирован ли пользователь
|
|
const { query } = await getClientWithToken();
|
|
const result = await query({
|
|
query: GQL.GetCustomerDocument,
|
|
variables: { telegramId: parsedTelegramId },
|
|
});
|
|
|
|
const customer = result.data.customers.at(0);
|
|
|
|
if (!customer) {
|
|
// Пользователь не зарегистрирован - перенаправляем на страницу регистрации
|
|
throw new Error('UNREGISTERED');
|
|
}
|
|
|
|
return { id: parsedTelegramId.toString(), telegramId: parsedTelegramId };
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message.includes('UNREGISTERED')) {
|
|
throw error;
|
|
}
|
|
|
|
throw new Error('Authentication failed');
|
|
}
|
|
},
|
|
credentials: {
|
|
telegramId: { label: 'Telegram ID', type: 'text' },
|
|
},
|
|
id: 'telegram',
|
|
name: 'Telegram',
|
|
}),
|
|
],
|
|
session: {
|
|
strategy: 'jwt',
|
|
},
|
|
};
|