feat: complete auth flow - email confirmation, login state, route guards

This commit is contained in:
2026-05-21 00:21:28 +08:00
parent c49ac7a42e
commit d4b07fba58
6 changed files with 258 additions and 78 deletions
+5
View File
@@ -11,6 +11,11 @@ app.use(pinia)
app.use(router) app.use(router)
const authStore = useAuthStore() const authStore = useAuthStore()
if (window.location.pathname === '/auth/confirm') {
app.mount('#app')
} else {
authStore.initialize().then(() => { authStore.initialize().then(() => {
app.mount('#app') app.mount('#app')
}) })
}
+5
View File
@@ -19,6 +19,11 @@ const router = createRouter({
name: 'register', name: 'register',
component: () => import('@/views/auth/RegisterView.vue'), component: () => import('@/views/auth/RegisterView.vue'),
}, },
{
path: '/auth/confirm',
name: 'auth-confirm',
component: () => import('@/views/auth/AuthConfirmView.vue'),
},
{ {
path: '/upload', path: '/upload',
name: 'upload', name: 'upload',
+25 -4
View File
@@ -19,12 +19,24 @@ export const useAuthStore = defineStore('auth', () => {
.select('*') .select('*')
.eq('id', user.value.id) .eq('id', user.value.id)
.single() .single()
profile.value = data if (data) {
profile.value = data as Profile
}
} }
async function login(email: string, password: string) { async function login(email: string, password: string) {
const { error } = await supabase.auth.signInWithPassword({ email, password }) const { data, error } = await supabase.auth.signInWithPassword({ email, password })
if (error) throw error if (error) {
if (error.message.includes('Invalid login credentials')) {
throw new Error('邮箱或密码错误')
}
if (error.message.includes('Email not confirmed')) {
throw new Error('邮箱未确认,请先查收确认邮件')
}
throw error
}
user.value = data.user
await fetchProfile()
} }
async function register(email: string, password: string, username: string) { async function register(email: string, password: string, username: string) {
@@ -33,9 +45,18 @@ export const useAuthStore = defineStore('auth', () => {
password, password,
options: { options: {
data: { username }, data: { username },
emailRedirectTo: `${window.location.origin}/auth/confirm`,
}, },
}) })
if (error) throw error if (error) {
if (error.message.includes('already registered')) {
throw new Error('该邮箱已被注册')
}
if (error.message.includes('Password')) {
throw new Error('密码强度不足,请使用至少6位密码')
}
throw error
}
} }
async function logout() { async function logout() {
+106
View File
@@ -0,0 +1,106 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { createClient } from '@supabase/supabase-js'
const router = useRouter()
const state = ref<'loading' | 'success' | 'failed'>('loading')
const countdown = ref(5)
let countdownTimer: ReturnType<typeof setInterval> | null = null
function startCountdown() {
countdownTimer = setInterval(() => {
countdown.value--
if (countdown.value <= 0) {
if (countdownTimer) clearInterval(countdownTimer)
router.push('/login')
}
}, 1000)
}
onMounted(async () => {
try {
const hash = window.location.hash.slice(1)
const params = new URLSearchParams(hash)
const accessToken = params.get('access_token')
const refreshToken = params.get('refresh_token')
const type = params.get('type')
const error = params.get('error')
if (error) {
state.value = 'failed'
return
}
if (type === 'signup' && accessToken && refreshToken) {
const confirmClient = createClient(
import.meta.env.VITE_SUPABASE_URL,
import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
)
const { error: setSessionError } = await confirmClient.auth.setSession({
access_token: accessToken,
refresh_token: refreshToken,
})
if (setSessionError) {
state.value = 'failed'
return
}
await confirmClient.auth.signOut()
window.history.replaceState(null, '', window.location.pathname)
state.value = 'success'
startCountdown()
return
}
state.value = 'failed'
} catch {
state.value = 'failed'
}
})
onUnmounted(() => {
if (countdownTimer) clearInterval(countdownTimer)
})
</script>
<template>
<div class="flex items-center justify-center min-h-[calc(100vh-4rem)] px-4">
<div class="w-full max-w-sm text-center">
<template v-if="state === 'success'">
<span class="text-5xl block mb-4"></span>
<h1 class="text-2xl font-bold text-gray-900 mb-2">邮箱认证成功</h1>
<p class="text-gray-500 mb-2">你的邮箱已确认现在可以登录了</p>
<p class="text-sm text-gray-400 mb-6">{{ countdown }} 秒后自动跳转登录页面...</p>
<RouterLink
to="/login"
class="inline-flex items-center px-6 py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 transition-colors"
>
立即登录
</RouterLink>
</template>
<template v-else-if="state === 'failed'">
<span class="text-5xl block mb-4"></span>
<h1 class="text-2xl font-bold text-gray-900 mb-2">认证失败</h1>
<p class="text-gray-500 mb-6">邮箱确认链接无效或已过期请重新注册</p>
<RouterLink
to="/register"
class="inline-flex items-center px-6 py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 transition-colors"
>
重新注册
</RouterLink>
</template>
<template v-else>
<span class="text-5xl block mb-4 animate-pulse"></span>
<h1 class="text-2xl font-bold text-gray-900 mb-2">正在验证...</h1>
<p class="text-gray-500">请稍候</p>
</template>
</div>
</div>
</template>
+15 -7
View File
@@ -20,7 +20,7 @@ async function handleLogin() {
const redirect = (route.query.redirect as string) || '/' const redirect = (route.query.redirect as string) || '/'
router.push(redirect) router.push(redirect)
} catch (e: unknown) { } catch (e: unknown) {
error.value = e instanceof Error ? e.message : '登录失败' error.value = e instanceof Error ? e.message : '登录失败,请稍后重试'
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -30,7 +30,11 @@ async function handleLogin() {
<template> <template>
<div class="flex items-center justify-center min-h-[calc(100vh-4rem)] px-4"> <div class="flex items-center justify-center min-h-[calc(100vh-4rem)] px-4">
<div class="w-full max-w-sm"> <div class="w-full max-w-sm">
<h1 class="text-2xl font-bold text-gray-900 text-center mb-8">登录 OpenCloud</h1> <div class="text-center mb-8">
<span class="text-5xl block mb-4"></span>
<h1 class="text-2xl font-bold text-gray-900">登录 OpenCloud</h1>
<p class="text-sm text-gray-500 mt-1">记录你眼中的每一朵云</p>
</div>
<form @submit.prevent="handleLogin" class="space-y-4"> <form @submit.prevent="handleLogin" class="space-y-4">
<div> <div>
@@ -39,8 +43,9 @@ async function handleLogin() {
v-model="email" v-model="email"
type="email" type="email"
required required
autocomplete="email"
placeholder="your@email.com" placeholder="your@email.com"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-colors"
/> />
</div> </div>
@@ -50,17 +55,20 @@ async function handleLogin() {
v-model="password" v-model="password"
type="password" type="password"
required required
placeholder="至少8位" autocomplete="current-password"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent" placeholder="输入密码"
class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-colors"
/> />
</div> </div>
<p v-if="error" class="text-sm text-red-600">{{ error }}</p> <div v-if="error" class="p-3 bg-red-50 border border-red-200 rounded-lg">
<p class="text-sm text-red-600">{{ error }}</p>
</div>
<button <button
type="submit" type="submit"
:disabled="loading" :disabled="loading"
class="w-full py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 disabled:opacity-50 transition-colors" class="w-full py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 focus:outline-none focus:ring-2 focus:ring-sky-500 focus:ring-offset-2 disabled:opacity-50 transition-colors"
> >
{{ loading ? '登录中...' : '登录' }} {{ loading ? '登录中...' : '登录' }}
</button> </button>
+47 -12
View File
@@ -1,10 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue' import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
const authStore = useAuthStore() const authStore = useAuthStore()
const router = useRouter()
const email = ref('') const email = ref('')
const password = ref('') const password = ref('')
@@ -12,10 +10,19 @@ const confirmPassword = ref('')
const username = ref('') const username = ref('')
const error = ref('') const error = ref('')
const loading = ref(false) const loading = ref(false)
const emailSent = ref(false)
async function handleRegister() { async function handleRegister() {
error.value = '' error.value = ''
if (!username.value.trim()) {
error.value = '请输入用户名'
return
}
if (username.value.length > 20) {
error.value = '用户名不能超过20个字符'
return
}
if (password.value.length < 8) { if (password.value.length < 8) {
error.value = '密码至少8位' error.value = '密码至少8位'
return return
@@ -27,10 +34,10 @@ async function handleRegister() {
loading.value = true loading.value = true
try { try {
await authStore.register(email.value, password.value, username.value) await authStore.register(email.value, password.value, username.value.trim())
router.push('/') emailSent.value = true
} catch (e: unknown) { } catch (e: unknown) {
error.value = e instanceof Error ? e.message : '注册失败' error.value = e instanceof Error ? e.message : '注册失败,请稍后重试'
} finally { } finally {
loading.value = false loading.value = false
} }
@@ -40,7 +47,27 @@ async function handleRegister() {
<template> <template>
<div class="flex items-center justify-center min-h-[calc(100vh-4rem)] px-4"> <div class="flex items-center justify-center min-h-[calc(100vh-4rem)] px-4">
<div class="w-full max-w-sm"> <div class="w-full max-w-sm">
<h1 class="text-2xl font-bold text-gray-900 text-center mb-8">注册 OpenCloud</h1> <div v-if="emailSent" class="text-center">
<span class="text-5xl block mb-4">📧</span>
<h1 class="text-2xl font-bold text-gray-900 mb-2">确认你的邮箱</h1>
<p class="text-gray-500 mb-6">
我们已向 <strong class="text-gray-700">{{ email }}</strong> 发送了确认邮件请查收并点击确认链接完成注册
</p>
<p class="text-sm text-gray-400 mb-6">没有收到请检查垃圾邮件文件夹</p>
<RouterLink
to="/login"
class="inline-flex items-center px-6 py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 transition-colors"
>
去登录
</RouterLink>
</div>
<template v-else>
<div class="text-center mb-8">
<span class="text-5xl block mb-4"></span>
<h1 class="text-2xl font-bold text-gray-900">注册 OpenCloud</h1>
<p class="text-sm text-gray-500 mt-1">加入天空探索者社区</p>
</div>
<form @submit.prevent="handleRegister" class="space-y-4"> <form @submit.prevent="handleRegister" class="space-y-4">
<div> <div>
@@ -49,8 +76,10 @@ async function handleRegister() {
v-model="username" v-model="username"
type="text" type="text"
required required
autocomplete="username"
placeholder="你的昵称" placeholder="你的昵称"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent" maxlength="20"
class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-colors"
/> />
</div> </div>
@@ -60,8 +89,9 @@ async function handleRegister() {
v-model="email" v-model="email"
type="email" type="email"
required required
autocomplete="email"
placeholder="your@email.com" placeholder="your@email.com"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-colors"
/> />
</div> </div>
@@ -71,8 +101,9 @@ async function handleRegister() {
v-model="password" v-model="password"
type="password" type="password"
required required
autocomplete="new-password"
placeholder="至少8位" placeholder="至少8位"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-colors"
/> />
</div> </div>
@@ -82,17 +113,20 @@ async function handleRegister() {
v-model="confirmPassword" v-model="confirmPassword"
type="password" type="password"
required required
autocomplete="new-password"
placeholder="再次输入密码" placeholder="再次输入密码"
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-colors"
/> />
</div> </div>
<p v-if="error" class="text-sm text-red-600">{{ error }}</p> <div v-if="error" class="p-3 bg-red-50 border border-red-200 rounded-lg">
<p class="text-sm text-red-600">{{ error }}</p>
</div>
<button <button
type="submit" type="submit"
:disabled="loading" :disabled="loading"
class="w-full py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 disabled:opacity-50 transition-colors" class="w-full py-2.5 bg-sky-500 text-white font-medium rounded-lg hover:bg-sky-600 focus:outline-none focus:ring-2 focus:ring-sky-500 focus:ring-offset-2 disabled:opacity-50 transition-colors"
> >
{{ loading ? '注册中...' : '注册' }} {{ loading ? '注册中...' : '注册' }}
</button> </button>
@@ -102,6 +136,7 @@ async function handleRegister() {
已有账号 已有账号
<RouterLink to="/login" class="text-sky-600 hover:text-sky-700 font-medium">去登录</RouterLink> <RouterLink to="/login" class="text-sky-600 hover:text-sky-700 font-medium">去登录</RouterLink>
</p> </p>
</template>
</div> </div>
</div> </div>
</template> </template>