lucia-auth / lucia

Authentication, simple and clean
https://lucia-auth.com
MIT License
8.35k stars 448 forks source link

oauth and nuxt tutortial (using mongodb) #1555

Closed slugb0t closed 2 months ago

slugb0t commented 2 months ago

I'm setting up a frontend to use Lucia for oauth authentication. I've followed the oauth tutortial as well as the instruction for using the lucia adapter to set up mongodb. I see in the callback I am successfully getting the user but in the client side when using useUser or useAuthenticatedUser, I am getting null everytime.

Could it be the server/utils/auth.ts file I created? I combined the oauth tutorial with the mongodb adapter instructions into the one file and typescript seems to be not happy with SessionDoc as well as User


import { MongodbAdapter } from "@lucia-auth/adapter-mongodb";
import { Collection, MongoClient } from "mongodb";
import { GitHub } from "arctic";

if (!process.env.MONGODB_URI) {
    throw new Error("Please add your Mongo URI to .env.local");
}

// import { webcrypto } from "crypto"; // polyfill for nodejs crypto | can be removed when on node v20

// @ts-expect-error
// globalThis.crypto = webcrypto;

const client = new MongoClient(process.env.MONGODB_URI!);
client.connect();

const db = client.db();
const User = db.collection("users") as Collection<UserDoc>;
const Session = db.collection("sessions") as Collection<SessionDoc>;

const adapter = new MongodbAdapter(Session, User);

export const lucia = new Lucia(adapter, {
    sessionCookie: {
        attributes: {
            secure: !import.meta.dev
        }
    },
    getUserAttributes: (attributes) => {
        return {
            username: attributes.username,
            githubId: attributes.github_id
        };
    }
});

declare module "lucia" {
    interface Register {
        Lucia: typeof lucia;
        DatabaseUserAttributes: Omit<DatabaseUser, "id">;
    }
}

interface DatabaseUser {
    id: string;
    username: string;
    github_id: number;
}

interface UserDoc {
    _id: string;
}

interface Session {
    _id: string;
    expires_at: Date;
    user_id: string;
}

export const github = new GitHub(process.env.GITHUB_CLIENT_ID!, process.env.GITHUB_CLIENT_SECRET!);```