Skip to content

Commit

Permalink
use supabase auth
Browse files Browse the repository at this point in the history
  • Loading branch information
gusibi committed Sep 30, 2024
1 parent 7148375 commit dca684a
Show file tree
Hide file tree
Showing 11 changed files with 372 additions and 1,584 deletions.
15 changes: 14 additions & 1 deletion app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@
</NuxtLayout>
</div>
</template>
<script setup lang="ts">
<script setup>
import { onMounted } from 'vue'
import { useSupabaseClient, useSupabaseUser } from '#imports'
const supabase = useSupabaseClient()
const user = useSupabaseUser()
onMounted(async () => {
console.log('Supabase client:', supabase)
console.log('Initial user state:', user.value)
const { data, error } = await supabase.auth.getSession()
console.log('Session data:', data)
console.log('Session error:', error)
})
</script>
55 changes: 55 additions & 0 deletions components/CommentBox.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<template>
<div class="mb-6">
<div v-if="user" class="flex items-start space-x-4">
<img :src="user.user_metadata.avatar_url" :alt="user.user_metadata.full_name" class="w-10 h-10 rounded-full">
<div class="flex-grow">
<p class="font-semibold text-gray-700 dark:text-gray-300">{{ user.user_metadata.full_name }}</p>
<textarea v-model="commentText" class="w-full mt-2 p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent" rows="3" placeholder="Write your comment here..."></textarea>
<button @click="submitComment" class="mt-2 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition duration-300"> Submit Comment </button>
</div>
</div>
<div v-else class="relative">
<div class="p-4 bg-gray-100 dark:bg-gray-800 rounded-md">
<p class="text-gray-500 dark:text-gray-400">Login to comment</p>
</div>
<button @click="login" class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition duration-300"> Login with GitHub to Comment </button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useSupabaseUser, useSupabaseClient } from '#imports'
import { useRoute } from 'vue-router'
const user = useSupabaseUser()
const supabase = useSupabaseClient()
const route = useRoute()
const commentText = ref('')
const emit = defineEmits(['comment-submitted'])
const submitComment = () => {
if (commentText.value.trim()) {
emit('comment-submitted', commentText.value)
commentText.value = '' // Clear the input after submission
}
}
const login = async () => {
// 保存当前路径到 cookie
const cookieName = useRuntimeConfig().public.supabase.cookieName
console.log("cookieName", cookieName)
useCookie(`${cookieName}-redirect-path`).value = route.fullPath
const { error } = await supabase.auth.signInWithOAuth({
provider: 'github',
options: {
redirectTo: `${window.location.origin}/auth/confirm`
}
})
if (error) {
console.error('Login error:', error)
}
}
</script>
34 changes: 30 additions & 4 deletions middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
export default defineNuxtRouteMiddleware((to) => {
export default defineNuxtRouteMiddleware((to, from) => {
const user = useSupabaseUser()
const supabase = useSupabaseClient()

console.log('Auth middleware executing')
console.log('Route:', to.path)
console.log('User:', user.value)

// 检查会话状态
const checkSession = async () => {
const { data, error } = await supabase.auth.getSession()
console.log('[middleware auth] Session check:', data, error)
return data.session
}

console.log('Auth middleware, path:', to.path, 'user:', user.value)
// 只有访问 /profile 页面时才需要登录
if (!user.value && to.path === '/profile') {
return navigateTo('/login')
if (to.path === '/profile') {
return checkSession().then(session => {
if (!session) {
console.log('[middleware auth] No session, redirecting to login')
return navigateTo('/login')
}
})
}

// 如果用户已登录且尝试访问登录页面,重定向到首页
if (to.path === '/login') {
return checkSession().then(session => {
if (session) {
console.log('[middleware auth] Session exists, redirecting to home')
return navigateTo('/')
}
})
}
})
24 changes: 23 additions & 1 deletion nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export default defineNuxtConfig({
url: 'https://momo.gusibi.mobi',
name: '古思乱讲'
},
ssr: false,
compatibilityDate: '2024-04-03',
devtools: { enabled: true },
modules: [
Expand Down Expand Up @@ -34,7 +35,21 @@ export default defineNuxtConfig({
'~/plugins/head.ts',
'~/plugins/banner-content.ts',
],

routeRules: {
// 指定只有 /profile 路由需要身份验证
'/profile': { auth: true },
},
// 确保中间件被加载
hooks: {
'pages:extend'(pages) {
pages.forEach((page) => {
if (page.path === '/profile') {
page.meta = page.meta || {}
page.meta.middleware = ['auth']
}
})
}
},
runtimeConfig: {
public: {
supabase: {
Expand All @@ -45,6 +60,13 @@ export default defineNuxtConfig({
siteUrl: process.env.SITE_URL || 'https://momo.gusibi.mobi'
}
},
supabase: {
// Options
url: process.env.SUPABASE_URL,
key: process.env.SUPABASE_KEY,
serviceKey: process.env.SUPABASE_SERVICE_KEY,
redirect: false, // Redirect automatically to the configured login page if a non authenticated user is trying to access a guarded. You can disable all redirects by setting this option to false.
},
// Sitemap configuration
sitemap: {
// hostname: 'https://momo.gusibi.mobi',
Expand Down
Loading

0 comments on commit dca684a

Please sign in to comment.