Я использую только один CredentialsProvider в следующей аутентификации, но я не понимаю, как обращаться с async authorize() с помощью пользовательского интерфейса.
Я определил пользовательский интерфейс в types/next-auth.d.ts следующим образом:
import NextAuth from "next-auth"
declare module "next-auth" {
interface User {
id: string
address: string
name?: string
}
}
Это определение провайдера в [...nextauth].ts:
CredentialsProvider({
name: "Ethereum",
credentials: {
message: {
label: "Message",
type: "text",
},
signature: {
label: "Signature",
type: "text",
},
},
async authorize(credentials) {
try {
const nextAuthUrl = process.env.NEXTAUTH_URL
if (!nextAuthUrl) return null
if (!credentials) return null
// [verify the credential here]
// "message" contains the verified information
let user = await prisma.user.findUnique({
where: {
address: message.address,
},
})
if (!user) {
user = await prisma.user.create({
data: {
address: message.address,
},
})
}
return {
id: user.id,
address: user.address,
name: user.name
}
} catch (e) {
console.error(e)
return null
}
},
})
Теперь я вижу ошибку машинописного текста в async authorize(credentials)
Type '(credentials: Record<"message" | "signature", string> | undefined) => Promise<{ id: string; address: string; name: string | null; } | null>' is not assignable to type '(credentials: Record<"message" | "signature", string> | undefined, req: Pick<RequestInternal, "body" | "query" | "headers" | "method">) => Awaitable<...>'.
Type 'Promise<{ id: string; address: string; name: string | null; } | null>' is not assignable to type 'Awaitable<User | null>'.
Type 'Promise<{ id: string; address: string; name: string | null; } | null>' is not assignable to type 'PromiseLike<User | null>'.
Types of property 'then' are incompatible.
Type '<TResult1 = { id: string; address: string; name: string | null; } | null, TResult2 = never>(onfulfilled?: ((value: { id: string; address: string; name: string | null; } | null) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | ... 1 more ... | unde...' is not assignable to type '<TResult1 = User | null, TResult2 = never>(onfulfilled?: ((value: User | null) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => PromiseLike<...>'.
Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
Types of parameters 'value' and 'value' are incompatible.
Type '{ id: string; address: string; name: string | null; } | null' is not assignable to type 'User | null'.
Type '{ id: string; address: string; name: string | null; }' is not assignable to type 'User'.
Types of property 'name' are incompatible.
Type 'string | null' is not assignable to type 'string | undefined'.
Type 'null' is not assignable to type 'string | undefined'.






Как указано на GitHub Ошибка TypeScript для поставщика учетных данных # 2701 текущее исправление этой проблемы заключается в том, чтобы установить для параметра strict значение false ("strict": false) в файле tsconfig.json. Причина этого в том, что NextAuth.js был разработан с использованием "strict": false, но в настоящее время они работают над тем, чтобы он стал совместимым со строгим значением true.
Получил ту же проблему. Поскольку я не хотел включать строгий режим в .tsconfig, я просто пошел с разбором возвращаемого объекта authorize() на любой...
async authorize(credentials) {
// ...
return {
// ...
} as any. // <-- This here
}
Мне это не нравится, но я думаю, что это лучше, чем выключение строгого режима.
Кроме того, это не нарушает безопасность типов в последующем, поскольку следующий шаг с использованием возвращаемого типа будет в обратном вызове jwt({user}), и типизация по-прежнему работает там просто отлично.