使用 lucia-auth 和 mongoDB 实现登录功能很困难

问题描述 投票:0回答:1

我刚刚开始学习凭证认证,根据我的研究,很多人推荐 lucia-auth 进行凭证认证。我正在遵循他们文档中的每一步,但我的代码中仍然出现错误。我附上了标记为错误的代码行的屏幕截图

我的架构 //模型.ts

import { MongodbAdapter } from "@lucia-auth/adapter-mongodb";
import mongoose from "mongoose";

const Schema = mongoose.Schema;

const userSchema = new Schema(
        {
            _id: {
                type: String,
                required: true
            },
            
                username: {
                    type: String
                }
            ,
            password: {
                type: String
            }
        } as const,
        { _id: false },
    )


const sessionSchema = new Schema(
        {
            _id: {
                type: String,
                required: true
            },
            user_id: {
                type: String,
                required: true
            },
            expires_at: {
                type: Date,
                required: true
            }
        } as const,
        { _id: false }
    )


    
    export const User = mongoose.models.User ?? mongoose.model("User", userSchema);
    
    export const Session =
      mongoose.models.Session ?? mongoose.model("Session", sessionSchema);


我的登录功能//route.ts

import Link from "next/link";

import { Argon2id } from "oslo/password";
import { cookies } from "next/headers";

import { redirect } from "next/navigation";


import { lucia } from "@/app/auth/lucia";
import { ActionResult } from "@/app/lib/form";
import { User } from "@/app/lib/models";



async function login(_: any, formData: FormData): Promise<ActionResult> {
    "use server";
    const username = formData.get("username");
    if (
        typeof username !== "string" ||
        username.length < 3 ||
        username.length > 31 ||
        !/^[a-z0-9_-]+$/.test(username)
    ) {
        return {
            error: "Invalid username"
        };
    }
    const password = formData.get("password");
    if (typeof password !== "string" || password.length < 6 || password.length > 255) {
        return {
            error: "Invalid password"
        };
    }

    const existingUser = User.find({username})
    if (!existingUser) {
        return {
            error: "Incorrect username or password"
        };
    }

    const validPassword = await new Argon2id().verify(existingUser.password, password);
    if (!validPassword) {
        return {
            error: "Incorrect username or password"
        };
    }

    const session = await lucia.createSession(existingUser.id, {});
    const sessionCookie = lucia.createSessionCookie(session.id);
    cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
    return redirect("/");
}

lucia 初始化 //lucia.ts

import { Lucia } from "lucia";
import { cookies } from "next/headers";
import { cache } from "react";

import type { DatabaseUser, Session, User } from "lucia";
import { MongodbAdapter } from "@lucia-auth/adapter-mongodb";
import mongoose from "mongoose";


const adapter = new MongodbAdapter(
    mongoose.connection.collection("sessions"),
    mongoose.connection.collection("users")
);

export const lucia = new Lucia(adapter, {
    sessionCookie: {
        attributes: {
            secure: process.env.NODE_ENV === "production"
        }
    },
    getUserAttributes: (attributes) => {
        return {
            username: attributes.username
        };
    }
});

export const validateRequest = cache(
    async (): Promise<{ user: User; session: Session } | { user: null; session: null }> => {
        const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null;
        if (!sessionId) {
            return {
                user: null,
                session: null
            };
        }

        const result = await lucia.validateSession(sessionId);
        // next.js throws when you attempt to set cookie when rendering page
        try {
            if (result.session && result.session.fresh) {
                const sessionCookie = lucia.createSessionCookie(result.session.id);
                cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
            }
            if (!result.session) {
                const sessionCookie = lucia.createBlankSessionCookie();
                cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
            }
        } catch {}
        return result;
    }
);

declare module "lucia" {
    interface Register {
        Lucia: typeof lucia;
        DatabaseUserAttributes: {
            username: string
        };
    }
}

这是我收到的错误的屏幕截图:

“查询”类型中不存在属性“密码”。 screenshot of lines of code with the errors 有人可以帮我解释一下吗,这样我就可以理解它以供将来参考。

mongodb authentication next.js
1个回答
0
投票

你的代码看起来不错,他们有一个你可以加入的不和谐服务器。将您的问题的链接粘贴到那里,希望您会看到有人知道您的代码有什么问题

© www.soinside.com 2019 - 2024. All rights reserved.