【发布时间】:2022-10-01 12:52:34
【问题描述】:
我想做简单的受保护路线。
我有凭据提供程序和 nextAuth 中间件。我只想做简单的逻辑:
- 如果用户已登录,他可以访问 /profile,如果他访问 /signup 或 /signin,则将他重定向到 /profile,如果他未登录,则无法访问 /profile 并将他重定向到 /signin
- 有些路线是中立的——例如他可以在登录或未登录时访问/shop。
有我的 [...nextauth].ts
export default NextAuth({
session: {
strategy: \'jwt\',
},
providers: [
CredentialsProvider({
type: \'credentials\',
async authorize(credentails) {
const { password, email } = credentails as Signin
try {
const client = await connectToDatabase()
if (!client) return
const db = client.db()
const user = await existingUser(email, db)
if (!user) throw new Error(\'Invalid credentails!\')
const isPasswordCorrect = await verifyPassword(password, user.password)
if (!isPasswordCorrect) throw new Error(\'Invalid credentails!\')
return { email: user.email, name: user.name, id: user._id.toString() }
} catch (e: unknown) {
if (e instanceof Error) {
throw new Error(e.message)
}
}
},
}),
],
})
标签: reactjs authentication next.js routes next-auth