使用 SvelteKit、MongoDB 和 Auth0 构建全栈 Web 应用程序,同时确保安全的用户特定文档访问

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

我正在使用 SvelteKit、MongoDB 和 Auth0 开发我的第一个全栈 Web 应用程序。我需要有关实施安全身份验证和特定于用户的文档访问的指导。这是我的具体问题:

  1. Authentication:如何在我的 SvelteKit 应用程序中配置 Auth0 和设置身份验证?我想将数据库访问限制为经过身份验证的用户,并确保每个用户只能访问自己的文档。
  2. MongoDB 集成:在 MongoDB 中为每个经过身份验证的用户创建新文档的推荐方法是什么(如果尚不存在)?我想确保数据分离并限制对每个用户自己文档的访问。
  3. 代码组织:在我的项目中,我使用 lib、services、stores 和 config 等目录来构建我的代码。这是在 SvelteKit 应用程序中组织代码的推荐方法吗?您能否提供有关我如何有效使用这些目录以及它们的目的是什么的见解?

以下是代码片段,以备不时之需 -

<!-- +layout.svelte -->
<script>
    import "../app.css"

    import { onMount } from "svelte"
    import auth from "$lib/services/auth"
    import { isAuthenticated, user } from "$lib/stores/auth"

    let auth0Client

    onMount(async () => {
        auth0Client = await auth.createClient()
        isAuthenticated.set(await auth0Client.isAuthenticated())
        user.set(await auth0Client.getUser())

        if ($isAuthenticated) {
            console.log("Logged in:", $user.name)

            const res = await fetch("/api/user", {
                method: "GET"
            })
            const response = await res.json()
    
            if (response.status === 200) {
                console.log("API Functional", response)
            } else {
                console.error("API Failed", response)
            }
        } else {
            console.log("Not logged in:", $isAuthenticated)

            const res = await fetch("/api/user", {
                method: "GET"
            })
            const response = await res.json()
    
            if (response.status === 200) {
                console.log("API Functional", response)
            } else {
                console.error("API Failed", response)
            }
        }

    })

    function login() {
        auth.loginWithPopup(auth0Client)
            .then(() => {
                console.log("Logged in post button click")
            })
            .catch((err) => {
                console.error("Could not log in post button click", err)
            })
    }

    function logout() {
        auth.logout(auth0Client)
            .then(() => {
                isAuthenticated.set(false)
                user.set({})
            })
            .catch((err) => {
                console.error("Could not log out.", err)
            })
    }
</script>

<div class="w-10/12 mx-auto">
    <h1 class="text-3xl font-bold">Business Point International</h1>

    {#if $isAuthenticated}
        <button on:click={logout}>Logout</button>
        <h2>Hey {$user.name}!</h2>
        {#if $user.picture}
            <img src={$user.picture} alt={$user.name} />
        {/if}
        <!-- <h3>{$user.sub}</h3> -->
    {:else}
        <button on:click={login}>Login</button>
    {/if}
    <!-- <p>{JSON.stringify(data)}</p> -->
</div>

<slot />
// lib/stores/auth.js
import { writable } from 'svelte/store'

export const isAuthenticated = writable(false)
export const user = writable({})
export const popupOpen = writable(false)
export const error = writable()
// lib/services/auth.js
import { createAuth0Client } from '@auth0/auth0-spa-js'

import { user, isAuthenticated, popupOpen } from '$lib/stores/auth'
import config from '$lib/config/auth0'

async function createClient() {
    let auth0Client = await createAuth0Client({
        domain: config.domain,
        clientId: config.clientId
    })

    return auth0Client
}

async function loginWithPopup(client, options) {
    popupOpen.set(true)
    try {
        await client.loginWithPopup(options)

        user.set(await client.getUser())
        isAuthenticated.set(true)
    } catch (e) {
        console.error(e)
    } finally {
        popupOpen.set(false)
    }
}

function logout(client) {
    return client.logout()
}

const auth = {
    createClient,
    loginWithPopup,
    logout
}

export default auth
// lib/services/mongodb.js
import { MongoClient } from "mongodb"
import { MONGO_DB_URI } from "$env/static/private"

const client = new MongoClient(MONGO_DB_URI)

await client.connect()

export default client.db("bpi")
// lib/config/auth0.js
const config = {
    domain: "dev-******.us.auth0.com",
    clientId: "***"
}

export default config;

如果有任何建议、代码片段或推荐资源可以帮助我有效且安全地实施这些功能,我将不胜感激。谢谢!

mongodb authentication auth0 sveltekit database-security
© www.soinside.com 2019 - 2024. All rights reserved.