consumer模块完成90%,前端完成supabase对接

This commit is contained in:
2026-02-04 17:21:15 +08:00
parent 8a535e3f38
commit 39aa1b6bec
1335 changed files with 191376 additions and 4 deletions

View File

@@ -0,0 +1,179 @@
<template>
<view class="page-container">
<view class="form-group">
<view class="input-item">
<text class="label">邮箱</text>
<input class="input" type="text" placeholder="请输入邮箱地址" v-model="email" />
</view>
<view class="input-item">
<text class="label">验证码</text>
<input class="input" type="number" placeholder="请输入验证码" v-model="code" maxlength="6" />
<text class="code-btn" @click="sendCode">{{ counting ? `${count}s` : '获取验证码' }}</text>
</view>
</view>
<button class="submit-btn" @click="handleSubmit">确认绑定</button>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import supa from '@/components/supadb/aksupainstance.uts'
const email = ref('')
const code = ref('')
const counting = ref(false)
const count = ref(60)
const sendCode = async () => {
if (counting.value) return
if (!email.value || !email.value.includes('@')) {
uni.showToast({
title: '请输入正确的邮箱',
icon: 'none'
})
return
}
uni.showLoading({ title: '发送中...' })
try {
const { error } = await supa.auth.updateUser({
email: email.value
})
uni.hideLoading()
if (error != null) {
uni.showToast({
title: '发送失败: ' + error.message,
icon: 'none'
})
return
}
counting.value = true
count.value = 60
const timer = setInterval(() => {
count.value--
if (count.value <= 0) {
clearInterval(timer)
counting.value = false
}
}, 1000)
uni.showToast({
title: '验证码已发送',
icon: 'none'
})
} catch(e) {
uni.hideLoading()
console.error(e)
uni.showToast({ title: '发送异常', icon: 'none' })
}
}
const handleSubmit = async () => {
if (!email.value || !code.value) {
uni.showToast({
title: '请填写完整信息',
icon: 'none'
})
return
}
uni.showLoading({ title: '绑定中...' })
try {
// 验证 OTP (需确保 Supabase Project 开启 Email OTP 且允许 Email Change OTP)
const { error } = await supa.auth.verifyOtp({
email: email.value,
token: code.value,
type: 'email_change'
})
uni.hideLoading()
if (error != null) {
uni.showToast({
title: '绑定失败: ' + error.message,
icon: 'none'
})
return
}
uni.showToast({
title: '绑定成功',
icon: 'success'
})
// 更新本地存储
const userInfo = uni.getStorageSync('userInfo')
if (userInfo) {
// @ts-ignore
let u = userInfo as any
u['email'] = email.value
uni.setStorageSync('userInfo', u)
}
setTimeout(() => {
uni.navigateBack()
}, 1500)
} catch(e) {
uni.hideLoading()
console.error(e)
uni.showToast({ title: '系统错误', icon: 'none' })
}
}
</script>
<style>
.page-container {
padding: 20px;
background-color: #f5f5f5;
min-height: 100vh;
}
.form-group {
background-color: #fff;
border-radius: 8px;
padding: 0 15px;
margin-bottom: 30px;
}
.input-item {
display: flex;
align-items: center;
height: 50px;
border-bottom: 1px solid #eee;
}
.input-item:last-child {
border-bottom: none;
}
.label {
width: 70px;
font-size: 14px;
color: #333;
}
.input {
flex: 1;
font-size: 14px;
}
.code-btn {
color: #007aff;
font-size: 14px;
padding: 5px 10px;
}
.submit-btn {
background-color: #007aff;
color: #fff;
border-radius: 25px;
font-size: 16px;
}
</style>

View File

@@ -0,0 +1,180 @@
<template>
<view class="page-container">
<view class="form-group">
<view class="input-item">
<text class="label">手机号</text>
<input class="input" type="number" placeholder="请输入新手机号" v-model="phone" maxlength="11" />
</view>
<view class="input-item">
<text class="label">验证码</text>
<input class="input" type="number" placeholder="请输入验证码" v-model="code" maxlength="6" />
<text class="code-btn" @click="sendCode">{{ counting ? `${count}s` : '获取验证码' }}</text>
</view>
</view>
<button class="submit-btn" @click="handleSubmit">确认绑定</button>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import supa from '@/components/supadb/aksupainstance.uts'
const phone = ref('')
const code = ref('')
const counting = ref(false)
const count = ref(60)
const sendCode = async () => {
if (counting.value) return
if (!phone.value || phone.value.length !== 11) {
uni.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
uni.showLoading({ title: '发送中...' })
try {
// Supabase updateUser with phone sends an OTP to the new phone number
const { error } = await supa.auth.updateUser({
phone: phone.value
})
uni.hideLoading()
if (error != null) {
uni.showToast({
title: '发送失败: ' + error.message,
icon: 'none'
})
return
}
counting.value = true
count.value = 60
const timer = setInterval(() => {
count.value--
if (count.value <= 0) {
clearInterval(timer)
counting.value = false
}
}, 1000)
uni.showToast({
title: '验证码已发送',
icon: 'none'
})
} catch(e) {
uni.hideLoading()
console.error(e)
uni.showToast({ title: '发送异常', icon: 'none' })
}
}
const handleSubmit = async () => {
if (!phone.value || !code.value) {
uni.showToast({
title: '请填写完整信息',
icon: 'none'
})
return
}
uni.showLoading({ title: '绑定中...' })
try {
// 验证 OTP
const { error } = await supa.auth.verifyOtp({
phone: phone.value,
token: code.value,
type: 'phone_change'
})
uni.hideLoading()
if (error != null) {
uni.showToast({
title: '绑定失败: ' + error.message,
icon: 'none'
})
return
}
uni.showToast({
title: '绑定成功',
icon: 'success'
})
// 更新本地存储的用户信息
const userInfo = uni.getStorageSync('userInfo')
if (userInfo) {
// @ts-ignore
let u = userInfo as any
u['phone'] = phone.value
uni.setStorageSync('userInfo', u)
}
setTimeout(() => {
uni.navigateBack()
}, 1500)
} catch(e) {
uni.hideLoading()
console.error(e)
uni.showToast({ title: '系统错误', icon: 'none' })
}
}
</script>
<style>
.page-container {
padding: 20px;
background-color: #f5f5f5;
min-height: 100vh;
}
.form-group {
background-color: #fff;
border-radius: 8px;
padding: 0 15px;
margin-bottom: 30px;
}
.input-item {
display: flex;
align-items: center;
height: 50px;
border-bottom: 1px solid #eee;
}
.input-item:last-child {
border-bottom: none;
}
.label {
width: 70px;
font-size: 14px;
color: #333;
}
.input {
flex: 1;
font-size: 14px;
}
.code-btn {
color: #007aff;
font-size: 14px;
padding: 5px 10px;
}
.submit-btn {
background-color: #007aff;
color: #fff;
border-radius: 25px;
font-size: 16px;
}
</style>

177
mall/pages/user/boot.uvue Normal file
View File

@@ -0,0 +1,177 @@
<template>
<view class="page">
<view class="splash">
<view class="brand">
<view class="brand-mark"></view>
<view class="brand-text">
<text class="brand-name">Mall</text>
<text class="brand-slogan">正品保障 · 省心售后</text>
</view>
</view>
<view class="status">
<view class="spinner"></view>
<text class="status-text">正在检查登录状态…</text>
<text class="status-sub">通常数秒内自动进入首页或登录页</text>
</view>
<view class="actions">
<navigator url="/pages/user/login" open-type="reLaunch" class="action primary">前往登录</navigator>
<navigator url="/pages/user/register" open-type="navigate" class="action ghost">我要注册</navigator>
</view>
</view>
</view>
</template>
<script lang="uts">
import supa from '@/components/supadb/aksupainstance.uts'
import { IS_TEST_MODE } from '@/ak/config.uts'
export default {
onLoad() {
// 启动页:根据登录态重定向
this.checkAndRedirect();
},
onShow() {
// 启动页仅在首次进入时做一次跳转,避免影响 H5 手动输入 URL
},
methods: {
checkAndRedirect() {
console.log('boot: start redirect check')
if (IS_TEST_MODE) {
// 测试阶段:不做强制重定向,保留你手动输入的 URL / 目标页面
return
}
try {
const sessionInfo = supa.getSession()
if (sessionInfo != null && sessionInfo.user != null) {
uni.reLaunch({ url: '/pages/mall/consumer/index' })
return
}
} catch (e) {
console.error('boot: error checking session', e)
}
uni.reLaunch({ url: '/pages/user/login' })
}
}
};
</script>
<style>
.page {
min-height: 100vh;
background: linear-gradient(180deg, #ffffff 0%, #f5f7fa 100%);
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx;
}
.splash {
width: 100%;
max-width: 640rpx;
background: #ffffff;
border-radius: 24rpx;
box-shadow: 0 12rpx 48rpx rgba(0, 0, 0, 0.08);
padding: 48rpx 40rpx;
display: flex;
flex-direction: column;
gap: 32rpx;
}
.brand {
display: flex;
align-items: center;
gap: 20rpx;
}
.brand-mark {
width: 80rpx;
height: 80rpx;
border-radius: 24rpx;
background: linear-gradient(135deg, #ff6b6b, #ff9f43);
}
.brand-text {
display: flex;
flex-direction: column;
gap: 8rpx;
}
.brand-name {
font-size: 36rpx;
font-weight: 700;
color: #111827;
}
.brand-slogan {
font-size: 26rpx;
color: #6b7280;
}
.status {
display: flex;
flex-direction: column;
align-items: center;
gap: 12rpx;
text-align: center;
}
.spinner {
width: 88rpx;
height: 88rpx;
border-radius: 50%;
border: 8rpx solid #f3f4f6;
border-top-color: #ff6b6b;
animation: spin 1s linear infinite;
}
.status-text {
font-size: 30rpx;
color: #111827;
font-weight: 600;
}
.status-sub {
font-size: 24rpx;
color: #6b7280;
}
.actions {
display: flex;
flex-direction: column;
gap: 16rpx;
}
.action {
width: 100%;
text-align: center;
padding: 24rpx;
border-radius: 16rpx;
font-size: 28rpx;
font-weight: 600;
}
.action.primary {
background: linear-gradient(135deg, #ff6b6b, #ff9f43);
color: #ffffff;
}
.action.ghost {
border: 2rpx solid #e5e7eb;
color: #374151;
background: #ffffff;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>

686
mall/pages/user/center.uvue Normal file
View File

@@ -0,0 +1,686 @@
<template>
<view class="page-wrapper">
<!-- Top section with language switch -->
<view class="top-section"> <view class="language-switch">
<button class="language-btn" @click="toggleLanguage">
{{ currentLocale === 'zh-CN' ? 'EN' : '中' }}
</button>
</view>
</view>
<!-- Main content section -->
<view class="main-section">
<scroll-view direction="vertical" class="user-center-container">
<!-- Header with user info -->
<view class="user-header">
<view class="user-info">
<image class="user-avatar" :src="userAvatar" mode="aspectFill"></image>
<view class="user-details">
<text class="user-name">{{ profile.username ?? $t('user.center.unnamed') }}</text>
<view class="edit-profile-link" @click="navigateToProfile">
<text class="edit-text">{{ $t('user.center.edit_profile') }}</text>
<text class="edit-icon">✏️</text>
</view>
</view>
</view>
<!-- User stats -->
<view class="stats-container">
<view class="stat-item">
<text class="stat-value">{{ userStats.trainings }}</text>
<text class="stat-label">{{ $t('user.center.trainings') }}</text>
</view>
<view class="stat-divider"></view>
<view class="stat-item">
<text class="stat-value">{{ userStats.points }}</text>
<text class="stat-label">{{ $t('user.center.points') }}</text>
</view>
<view class="stat-divider"></view>
<view class="stat-item">
<text class="stat-value">{{ userStats.streak }}</text>
<text class="stat-label">{{ $t('user.center.streak') }}</text>
</view>
</view>
</view>
<!-- Main menu sections -->
<view class="menu-sections">
<!-- Training section -->
<view class="menu-section">
<view class="section-header">
<text class="section-title">{{ $t('user.center.training') }}</text>
</view>
<view class="section-items">
<view class="menu-item" @click="navigateTo('/pages/training/records')"> <view class="menu-icon training-records">📊</view>
<text class="menu-text">{{ $t('user.center.training_records') }}</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" @click="navigateTo('/pages/training/plans')">
<view class="menu-icon training-plans">📋</view>
<text class="menu-text">{{ $t('user.center.training_plans') }}</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" @click="navigateTo('/pages/training/reports')">
<view class="menu-icon reports">📈</view>
<text class="menu-text">{{ $t('user.center.reports') }}</text>
<text class="menu-arrow">></text>
</view>
</view>
</view>
<!-- Account section -->
<view class="menu-section">
<view class="section-header">
<text class="section-title">{{ $t('user.center.account') }}</text>
</view>
<view class="section-items"> <view class="menu-item" @click="navigateTo('/pages/user/profile')">
<view class="menu-icon profile">👤</view>
<text class="menu-text">{{ $t('user.center.profile') }}</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" @click="navigateTo('/pages/user/devices')">
<view class="menu-icon devices">📱</view>
<text class="menu-text">{{ $t('user.center.devices') }}</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" @click="navigateTo('/pages/user/notifications')">
<view class="menu-icon notifications">🔔</view>
<text class="menu-text">{{ $t('user.center.notifications') }}</text>
<text class="menu-arrow">></text>
</view>
</view>
</view>
<!-- Settings section -->
<view class="menu-section">
<view class="section-header">
<text class="section-title">{{ $t('user.center.settings') }}</text>
</view>
<view class="section-items"> <view class="menu-item" @click="navigateTo('/pages/settings/app')">
<view class="menu-icon app-settings">⚙️</view>
<text class="menu-text">{{ $t('user.center.app_settings') }}</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" @click="navigateTo('/pages/settings/about')">
<view class="menu-icon about"></view>
<text class="menu-text">{{ $t('user.center.about') }}</text>
<text class="menu-arrow">></text>
</view>
</view>
</view> <!-- Logout button -->
<button class="logout-button" @click="showLogoutConfirm">
{{ $t('user.center.logout') }}
</button>
</view>
</scroll-view>
</view>
<!-- Bottom section -->
<view class="bottom-section">
<!-- Footer content or spacing -->
</view>
</view>
</template>
<script lang="uts">
import { AkReqOptions, AkReqResponse, AkReqError } from '@/uni_modules/ak-req/index.uts';
import supa from '@/components/supadb/aksupainstance.uts'
import type { UserProfile,UserStats } from './types.uts';
import { setUserProfile } from '@/utils/store.uts';
import { AkSupaSelectOptions } from '@/components/supadb/aksupa.uts'
import { switchLocale, getCurrentLocale } from '@/utils/utils.uts';
export default {
data() {
return {
isLoading: true,
userStats: {
trainings: 0,
points: 0,
streak: 0
} as UserStats,
profile: {
username: '',
email: ''
} as UserProfile,
userAvatar: '/static/default-avatar.png',
currentLocale: getCurrentLocale()
};
},
onLoad() {
},
onShow() {
this.loadProfile();
this.loadUserStats();
}, methods: {
toggleLanguage() {
const newLocale = this.currentLocale === 'zh-CN' ? 'en-US' : 'zh-CN';
switchLocale(newLocale);
this.currentLocale = newLocale;
uni.showToast({
title: this.$t('user.center.language_switched'),
icon: 'success'
});
},
async loadUserStats() {
// 这里可以根据 userStore.profile.id 拉取真实数据
this.userStats = {
trainings: 12,
points: 480,
streak: 5
};
},
async loadProfile() {
const user = supa.user;
if (user==null || user.email=='') {
console.log('null user:',user)
this.profile.email = '';
return;
}
const filter = `id.eq.${user.id}`;
const options = { single: true } as AkSupaSelectOptions;
const { data, error } = await supa.select('ak_users', filter, options);
// 判断 data 是否为数组且为空
if(Array.isArray(data) && data.length> 0) {
console.log(data)
let prodata= data[0] as UTSJSONObject;
this.profile = {
id: user.id as string,
username: prodata.getString("username")??"",
email: prodata.getString("email")??"",
gender: prodata.getString("gender"),
birthday: prodata.getString("birthday"),
height_cm: prodata.getNumber("height_cm"),
weight_kg: prodata.getNumber("weight_kg"),
bio: prodata.getString("bio"),
avatar_url: prodata.getString("avatar_url")??'/static/logo.png',
preferred_language: prodata.getString("preferred_language"),
}
this.userAvatar = this.profile.avatar_url!!;
}
else {
this.profile.id= user.getString("id");
this.profile.username = user.getString("username")??"";
this.profile.email = user.getString("email")??"";
let newProfile = new UTSJSONObject(this.profile);
const insertResult = await supa.from('ak_users').insert(newProfile).execute();
console.log(insertResult)
if (insertResult.error==null) {
setUserProfile(this.profile);
}
}
},
navigateToProfile() {
uni.navigateTo({
url: '/pages/user/profile'
});
},
navigateTo(url: string) {
const implementedPages = ['/pages/user/profile'];
if (implementedPages.includes(url)) {
uni.navigateTo({ url });
} else {
uni.showToast({
title: 'Coming soon',
icon: 'none'
});
}
},
showLogoutConfirm() {
uni.showModal({
title: this.$t('user.center.logout_confirm_title'),
content: this.$t('user.center.logout_confirm_message'),
cancelText: this.$t('user.center.cancel'),
confirmText: this.$t('user.center.confirm'),
success: (res) => {
if (res.confirm) {
this.handleLogout();
}
}
});
},
async handleLogout() {
try {
await supa.signOut();
uni.showToast({
title: this.$t('user.center.logout_success'),
icon: 'success'
});
setTimeout(() => {
uni.reLaunch({
url: '/pages/user/login'
});
}, 1000);
} catch (err) {
console.error('Logout error:', err);
uni.showToast({
title: this.$t('user.center.logout_error'),
icon: 'none'
});
}
}
}
};
</script>
<style>
/* Page wrapper for full screen utilization */
.page-wrapper {
/* #ifdef APP-PLUS */ display: flex;
flex-direction: column;
/* #endif */
/* #ifndef APP-PLUS *//* #endif */
background-color: #f8f9fa;
}
/* Top section - Fixed header */
.top-section {
/* #ifdef APP-PLUS */
flex: 0 0 auto;
height: 100rpx;
/* #endif */ /* #ifndef APP-PLUS */
height: 120rpx;
/* #endif */
position: relative;
background-image: linear-gradient(to right, #2196f3, #03a9f4);
}
/* Main content section - Scrollable */
.main-section {
/* #ifdef APP-PLUS */
flex: 1;
overflow: hidden;
/* #endif */
/* #ifndef APP-PLUS */
flex-grow: 1;
/* #endif */
}
/* Bottom section - Fixed footer */
.bottom-section {
/* #ifdef APP-PLUS */
flex: 0 0 auto;
height: 50rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 60rpx;
/* #endif */
background-color: #f8f9fa;
}
.user-center-container {
/* #ifdef APP-PLUS */ /* #endif */
/* #ifndef APP-PLUS *//* #endif */
background-color: #f8f9fa;
/* #ifdef APP-PLUS */
padding-bottom: 40rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding-bottom: 50rpx;
/* #endif */
}
/* Language switch button */
.language-switch {
position: absolute;
/* #ifdef APP-PLUS */
top: 20rpx;
right: 30rpx;
/* #endif */
/* #ifndef APP-PLUS */
top: 30rpx;
right: 40rpx;
/* #endif */
z-index: 10;
}
/* User header */
.user-header {
background-image: linear-gradient(to right, #2196f3, #03a9f4);
/* #ifdef APP-PLUS */
padding: 30rpx 30rpx 25rpx;
border-bottom-left-radius: 25rpx;
border-bottom-right-radius: 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 60rpx 40rpx 30rpx;
border-bottom-left-radius: 30rpx;
border-bottom-right-radius: 30rpx;
/* #endif */
color: #fff;
box-shadow: 0 10rpx 20rpx rgba(3, 169, 244, 0.2);
}
.user-info {
display: flex;
align-items: center;
flex-direction: row;
}
.user-avatar {
/* #ifdef APP-PLUS */
width: 90rpx;
height: 90rpx;
border-radius: 45rpx;
border: 3rpx solid #fff;
/* #endif */
/* #ifndef APP-PLUS */
width: 120rpx;
height: 120rpx;
border-radius: 60rpx;
border: 4rpx solid #fff;
/* #endif */
background-color: #fff;
}
.user-details {
flex: 1;
/* #ifdef APP-PLUS */
margin-left: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-left: 30rpx;
/* #endif */
}
.user-name {
/* #ifdef APP-PLUS */
font-size: 28rpx;
margin-bottom: 8rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 36rpx;
margin-bottom: 10rpx;
/* #endif */
font-weight: bold;
}
.edit-profile-link {
display: flex;
align-items: center;
}
.edit-text {
/* #ifdef APP-PLUS */
font-size: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
/* #endif */
color: rgba(255, 255, 255, 0.9);
}
.edit-icon {
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-left: 5rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-left: 6rpx;
/* #endif */
}
/* Stats container */
.stats-container {
display: flex;
flex-direction: row;
/* #ifdef APP-PLUS */
margin-top: 30rpx;
border-radius: 12rpx;
padding: 15rpx 0;
/* #endif */
/* #ifndef APP-PLUS */
margin-top: 40rpx;
border-radius: 15rpx;
padding: 20rpx 0;
/* #endif */
background-color: rgba(255, 255, 255, 0.15);
}
.stat-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.stat-value {
/* #ifdef APP-PLUS */
font-size: 24rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 32rpx;
/* #endif */
font-weight: bold;
}
.stat-label {
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-top: 4rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-top: 6rpx;
/* #endif */
opacity: 0.9;
}
.stat-divider {
width: 2rpx;
background-color: rgba(255, 255, 255, 0.3);
/* #ifdef APP-PLUS */
margin: 8rpx 0;
/* #endif */
/* #ifndef APP-PLUS */
margin: 10rpx 0;
/* #endif */
}
/* Menu sections */
.menu-sections {
/* #ifdef APP-PLUS */
padding: 30rpx 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 40rpx 30rpx;
/* #endif */
}
.menu-section {
background-color: #fff;
/* #ifdef APP-PLUS */
border-radius: 15rpx;
margin-bottom: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
border-radius: 20rpx;
margin-bottom: 30rpx;
/* #endif */
overflow: hidden;
box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.05);
}
.section-header {
/* #ifdef APP-PLUS */
padding: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 30rpx;
/* #endif */
border-bottom: 2rpx solid #f0f0f0;
}
.section-title {
/* #ifdef APP-PLUS */
font-size: 22rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
/* #endif */
font-weight: bold;
color: #333;
}
.section-items {
/* #ifdef APP-PLUS */
padding: 0 10rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 0 15rpx;
/* #endif */
}
.menu-item {
display: flex;
flex-direction: row;
align-items: center;
/* #ifdef APP-PLUS */
padding: 20rpx 10rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 30rpx 15rpx;
/* #endif */
border-bottom: 2rpx solid #f8f8f8;
}
.menu-item:last-child {
border-bottom: none;
flex-direction: row;
}
.menu-icon {
/* #ifdef APP-PLUS */
width: 45rpx;
height: 45rpx;
border-radius: 22rpx;
margin-right: 15rpx;
font-size: 24rpx;
/* #endif */
/* #ifndef APP-PLUS */
width: 60rpx;
height: 60rpx;
border-radius: 30rpx;
margin-right: 20rpx;
font-size: 30rpx;
/* #endif */
display: flex;
align-items: center;
justify-content: center;
}
.menu-text {
flex: 1;
/* #ifdef APP-PLUS */
font-size: 22rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
/* #endif */
color: #333;
}
.menu-arrow {
/* #ifdef APP-PLUS */
font-size: 28rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 36rpx;
/* #endif */
color: #ccc;
}
/* Menu icons with different colors */
.training-records {
background-color: #e3f2fd;
}
.training-plans {
background-color: #e8f5e9;
}
.reports {
background-color: #f3e5f5;
}
.profile {
background-color: #e1f5fe;
}
.devices {
background-color: #fffde7;
}
.notifications {
background-color: #fff3e0;
}
.app-settings {
background-color: #e0f2f1;
}
.about {
background-color: #f5f5f5;
}
/* Logout button */
.logout-button {
width: 100%;
/* #ifdef APP-PLUS */
height: 70rpx;
font-size: 26rpx;
margin: 20rpx 0 15rpx;
border-radius: 35rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 90rpx;
font-size: 32rpx;
margin: 30rpx 0 20rpx;
border-radius: 45rpx;
/* #endif */
background-color: #fff; color: #f44336;
font-weight: normal;
border: 2rpx solid #fce4ec;
text-align: center;
}
/* Center row utility class */
.center-row {
display: flex;
flex-direction: row;
align-items: center; /* 如有需<E69C89>?*/
}
.language-btn {
/* #ifdef APP-PLUS */
width: 60rpx;
height: 60rpx;
border-radius: 30rpx;
font-size: 22rpx;
/* #endif */
/* #ifndef APP-PLUS */
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
font-size: 28rpx;
/* #endif */ background-color: rgba(33, 150, 243, 0.8);
color: #fff;
font-weight: normal;
border: 2rpx solid rgba(255, 255, 255, 0.3);
text-align: center;
box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
}
</style>

View File

@@ -0,0 +1,128 @@
<template>
<view class="page-container">
<view class="form-group">
<view class="input-item">
<text class="label">旧密码</text>
<input class="input" type="password" placeholder="请输入旧密码" v-model="oldPassword" />
</view>
<view class="input-item">
<text class="label">新密码</text>
<input class="input" type="password" placeholder="请输入新密码" v-model="newPassword" />
</view>
<view class="input-item">
<text class="label">确认密码</text>
<input class="input" type="password" placeholder="请再次输入新密码" v-model="confirmPassword" />
</view>
</view>
<button class="submit-btn" @click="handleSubmit">确认修改</button>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import supa from '@/components/supadb/aksupainstance.uts'
const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const handleSubmit = async () => {
if (!oldPassword.value || !newPassword.value || !confirmPassword.value) {
uni.showToast({
title: '请填写完整信息',
icon: 'none'
})
return
}
if (newPassword.value !== confirmPassword.value) {
uni.showToast({
title: '两次输入的密码不一致',
icon: 'none'
})
return
}
uni.showLoading({ title: '提交中...' })
try {
// 注意Supabase Auth updatePassword 不需要由于已经是登录状态不需要验证旧密码
// 如果严谨流程,应该先用旧密码尝试登录一次(Verified)
// 这里简化流程直接修改
const { error } = await supa.auth.updateUser({
password: newPassword.value
})
uni.hideLoading()
if (error !== null) {
console.error(error)
uni.showToast({
title: '修改失败: ' + error.message,
icon: 'none'
})
return
}
uni.showToast({
title: '修改成功',
icon: 'success'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
} catch (e) {
uni.hideLoading()
console.error(e)
uni.showToast({
title: '请求异常',
icon: 'none'
})
}
}
</script>
<style>
.page-container {
padding: 20px;
background-color: #f5f5f5;
min-height: 100vh;
}
.form-group {
background-color: #fff;
border-radius: 8px;
padding: 0 15px;
margin-bottom: 30px;
}
.input-item {
display: flex;
align-items: center;
height: 50px;
border-bottom: 1px solid #eee;
}
.input-item:last-child {
border-bottom: none;
}
.label {
width: 80px;
font-size: 14px;
color: #333;
}
.input {
flex: 1;
font-size: 14px;
}
.submit-btn {
background-color: #007aff;
color: #fff;
border-radius: 25px;
font-size: 16px;
}
</style>

View File

@@ -0,0 +1,495 @@
<template>
<!-- Single scrollable container for tablet optimization -->
<scroll-view class="forgot-password-container" scroll-y="true" show-scrollbar="false">
<!-- Language switch positioned absolutely -->
<view class="language-switch">
<button class="language-btn" @click="toggleLanguage">
{{ currentLocale === 'zh-CN' ? 'EN' : '中' }}
</button>
</view>
<!-- Main content wrapper -->
<view class="content-wrapper">
<!-- Logo and title section -->
<view class="logo-section">
<text class="app-title">Akmon</text>
<text class="page-title">{{ $t('user.forgot_password.title') }}</text>
<text class="page-subtitle">{{ $t('user.forgot_password.subtitle') }}</text>
</view>
<!-- Form container with content inside -->
<view class="form-container">
<view v-if="!resetEmailSent">
<form @submit="onSubmit">
<!-- Email input -->
<view class="input-group" :class="{ 'input-error': emailError }">
<text class="input-label">{{ $t('user.forgot_password.email') }}</text>
<input
class="input-field"
name="email"
type="text"
v-model="email"
:placeholder="$t('user.forgot_password.email_placeholder')"
@blur="validateEmail"
/>
<text v-if="emailError" class="error-text">{{ emailError }}</text>
</view>
<!-- Submit button -->
<button form-type="submit" class="submit-button" :disabled="isLoading" :loading="isLoading">
{{ $t('user.forgot_password.submit_button') }}
</button>
<!-- General error message -->
<text v-if="generalError" class="general-error">{{ generalError }}</text>
</form>
<!-- Login option -->
<view class="login-option">
<text class="login-text">{{ $t('user.forgot_password.remember_password') }}</text>
<text class="login-link" @click="navigateToLogin">{{ $t('user.forgot_password.login') }}</text>
</view>
</view>
<!-- Success message -->
<view v-else class="success-container">
<view class="success-icon">✓</view>
<text class="success-title">{{ $t('user.forgot_password.email_sent_title') }}</text>
<text class="success-message">{{ $t('user.forgot_password.email_sent_message') }}</text>
<button class="back-button" @click="navigateToLogin">
{{ $t('user.forgot_password.back_to_login') }}
</button>
</view>
</view>
</view>
</scroll-view>
</template>
<script lang="uts">
import supa from '@/components/supadb/aksupainstance.uts';
import { switchLocale, getCurrentLocale } from '@/utils/utils.uts';
export default {
data() {
return {
email: "",
emailError: "",
generalError: "",
isLoading: false,
resetEmailSent: false,
currentLocale: getCurrentLocale()
};
}, methods: {
toggleLanguage() {
const newLocale = this.currentLocale === 'zh-CN' ? 'en-US' : 'zh-CN';
switchLocale(newLocale);
this.currentLocale = newLocale;
uni.showToast({
title: this.$t('user.forgot_password.language_switched'),
icon: 'success'
});
},
onSubmit(e: UniFormSubmitEvent) {
this.handleResetRequest();
},
validateEmail() {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (this.email == null || this.email === "") {
this.emailError = this.$t('user.forgot_password.email_required');
return false;
} else if (!emailRegex.test(this.email)) {
this.emailError = this.$t('user.forgot_password.email_invalid');
return false;
} else {
this.emailError = '';
return true;
}
},
async handleResetRequest() {
this.generalError = '';
if (!this.validateEmail()) {
return;
}
this.isLoading = true;
try {
// Call Supabase password reset method
const result = await supa.resetPassword(this.email);
// Show success view
this.resetEmailSent = true;
} catch (err) {
console.error("Password reset error:", err);
// Format error message
if (typeof err === 'object' && err !== null) {
const errObj = err as UniError;
if (typeof errObj.message === 'string') {
// If we have a specific error message from Supabase
this.generalError = errObj.message;
} else {
this.generalError = this.$t('user.forgot_password.unknown_error');
}
} else {
this.generalError = this.$t('user.forgot_password.unknown_error');
}
} finally {
this.isLoading = false;
}
},
navigateToLogin() {
uni.navigateTo({
url: '/pages/user/login'
});
}
}
};
</script>
<style>
/* Single scrollable container for tablet optimization */
.forgot-password-container {
height: 100%;
/* #ifdef APP-PLUS */
padding: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 40rpx;
/* #endif */
background-color: #f8f9fa;
box-sizing: border-box;
}
/* Content wrapper for centered layout */
.content-wrapper {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
padding-bottom: 40rpx;
/* 确保内容足够高以触发滚动 */
/* #ifdef APP-PLUS */
min-height: 800rpx;
/* #endif */
/* #ifndef APP-PLUS */
min-height: 1000rpx;
/* #endif */
}
/* Language switch button - positioned absolutely */
.language-switch {
position: absolute;
/* #ifdef APP-PLUS */
top: 30rpx;
right: 30rpx;
/* #endif */
/* #ifndef APP-PLUS */
top: 40rpx;
right: 40rpx;
/* #endif */
z-index: 10;
}
.language-btn {
/* #ifdef APP-PLUS */
width: 50rpx;
height: 50rpx;
border-radius: 25rpx;
font-size: 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
font-size: 28rpx;
/* #endif */ background-color: rgba(33, 150, 243, 0.8); color: #fff;
font-weight: normal;
border: 2rpx solid rgba(255, 255, 255, 0.3);
text-align: center;
box-shadow: 0 4rpx 12rpx rgba(33, 150, 243, 0.3);
}
/* Logo and title section */
.logo-section {
display: flex;
flex-direction: column;
align-items: center;
/* #ifdef APP-PLUS */
margin-top: 60rpx;
margin-bottom: 30rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-top: 80rpx;
margin-bottom: 40rpx;
/* #endif */
}
.app-title {
/* #ifdef APP-PLUS */
font-size: 28rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 36rpx;
/* #endif */
font-weight: bold;
color: #2196f3;
}
.page-title {
/* #ifdef APP-PLUS */
font-size: 32rpx;
margin-top: 12rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 48rpx;
margin-top: 20rpx;
/* #endif */
font-weight: bold;
color: #333;
}
.page-subtitle {
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-top: 6rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
margin-top: 10rpx;
/* #endif */
color: #666;
}
/* Form container */
.form-container {
width: 100%;
/* #ifdef APP-PLUS */
max-width: 500rpx;
padding: 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
max-width: 680rpx;
padding: 40rpx;
/* #endif */
background-color: #ffffff;
border-radius: 20rpx;
box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
box-sizing: border-box;
}
/* Input groups */
.input-group {
/* #ifdef APP-PLUS */
margin-bottom: 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-bottom: 30rpx;
/* #endif */
}
.input-label {
/* #ifdef APP-PLUS */ font-size: 20rpx;
margin-bottom: 6rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
margin-bottom: 10rpx;
/* #endif */
font-weight: normal;
color: #333;
display: flex;
}
.input-field {
width: 100%;
/* #ifdef APP-PLUS */
height: 60rpx;
padding: 0 20rpx;
font-size: 22rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 90rpx;
padding: 0 30rpx;
font-size: 28rpx;
/* #endif */
border-radius: 10rpx;
border: 2rpx solid #ddd;
background-color: #f9f9f9;
box-sizing: border-box;
}
.input-error .input-field {
border-color: #f44336;
}
.error-text {
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-top: 4rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-top: 6rpx;
/* #endif */
color: #f44336;
}
/* Submit button */
.submit-button {
width: 100%;
/* #ifdef APP-PLUS */
height: 60rpx;
font-size: 24rpx;
margin: 12rpx 0;
border-radius: 30rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 90rpx;
font-size: 32rpx;
margin: 20rpx 0; border-radius: 45rpx;
/* #endif */
background-image: linear-gradient(to right, #2196f3, #03a9f4); color: #fff;
font-weight: normal;
text-align: center;
box-shadow: 0 10rpx 20rpx rgba(3, 169, 244, 0.2);
}
.submit-button:disabled {
background: #ccc;
box-shadow: none;
}
/* General error */
.general-error {
width: 100%;
text-align: center;
color: #f44336;
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-top: 12rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
margin-top: 20rpx;
/* #endif */
}
/* Login option */
.login-option {
display: flex;
justify-content: center;
/* #ifdef APP-PLUS */
margin-top: 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-top: 40rpx;
/* #endif */
}
.login-text {
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-right: 5rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
margin-right: 8rpx;
/* #endif */
color: #666;
}
.login-link {
/* #ifdef APP-PLUS */
font-size: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx; /* #endif */
color: #2196f3;
font-weight: normal;
}
/* Success container */
.success-container {
display: flex;
flex-direction: column;
align-items: center;
/* #ifdef APP-PLUS */
padding: 12rpx 0;
/* #endif */
/* #ifndef APP-PLUS */
padding: 20rpx 0;
/* #endif */
}
.success-icon {
/* #ifdef APP-PLUS */
width: 75rpx;
height: 75rpx;
font-size: 38rpx;
margin-bottom: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
width: 120rpx;
height: 120rpx;
font-size: 60rpx;
margin-bottom: 30rpx;
/* #endif */
background-color: #4caf50;
color: white;
/* #ifdef APP-PLUS */
border-radius: 75rpx;
/* #endif */
/* #ifndef APP-PLUS */
border-radius: 120rpx;
/* #endif */
display: flex;
align-items: center;
justify-content: center;
}
.success-title {
/* #ifdef APP-PLUS */
font-size: 24rpx;
margin-bottom: 12rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 36rpx;
margin-bottom: 20rpx;
/* #endif */
font-weight: bold;
color: #333;
}
.success-message {
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-bottom: 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 28rpx;
margin-bottom: 40rpx;
/* #endif */
color: #666;
text-align: center;
}
.back-button {
width: 100%;
/* #ifdef APP-PLUS */
height: 60rpx;
font-size: 24rpx;
border-radius: 30rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 90rpx;
font-size: 32rpx;
border-radius: 45rpx;
/* #endif */
background-color: #f0f0f0; color: #333;
font-weight: normal;
text-align: center;
}
</style>

656
mall/pages/user/login.uvue Normal file
View File

@@ -0,0 +1,656 @@
<template>
<view class="page" :style="cssVars">
<!-- Header仅保留左侧Logo -->
<view class="header">
<view class="header-left">
<image :src="logoUrl" mode="aspectFit" class="logo" />
</view>
</view>
<!-- Main -->
<view class="main">
<view class="card">
<!-- Left扫码区>=768显示 -->
<view class="left">
<text class="left-title">APP 扫码登录</text>
<view class="left-hint">
<text class="hint-text">打开 APP 扫一扫</text>
<text class="hint-link" @click="handleTutorial">查看教程</text>
</view>
<view class="qr-wrap">
<view class="qr">
<view class="qr-placeholder">
<text class="qr-text">二维码占位</text>
<text class="qr-sub">220×220</text>
</view>
</view>
</view>
</view>
<!-- Divider -->
<view class="divider"></view>
<!-- Right表单区 -->
<view class="right">
<view class="right-inner">
<!-- Tabs -->
<view class="tabs">
<view class="tab" :class="{ active: loginType === 0 }" @click="loginType = 0">
<text class="tab-text">密码登录</text>
<view v-if="loginType === 0" class="tab-line"></view>
</view>
<view class="tab" :class="{ active: loginType === 1 }" @click="loginType = 1">
<text class="tab-text">短信登录</text>
<view v-if="loginType === 1" class="tab-line"></view>
</view>
</view>
<!-- Form -->
<view class="form">
<template v-if="loginType === 0">
<view class="field">
<input
class="input"
type="text"
placeholder="账号名/手机号/邮箱"
:value="account"
@input="(e: any) => account = e.detail.value"
/>
</view>
<view class="field">
<input
class="input"
type="password"
placeholder="密码"
:value="password"
@input="(e: any) => password = e.detail.value"
/>
</view>
</template>
<template v-else>
<view class="field">
<input
class="input"
type="text"
placeholder="输入手机号码"
maxlength="11"
:value="account"
@input="(e: any) => account = e.detail.value"
/>
</view>
<view class="field code-row">
<input
class="input code-input"
type="text"
placeholder="填写验证码"
maxlength="6"
:value="captcha"
@input="(e: any) => captcha = e.detail.value"
/>
<view class="code-btn" :class="{ disabled: codeDisabled }" @click="getCode">
<text class="code-text">{{ codeText }}</text>
</view>
</view>
</template>
<!-- Button -->
<view class="btn" :class="{ disabled: isLoading }" @click="handleLogin">
<text class="btn-text">登录</text>
</view>
<!-- Actions一行横排 -->
<view class="actions">
<view class="action-item" @click="handleWechatLogin">
<view class="dot wechat"></view>
<text class="action-text">微信登录</text>
</view>
<text class="sep">|</text>
<view class="action-item" @click="handleQQLogin">
<view class="dot qq"></view>
<text class="action-text">QQ登录</text>
</view>
<text class="sep">|</text>
<text class="action-link" @click="handleForgotPassword">忘记密码</text>
<text class="sep">|</text>
<text class="action-link" @click="navigateToRegister">立即注册</text>
</view>
</view>
</view>
</view>
</view>
</view>
<!-- Footer -->
<view class="footer">
<text class="footer-text">Copyright ©2024 Mall. All Rights Reserved</text>
</view>
</view>
</template>
<script setup lang="uts">
import { ref, onMounted } from 'vue'
import supa from '@/components/supadb/aksupainstance.uts'
import { IS_TEST_MODE } from '@/ak/config.uts'
import { getCurrentUser, logout } from '@/utils/store.uts'
const cssVars = {
'--bg': '#f5f6f8',
'--card': '#ffffff',
'--brand': '#e1251b',
'--text': '#333333',
'--muted': '#666666',
'--muted2': '#999999',
'--border': '#eeeeee',
'--inputbg': '#f6f7f9',
'--shadow': '0 2px 12px rgba(0,0,0,0.06)'
}
const logoUrl = ref<string>('/static/logo.png')
const loginType = ref<number>(0)
const account = ref<string>('')
const password = ref<string>('')
const captcha = ref<string>('')
const isLoading = ref<boolean>(false)
const codeDisabled = ref<boolean>(false)
const codeText = ref<string>('获取验证码')
let codeTimer: number | null = null
const codeCountdown = ref<number>(0)
onMounted(() => {
try {
if (IS_TEST_MODE) return
const sessionInfo = supa.getSession()
if (sessionInfo != null && sessionInfo.user != null) {
const pages = getCurrentPages() as any[]
const currentPage = pages.length > 0 ? pages[pages.length - 1] : null
const opts = currentPage?.options as any
const redirect = opts?.redirect as string | null
if (redirect != null && redirect.length > 0) {
uni.redirectTo({ url: decodeURIComponent(redirect) })
} else {
uni.switchTab({ url: '/pages/mall/consumer/index' })
}
}
} catch (e) {
console.error('检查登录状态失败:', e)
}
})
const validateAccount = (): boolean => {
if (account.value.trim() === '') {
uni.showToast({ title: '请填写账号', icon: 'none' })
return false
}
if (loginType.value === 1) {
if (!/^1[3-9]\d{9}$/.test(account.value)) {
uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
return false
}
}
return true
}
const validatePassword = (): boolean => {
if (password.value.trim() === '') {
uni.showToast({ title: '请填写密码', icon: 'none' })
return false
}
if (password.value.length < 6) {
uni.showToast({ title: '密码长度不能少于6位', icon: 'none' })
return false
}
return true
}
const validateCaptcha = (): boolean => {
if (captcha.value.trim() === '') {
uni.showToast({ title: '请填写验证码', icon: 'none' })
return false
}
if (!/^\d{6}$/.test(captcha.value)) {
uni.showToast({ title: '请输入正确的验证码', icon: 'none' })
return false
}
return true
}
const getCode = async () => {
if (codeDisabled.value) return
if (!validateAccount()) return
uni.showToast({ title: '验证码已发送', icon: 'success' })
codeDisabled.value = true
codeCountdown.value = 60
codeText.value = `${codeCountdown.value}秒后重试`
codeTimer = setInterval(() => {
codeCountdown.value--
if (codeCountdown.value > 0) {
codeText.value = `${codeCountdown.value}秒后重试`
} else {
codeDisabled.value = false
codeText.value = '获取验证码'
if (codeTimer != null) {
clearInterval(codeTimer)
codeTimer = null
}
}
}, 1000) as unknown as number
}
const handleLogin = async () => {
if (!validateAccount()) return
// 特殊账号处理admin/admin 直接跳转
if (account.value === 'admin' && password.value === 'admin') {
setIsLoggedIn(true)
const adminProfile = {
id: 'admin',
username: 'Admin',
email: 'admin@mall.com',
gender: 'unknown',
birthday: '',
height_cm: 0,
weight_kg: 0,
bio: 'Administrator',
avatar_url: '/static/logo.png',
preferred_language: 'zh-CN',
role: 'admin',
school_id: '',
grade_id: '',
class_id: ''
} as UserProfile
setUserProfile(adminProfile)
uni.showToast({ title: '管理员登录成功', icon: 'success' })
setTimeout(() => {
uni.switchTab({ url: '/pages/mall/consumer/index' })
}, 500)
return
}
if (loginType.value === 0) {
if (!validatePassword()) return
} else {
if (!validateCaptcha()) return
}
isLoading.value = true
try {
logout()
if (loginType.value === 0) {
const isEmail = account.value.includes('@')
if (isEmail) {
// 邮箱 + 密码登录Supabase Auth
const result = await supa.signIn(account.value.trim(), password.value)
console.log('signIn result:', result)
// 检查登录是否失败
if (result.user == null) {
// 检查是否是邮箱未确认的错误
const rawData = result.raw as UTSJSONObject
const errorMsg = rawData?.getString('msg') ?? ''
const errorCode = rawData?.getString('error_code') ?? ''
if (errorMsg.includes('email') && errorMsg.includes('confirm') ||
errorCode === 'email_not_confirmed' ||
errorMsg.includes('邮箱') && errorMsg.includes('确认')) {
throw new Error('邮箱未确认,请先检查邮箱并点击确认链接')
} else if (errorMsg.includes('Invalid login credentials') ||
errorCode === 'invalid_credentials') {
throw new Error('邮箱或密码错误')
} else {
throw new Error(errorMsg || '登录失败,请重试')
}
}
} else {
uni.showToast({ title: '手机号密码登录功能开发中', icon: 'none' })
return
}
} else {
uni.showToast({ title: '手机验证码登录功能开发中', icon: 'none' })
return
}
// 尝试获取/补全用户资料,但失败时不再阻塞登录
try {
const profile = await getCurrentUser()
console.log('current user profile:', profile)
} catch (e) {
console.error('获取用户信息失败(忽略,不阻塞登录):', e)
}
// 显式保存用户ID到本地存储确保页面刷新或重启后 SupabaseService 能恢复身份
const currentSession = supa.getSession()
if (currentSession.user != null) {
const uid = currentSession.user?.getString('id')
if (uid != null) {
uni.setStorageSync('user_id', uid)
console.log('用户ID已保存到本地存储:', uid)
}
}
uni.showToast({ title: '登录成功', icon: 'success' })
// if (!IS_TEST_MODE) {
setTimeout(() => {
const pages = getCurrentPages() as any[]
const currentPage = pages.length > 0 ? pages[pages.length - 1] : null
const opts = currentPage?.options as any
const redirect = opts?.redirect as string | null
if (redirect != null && redirect.length > 0) {
uni.redirectTo({ url: decodeURIComponent(redirect) })
} else {
uni.switchTab({ url: '/pages/mall/consumer/index' })
}
}, 500)
// }
} catch (err) {
console.error('登录错误:', err)
let msg = '登录失败,请重试'
if (err != null && typeof err === 'object') {
const e = err as Error
if (e.message != null && e.message.trim() !== '') msg = e.message
}
uni.showToast({ title: msg, icon: 'none' })
} finally {
isLoading.value = false
}
}
const navigateToRegister = () => {
const pages = getCurrentPages() as any[]
const currentPage = pages.length > 0 ? pages[pages.length - 1] : null
const opts = currentPage?.options as any
const redirect = opts?.redirect as string | null
if (redirect != null && redirect.length > 0) {
uni.navigateTo({
url: `/pages/user/register?redirect=${redirect}`
})
} else {
uni.navigateTo({
url: '/pages/user/register'
})
}
}
const handleTutorial = () => uni.showToast({ title: '扫码教程开发中', icon: 'none' })
const handleForgotPassword = () => uni.showToast({ title: '忘记密码开发中', icon: 'none' })
const handleWechatLogin = () => uni.showToast({ title: '微信登录开发中', icon: 'none' })
const handleQQLogin = () => uni.showToast({ title: 'QQ登录开发中', icon: 'none' })
</script>
<style scoped>
/* Base */
.page{
min-height: 100vh;
display: flex;
flex-direction: column;
background: var(--bg);
}
/* Header */
.header{
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
padding: 30px 72px;
}
.logo{
width: 300px;
height: 80px;
}
/* Main */
.main{
flex: 1;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
padding: 28px 18px;
}
/* Card */
.card{
width: min(980px, 92vw);
min-height: 460px;
background: var(--card);
border-radius: 16px;
box-shadow: var(--shadow);
padding: 40px;
display: flex;
flex-direction: row;
gap: 32px;
}
/* Left */
.left{
flex: 0 0 52%;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
padding-left: 18px;
}
.left-title{
font-size: 18px;
font-weight: 600;
color: var(--text);
margin-bottom: 10px;
}
.left-hint{
display: flex;
flex-direction: row;
align-items: center;
gap: 14px;
margin-bottom: 18px;
}
.hint-text{ font-size: 13px; color: var(--muted); }
.hint-link{ font-size: 13px; color: var(--brand); }
.qr-wrap{
width: 100%;
display: flex;
flex-direction: row;
justify-content: flex-start;
}
.qr{
width: 240px;
height: 240px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.qr-placeholder{
width: 220px;
height: 220px;
border: 1px solid #e6e6e6;
border-radius: 8px;
background: #fff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
}
.qr-text{ font-size: 14px; color: var(--muted); }
.qr-sub{ font-size: 12px; color: var(--muted2); }
/* Divider */
.divider{
width: 1px;
background: var(--border);
flex-shrink: 0;
}
/* Right */
.right{
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
}
.right-inner{
width: 360px; /* 京东右侧“窄列”观感 */
max-width: 100%;
margin-left: auto; /* 靠右 */
}
/* Tabs */
.tabs{
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
gap: 24px;
margin-bottom: 18px;
}
.tab{
position: relative;
padding: 8px 2px;
}
.tab-text{
font-size: 16px;
color: var(--muted);
}
.tab.active .tab-text{
color: var(--brand);
font-weight: 600;
}
.tab-line{
position: absolute;
left: 0;
right: 0;
bottom: -6px;
height: 2px;
background: var(--brand);
border-radius: 2px;
}
/* Form */
.form{ margin-top: 10px; }
.field{ margin-bottom: 14px; }
.input{
width: 100%;
height: 44px;
border-radius: 10px;
background: var(--inputbg);
padding: 0 14px;
font-size: 14px;
color: var(--text);
box-sizing: border-box;
}
/* Code row */
.code-row{
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
}
.code-input{ flex: 1; }
.code-btn{
height: 44px;
padding: 0 12px;
border-radius: 10px;
background: #fff;
border: 1px solid #eee;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.code-btn.disabled{ opacity: 0.5; }
.code-text{ font-size: 13px; color: var(--brand); }
/* Button */
.btn{
margin-top: 16px;
height: 46px;
border-radius: 10px;
background: rgba(225, 37, 27, 0.45);
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.btn.disabled{ background: #d9d9d9; }
.btn-text{
color: #fff;
font-size: 16px;
font-weight: 600;
}
/* Actions一行横排 */
.actions{
margin-top: 16px;
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
gap: 12px;
flex-wrap: nowrap;
}
.action-item{
display: flex;
flex-direction: row;
align-items: center;
gap: 8px;
}
.dot{
width: 16px;
height: 16px;
border-radius: 50%;
}
.dot.wechat{ background: #19be6b; }
.dot.qq{ background: #2d8cf0; }
.action-text{ font-size: 13px; color: var(--muted); }
.action-link{ font-size: 13px; color: var(--muted); }
.sep{ font-size: 13px; color: #e0e0e0; }
/* Footer */
.footer{
padding: 18px 0 28px;
display: flex;
flex-direction: row;
justify-content: center;
}
.footer-text{ font-size: 12px; color: var(--muted2); }
/* ===== 自适应:断点全部用 px避免 rpx 在宽屏放大) ===== */
@media screen and (max-width: 1024px){
.header{ padding: 24px 20px; }
.logo{ width: 240px; height: 68px; }
.card{ width: 92vw; padding: 28px; gap: 22px; }
.right-inner{ width: 360px; }
}
@media screen and (max-width: 768px){
.card{ flex-direction: column; min-height: auto; }
.left{ display: none; }
.divider{ display: none; }
.right-inner{ width: 100%; margin-left: 0; }
.actions{ flex-wrap: wrap; }
}
@media screen and (max-width: 520px){
.sep{ display: none; }
}
</style>

690
mall/pages/user/loginn.uvue Normal file
View File

@@ -0,0 +1,690 @@
<template>
<view class="page-wrapper">
<scroll-view class="login-container" scroll-y="true" show-scrollbar="false">
<!-- Language switch button -->
<view class="language-switch">
<button class="language-btn" @click="toggleLanguage">
{{ currentLocale === 'zh-CN' ? 'EN' : '中' }}
</button>
</view>
<!-- Unified content container -->
<view class="content-wrapper">
<!-- Logo section -->
<view class="logo-section">
<text class="app-title">Trainning Monitor</text>
<text class="page-title">{{ $t('user.login.title') }}</text>
<text class="page-subtitle">{{ $t('user.login.subtitle') }}</text>
</view>
<!-- Form container -->
<view class="form-container">
<form @submit="onSubmit">
<!-- Email input -->
<view class="input-group" :class="{ 'input-error': emailError }">
<text class="input-label">{{ $t('user.login.email') }}</text>
<input class="input-field" name="email" type="text" :value="email"
:placeholder="$t('user.login.email_placeholder')" @blur="validateEmail" />
<text v-if="emailError" class="error-text">{{ emailError }}</text>
</view>
<!-- Password input -->
<view class="input-group" :class="{ 'input-error': passwordError }">
<text class="input-label">{{ $t('user.login.password') }}</text>
<view class="password-input-container">
<input class="input-field" name="password" :type="showPassword ? 'text' : 'password'"
:value="password" :placeholder="$t('user.login.password_placeholder')"
@blur="validatePassword" />
<view class="password-toggle" @click="showPassword = !showPassword">
<text class="toggle-icon">{{ showPassword ? '👁' : '🙈' }}</text>
</view>
</view>
<text v-if="passwordError" class="error-text">{{ passwordError }}</text>
</view>
<!-- Additional options -->
<view class="options-row">
<view class="remember-me">
<checkbox value="rememberMe" color="#2196f3" />
<text class="remember-me-text">{{ $t('user.login.remember_me') }}</text>
</view>
<text class="forgot-password" @click="navigateToForgotPassword">
{{ $t('user.login.forgot_password') }}
</text>
</view>
<!-- Login button -->
<button form-type="submit" class="login-button" :disabled="isLoading" :loading="isLoading">
{{ $t('user.login.login_button') }}
</button>
<!-- General error message -->
<text v-if="generalError" class="general-error">{{ generalError }}</text>
</form>
<!-- Social login options -->
<view class="social-login">
<text class="social-login-text">{{ $t('user.login.or_login_with') }}</text>
<view class="social-buttons">
<button class="social-button wechat" @click="socialLogin('WeChat')">
<text class="social-icon">🟩</text>
</button>
<button class="social-button qq" @click="socialLogin('QQ')">
<text class="social-icon">🔵</text>
</button>
<button class="social-button sms" @click="socialLogin('SMS')">
<text class="social-icon">✉️</text>
</button>
</view>
</view>
<!-- Register option -->
<view class="register-option">
<text class="register-text">{{ $t('user.login.no_account') }}</text>
<text class="register-link"
@click="navigateToRegister">{{ $t('user.login.register_now') }}</text>
</view>
</view>
</view>
</scroll-view>
</view>
</template>
<script lang="uts">
import {HOME_REDIRECT,TABORPAGE} from '@/ak/config.uts'
import type { AkReqOptions, AkReqResponse, AkReqError } from '@/uni_modules/ak-req/index.uts';
import supa from '@/components/supadb/aksupainstance.uts';
import { getCurrentUser, logout } from '@/utils/store.uts';
import { switchLocale, getCurrentLocale } from '@/utils/utils.uts';
export default {
data() {
return {
// email: "akoo@163.com",
// password: "Hf2152111",
email: "am@163.com",
password: "kookoo",
emailError: "",
passwordError: "",
generalError: "",
isLoading: false,
showPassword: false,
rememberMe: false,
currentLocale: getCurrentLocale()
};
},
onLoad() {
// Try to restore saved email if "remember me" was selected
// this.tryRestoreEmail();
console.log('akkkk')
}, methods: {
toggleLanguage() {
const newLocale = this.currentLocale === 'zh-CN' ? 'en-US' : 'zh-CN';
switchLocale(newLocale);
this.currentLocale = newLocale;
uni.showToast({
title: this.$t('user.login.language_switched'),
icon: 'success'
});
}, tryRestoreEmail() {
try {
const savedEmail = uni.getStorageSync('rememberEmail') as string;
if (savedEmail.trim() !== "") {
this.email = savedEmail;
this.rememberMe = true;
}
} catch (e) {
console.error("Error restoring email:", e);
}
},
onSubmit(e : UniFormSubmitEvent) {
this.handleLogin();
},
validateEmail() {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (this.email.trim() === "") {
this.emailError = this.$t('user.login.email_required');
return false;
} else if (!emailRegex.test(this.email)) {
this.emailError = this.$t('user.login.email_invalid');
return false;
} else {
this.emailError = '';
return true;
}
}, validatePassword() {
if (this.password.trim() === "") {
this.passwordError = this.$t('user.login.password_required');
return false;
} else if (this.password.length < 6) {
this.passwordError = this.$t('user.login.password_too_short');
return false;
} else {
this.passwordError = '';
return true;
}
},
validateForm() {
const emailValid = this.validateEmail();
const passwordValid = this.validatePassword();
return emailValid && passwordValid;
},
async handleLogin() {
this.generalError = '';
// 清除旧用户数据
logout();
if (!this.validateForm()) {
return;
}
this.isLoading = true;
try {
// Save email if remember me is checked
if (this.rememberMe) {
uni.setStorageSync('rememberEmail', this.email);
} else {
uni.removeStorageSync('rememberEmail');
} // Call signin method from Supabase
const result = await supa.signIn(
this.email,
this.password);
if (result.user !== null) {
// 获取并更新当前用户,确保数据已生效
const profile = await getCurrentUser();
if (profile==null) throw new Error(this.$t('user.login.profile_update_failed'));
// 登录成功提示
uni.showToast({ title: this.$t('user.login.login_success'), icon: 'success' });
// 跳转至运动页面
if(TABORPAGE)
{
uni.switchTab({ url: HOME_REDIRECT });
}
else{
uni.navigateTo({ url: HOME_REDIRECT });
}
return;
} else {
throw new Error(this.$t('user.login.login_failed'));
}
} catch (err) {
console.error("Login error:", err);
// Show error dialog to user
let errorMessage = this.$t('user.login.login_failed');
if (err !== null && typeof err === 'object') {
const error = err as Error;
if (error.message !== null && error.message.trim() !== '') {
errorMessage = error.message;
}
}
uni.showModal({
title: this.$t('user.login.error_title'),
content: errorMessage,
showCancel: false,
confirmText: this.$t('user.login.confirm'),
success: () => {
// Clear any existing error states
this.generalError = '';
this.emailError = '';
this.passwordError = '';
}
});
} finally {
this.isLoading = false;
}
},
socialLogin(provider : string) {
// This would be implemented to handle OAuth login with different providers
uni.showToast({
title: `${provider} ${this.$t('user.login.coming_soon')}`,
icon: 'none'
});
},
navigateToRegister() {
uni.navigateTo({
url: '/pages/user/register'
});
},
navigateToForgotPassword() {
uni.navigateTo({
url: '/pages/user/forgot-password'
});
}
}
};
</script>
<style>
/* Page wrapper for full screen */
.page-wrapper {
width: 100%;
}
.login-container {
width: 100%;
background-image: linear-gradient(to bottom right, #f8f9fa, #e9ecef);
}
/* Content wrapper - single scrollable container */
.content-wrapper {
width: 100%;
/* #ifdef APP-PLUS */
padding: 20rpx 15rpx;
min-height: 800rpx;
/* #endif */
/* #ifndef APP-PLUS */
padding: 30rpx 25rpx;
min-height: 1000rpx;
/* #endif */
display: flex;
flex-direction: column;
align-items: center;
box-sizing: border-box;
}
/* Language switch button - adjusted for single container */
.language-switch {
position: absolute;
/* #ifdef APP-PLUS */
top: 30rpx;
right: 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
top: 40rpx;
right: 35rpx;
/* #endif */
z-index: 100;
}
.language-btn {
/* #ifdef APP-PLUS */
width: 50rpx;
height: 50rpx;
border-radius: 25rpx;
font-size: 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
width: 70rpx;
height: 70rpx;
border-radius: 35rpx;
font-size: 24rpx;
/* #endif */
background-color: rgba(33, 150, 243, 0.8);
color: #fff;
font-weight: normal;
border: 1rpx solid rgba(255, 255, 255, 0.3);
text-align: center;
box-shadow: 0 3rpx 10rpx rgba(33, 150, 243, 0.3);
}
/* Logo section - very compact */
.logo-section {
display: flex;
flex-direction: column;
align-items: center;
/* #ifdef APP-PLUS */
margin: 15rpx 0 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin: 25rpx 0 30rpx;
/* #endif */
}
.app-title {
/* #ifdef APP-PLUS */
font-size: 28rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 36rpx;
/* #endif */
font-weight: bold;
color: #2196f3;
}
.page-title {
/* #ifdef APP-PLUS */
font-size: 32rpx;
margin-top: 8rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 48rpx;
margin-top: 15rpx;
/* #endif */
font-weight: bold;
color: #333;
}
.page-subtitle {
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-top: 4rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-top: 8rpx;
/* #endif */
color: #666;
}
/* Form container - optimized for tablets */
.form-container {
width: 100%;
/* #ifdef APP-PLUS */
max-width: 620rpx;
padding: 18rpx;
margin: 0 auto;
/* #endif */
/* #ifndef APP-PLUS */
max-width: 560rpx;
padding: 32rpx;
margin: 0 auto;
/* #endif */
background-color: #ffffff;
border-radius: 12rpx;
box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
box-sizing: border-box;
}
/* Input groups - more compact */
.input-group {
/* #ifdef APP-PLUS */
margin-bottom: 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-bottom: 25rpx;
/* #endif */
}
.input-label {
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-bottom: 6rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 26rpx;
margin-bottom: 8rpx;
/* #endif */
font-weight: normal;
color: #333;
display: block;
}
.input-field {
width: 100%;
/* #ifdef APP-PLUS */
height: 60rpx;
padding: 0 20rpx;
font-size: 22rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 80rpx;
padding: 0 25rpx;
font-size: 26rpx;
/* #endif */
border-radius: 8rpx;
border: 2rpx solid #ddd;
background-color: #f9f9f9;
box-sizing: border-box;
}
.input-error .input-field {
border-color: #f44336;
}
.error-text {
/* #ifdef APP-PLUS */
font-size: 20rpx;
margin-top: 5rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-top: 6rpx;
/* #endif */
color: #f44336;
}
/* Password input */
.password-input-container {
position: relative;
}
.password-toggle {
position: absolute;
/* #ifdef APP-PLUS */
right: 12rpx;
top: 16rpx;
/* #endif */
/* #ifndef APP-PLUS */
right: 18rpx;
top: 22rpx;
/* #endif */
z-index: 1;
}
.toggle-icon {
/* #ifdef APP-PLUS */
font-size: 20rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 26rpx;
/* #endif */
color: #666;
}
/* Options row - more compact */
.options-row {
display: flex;
justify-content: flex-start;
align-items: center;
flex-direction: row;
/* #ifdef APP-PLUS */
margin: 10rpx 0 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin: 15rpx 0 25rpx;
/* #endif */
}
.remember-me {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
}
.remember-me-text {
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-left: 6rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-left: 8rpx;
/* #endif */
color: #666;
}
.forgot-password {
/* #ifdef APP-PLUS */
font-size: 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
/* #endif */
color: #2196f3;
}
/* Login button - more compact */
.login-button {
width: 100%;
/* #ifdef APP-PLUS */
height: 60rpx;
font-size: 24rpx;
margin: 12rpx 0;
border-radius: 30rpx;
/* #endif */
/* #ifndef APP-PLUS */
height: 80rpx;
font-size: 30rpx;
margin: 18rpx 0; border-radius: 40rpx;
/* #endif */
background-image: linear-gradient(to right, #2196f3, #03a9f4);
color: #fff;
font-weight: normal;
text-align: center;
box-shadow: 0 8rpx 16rpx rgba(3, 169, 244, 0.2);
}
.login-button:disabled {
background: #ccc;
box-shadow: none;
}
/* General error */
.general-error {
width: 100%;
text-align: center;
color: #f44336;
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-top: 10rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-top: 15rpx;
/* #endif */
}
/* Social login - very compact */
.social-login {
/* #ifdef APP-PLUS */
margin-top: 15rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-top: 25rpx;
/* #endif */
display: flex;
flex-direction: column;
align-items: center;
}
.social-login-text {
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-bottom: 10rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-bottom: 15rpx;
/* #endif */
color: #666;
}
.social-buttons {
display: flex;
flex-direction: row;
justify-content: center;
}
.social-buttons .social-button {
/* #ifdef APP-PLUS */
margin-left: 10rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-left: 12rpx;
/* #endif */
}
.social-buttons .social-button:first-child {
margin-left: 0;
}
.social-button {
/* #ifdef APP-PLUS */
width: 50rpx;
height: 50rpx;
border-radius: 25rpx;
/* #endif */
/* #ifndef APP-PLUS */
width: 70rpx;
height: 70rpx;
border-radius: 35rpx;
/* #endif */
text-align: center;
}
.social-icon {
/* #ifdef APP-PLUS */
font-size: 24rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 32rpx;
/* #endif */
color: #fff;
}
.google {
background-color: #db4437;
}
.facebook {
background-color: #4267B2;
}
.apple {
background-color: #000;
}
.wechat {
background-color: #1aad19;
}
.qq {
background-color: #498ad5;
}
.sms {
background-color: #ffb300;
}
/* Register option - compact */
.register-option {
display: flex;
justify-content: center;
/* #ifdef APP-PLUS */
margin-top: 15rpx;
margin-bottom: 5rpx;
/* #endif */
/* #ifndef APP-PLUS */
margin-top: 25rpx;
margin-bottom: 10rpx;
/* #endif */
}
.register-text {
/* #ifdef APP-PLUS */
font-size: 18rpx;
margin-right: 4rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
margin-right: 6rpx;
/* #endif */
color: #666;
}
.register-link {
/* #ifdef APP-PLUS */
font-size: 18rpx;
/* #endif */
/* #ifndef APP-PLUS */
font-size: 24rpx;
/* #endif */
color: #2196f3;
font-weight: normal;
}
</style>

1070
mall/pages/user/profile.uvue Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,538 @@
<template>
<view class="register-wrapper">
<!-- Header Logo -->
<view class="header">
<image :src="logoUrl" mode="aspectFit" class="logo" />
</view>
<!-- 注册表单区域 -->
<view class="register-box">
<view class="title">注册账号</view>
<!-- 注册表单 -->
<view class="form-content">
<!-- 邮箱 -->
<view class="input-group">
<view class="input-wrapper">
<image src="/static/user/phone_1.png" class="input-icon" />
<input
type="text"
placeholder="输入邮箱"
:value="email"
@input="(e: any) => email = e.detail.value"
class="input-field"
/>
</view>
</view>
<!-- 密码 -->
<view class="input-group">
<view class="input-wrapper">
<image src="/static/user/code_1.png" class="input-icon" />
<input
type="password"
placeholder="填写密码"
:value="password"
@input="(e: any) => password = e.detail.value"
class="input-field"
/>
</view>
</view>
<!-- 确认密码 -->
<view class="input-group">
<view class="input-wrapper">
<image src="/static/user/code_1.png" class="input-icon" />
<input
type="password"
placeholder="确认密码"
:value="confirmPassword"
@input="(e: any) => confirmPassword = e.detail.value"
class="input-field"
/>
</view>
</view>
</view>
<!-- 注册按钮 -->
<view class="register-btn" @click="handleRegister" :class="{ 'disabled': isLoading }">
注册
</view>
<!-- 已有账号 -->
<view class="tips">
<text class="tips-text">已有账号?</text>
<text class="tips-link" @click="navigateToLogin">立即登录</text>
</view>
<!-- 协议勾选 -->
<view class="protocol">
<checkbox-group @change="handleProtocolChange">
<checkbox
:checked="protocol"
:class="{ 'trembling': inAnimation }"
@animationend="inAnimation = false"
/>
<text class="protocol-text">
已阅读并同意
<text class="main-color" @click="navigateToTerms(3)">《用户协议》</text>
<text class="main-color" @click="navigateToTerms(4)">《隐私协议》</text>
</text>
</checkbox-group>
</view>
</view>
<!-- 底部版权信息 -->
<view class="footer">
<text class="footer-text">Copyright ©2024 Mall. All Rights Reserved</text>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import supa from '@/components/supadb/aksupainstance.uts'
import { ensureUserProfile } from '@/utils/sapi.uts'
// 响应式数据
const email = ref<string>('')
const password = ref<string>('')
const confirmPassword = ref<string>('')
const protocol = ref<boolean>(false)
const inAnimation = ref<boolean>(false)
const isLoading = ref<boolean>(false)
const logoUrl = ref<string>('/static/logo.png')
// 处理协议勾选变化
const handleProtocolChange = (e: any) => {
protocol.value = !protocol.value
}
// 验证邮箱
const validateEmail = (): boolean => {
if (email.value.trim() === '') {
uni.showToast({
title: '请填写邮箱',
icon: 'none'
})
return false
}
// 基础邮箱格式校验(足够用于前端提示)
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
uni.showToast({
title: '请输入正确的邮箱',
icon: 'none'
})
return false
}
return true
}
// 验证密码
const validatePassword = (): boolean => {
if (password.value.trim() === '') {
uni.showToast({
title: '请填写密码',
icon: 'none'
})
return false
}
if (password.value.length < 6) {
uni.showToast({
title: '密码长度不能少于6位',
icon: 'none'
})
return false
}
// 密码不能过于简单
if (/^([0-9]|[a-z]|[A-Z]){0,6}$/i.test(password.value)) {
uni.showToast({
title: '您输入的密码过于简单',
icon: 'none'
})
return false
}
return true
}
// 验证确认密码
const validateConfirmPassword = (): boolean => {
if (confirmPassword.value.trim() === '') {
uni.showToast({
title: '请确认密码',
icon: 'none'
})
return false
}
if (confirmPassword.value !== password.value) {
uni.showToast({
title: '两次输入的密码不一致',
icon: 'none'
})
return false
}
return true
}
// 处理注册
const handleRegister = async () => {
// 检查协议
if (!protocol.value) {
inAnimation.value = true
uni.showToast({
title: '请先阅读并同意协议',
icon: 'none'
})
return
}
// 表单验证
if (!validateEmail()) {
return
}
if (!validatePassword()) {
return
}
if (!validateConfirmPassword()) {
return
}
isLoading.value = true
try {
// 使用 Supabase Auth邮箱 + 密码注册
const result = await supa.signUp(email.value.trim(), password.value)
console.log('📝 注册返回结果:', result)
console.log('📝 注册返回结果JSON:', JSON.stringify(result))
// 检查是否有错误(邮件发送失败等)
const errorCode = result?.getString('error_code') ?? ''
const errorMsg = result?.getString('msg') ?? ''
const code = result?.getNumber('code') ?? 0
console.log('📝 错误代码:', errorCode, '错误信息:', errorMsg, '状态码:', code)
// 如果返回 500 错误且是邮件发送失败,但用户可能已创建
if (code === 500 && (errorCode === 'unexpected_failure' || errorMsg.includes('confirmation email'))) {
console.warn('⚠️ 邮件发送失败,但用户可能已创建,尝试获取用户信息')
// 即使邮件发送失败,用户可能已经在 auth.users 中创建
// 这里我们仍然尝试创建用户资料
}
// signUp 返回的是 UTSJSONObjectSupabase signup API 返回结构:
// { user: {...}, session: {...} } - 如果邮箱验证未开启
// { user: {...} } - 如果邮箱验证已开启(需要验证邮箱后才能登录)
// { code: 500, error_code: ..., msg: ... } - 如果发生错误(但用户可能已创建)
let user: UTSJSONObject | null = null
let hasSession = false
if (result != null) {
// 尝试获取 user 字段
const userField = result.getJSON('user')
if (userField != null) {
user = userField
console.log('✅ 找到 user 字段:', user.getString('id'), user.getString('email'))
} else {
// 如果没有 user 字段,可能 result 本身就是 user 对象
const id = result.getString('id')
if (id != null && id !== '') {
user = result
console.log('✅ result 本身就是 user 对象:', id)
} else {
console.warn('⚠️ 未找到 user 信息,检查所有字段:', Object.keys(result.toMap() || {}))
}
}
// 检查是否有 session表示注册后自动登录成功
const sessionField = result.getJSON('session')
if (sessionField != null) {
hasSession = true
console.log('✅ 找到 session已自动登录')
// 如果有 session说明已经自动登录token 应该已经设置
// 此时可以直接创建用户资料
} else {
console.log(' 未找到 session可能需要邮箱验证')
}
}
// 如果返回错误且没有用户信息,说明注册失败
if (user == null && code !== 0 && code !== 200) {
// 如果是邮件发送失败,给出明确的错误提示
if (code === 500 && errorMsg.includes('confirmation email')) {
throw new Error('注册失败:邮件服务配置错误,请联系管理员或修改 Supabase 配置(设置 ENABLE_EMAIL_AUTOCONFIRM=true')
} else {
throw new Error(errorMsg || '注册失败,请重试')
}
}
// 如果获取到 user尝试创建业务侧用户资料ak_users
if (user != null) {
try {
const profileResult = await ensureUserProfile(user)
if (profileResult != null) {
console.log('✅ 用户资料创建成功:', profileResult.id)
} else {
console.warn('⚠️ 用户资料创建失败,但注册已成功')
// 如果创建失败,可能是因为 RLS 策略限制
// 建议用户登录后再自动创建(在 getCurrentUser 中处理)
}
} catch (profileError) {
console.error('❌ 创建用户资料异常:', profileError)
// 即使创建资料失败,也不阻止注册流程
// 用户登录时会自动创建(见 utils/store.uts 的 getCurrentUser
}
} else {
console.warn('⚠️ 注册成功但未获取到用户信息')
// 可能需要邮箱验证,用户验证邮箱后登录时会自动创建资料
}
// 如果注册后没有自动登录(需要邮箱验证),提示用户
if (!hasSession && user != null) {
console.log(' 需要邮箱验证,验证后登录时会自动创建用户资料')
}
uni.showToast({
title: '注册成功',
icon: 'success'
})
setTimeout(() => {
uni.redirectTo({
url: '/pages/user/login'
})
}, 1500)
} catch (err) {
console.error('注册错误:', err)
let errorMessage = '注册失败,请重试'
if (err != null && typeof err === 'object') {
const error = err as Error
if (error.message != null && error.message.trim() !== '') {
errorMessage = error.message
// 如果是邮件发送失败,给出更友好的提示
if (error.message.includes('confirmation email') || error.message.includes('邮件')) {
errorMessage = '注册可能成功,但邮件发送失败,请稍后尝试登录'
}
}
}
uni.showToast({
title: errorMessage,
icon: 'none',
duration: 3000
})
} finally {
isLoading.value = false
}
}
// 跳转到登录页
const navigateToLogin = () => {
const pages = getCurrentPages() as any[]
const currentPage = pages.length > 0 ? pages[pages.length - 1] : null
const opts = currentPage?.options as any
const redirect = opts?.redirect as string | null
if (redirect != null && redirect.length > 0) {
uni.navigateTo({
url: `/pages/user/login?redirect=${redirect}`
})
} else {
uni.navigateTo({
url: '/pages/user/login'
})
}
}
// 跳转到协议页面
const navigateToTerms = (type: number) => {
uni.navigateTo({
url: `/pages/user/terms?type=${type}`
})
}
</script>
<style>
page {
background: #F5F5F5;
}
.register-wrapper {
min-height: 100vh;
display: flex;
flex-direction: column;
background: #F5F5F5;
}
/* Header Logo */
.header {
padding: 40rpx 0 0 60rpx;
background: #F5F5F5;
}
.logo {
width: 200rpx;
height: 80rpx;
}
/* 注册表单区域 */
.register-box {
flex: 1;
background: #FFFFFF;
margin: 60rpx 40rpx 0;
border-radius: 8rpx;
padding: 60rpx 50rpx 40rpx;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}
.title {
font-size: 40rpx;
font-weight: 600;
color: #333333;
text-align: center;
margin-bottom: 50rpx;
}
/* 表单内容 */
.form-content {
margin-bottom: 40rpx;
}
.input-group {
margin-bottom: 30rpx;
}
.input-wrapper {
position: relative;
display: flex;
align-items: center;
padding: 0 20rpx;
height: 88rpx;
border: 1rpx solid #E0E0E0;
border-radius: 4rpx;
background: #FFFFFF;
}
.input-wrapper:focus-within {
border-color: var(--view-theme, #FF4D4F);
}
.input-icon {
width: 32rpx;
height: 32rpx;
flex-shrink: 0;
margin-right: 20rpx;
}
.input-field {
flex: 1;
font-size: 28rpx;
height: 100%;
color: #333333;
}
.code-input {
flex: 1;
}
.code-btn {
position: absolute;
right: 20rpx;
top: 50%;
transform: translateY(-50%);
color: var(--view-theme, #FF4D4F);
font-size: 26rpx;
background: transparent;
border: none;
padding: 0;
line-height: 1;
}
.code-btn.disabled {
color: #999999;
}
/* 注册按钮 */
.register-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 88rpx;
margin-top: 50rpx;
background: linear-gradient(135deg, #FF4D4F 0%, #FF7A45 100%);
border-radius: 4rpx;
color: #FFFFFF;
font-size: 32rpx;
font-weight: 500;
box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.3);
}
.register-btn.disabled {
background: #D9D9D9;
box-shadow: none;
opacity: 0.6;
}
/* 已有账号提示 */
.tips {
margin-top: 30rpx;
text-align: center;
}
.tips-text {
font-size: 28rpx;
color: #666666;
}
.tips-link {
font-size: 28rpx;
color: var(--view-theme, #FF4D4F);
margin-left: 8rpx;
}
/* 协议区域 */
.protocol {
margin-top: 40rpx;
display: flex;
align-items: center;
justify-content: center;
}
.protocol checkbox {
margin-right: 10rpx;
}
.protocol-text {
font-size: 24rpx;
color: #999999;
}
.main-color {
color: var(--view-theme, #FF4D4F);
}
.trembling {
animation: shake 0.6s;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-10rpx); }
20%, 40%, 60%, 80% { transform: translateX(10rpx); }
}
/* 底部版权 */
.footer {
padding: 40rpx 0;
text-align: center;
background: #F5F5F5;
}
.footer-text {
font-size: 22rpx;
color: #999999;
}
</style>

131
mall/pages/user/terms.uvue Normal file
View File

@@ -0,0 +1,131 @@
<template>
<view class="page">
<view class="topbar">
<text class="back" @click="goBack">返回</text>
<text class="title">用户协议与隐私政策</text>
<text class="ghost"> </text>
</view>
<scroll-view class="content" scroll-y="true" show-scrollbar="false">
<view class="card">
<text class="h1">用户协议</text>
<text class="p">1. 本应用为商城系统示例/项目使用。
</text>
<text class="p">2. 你在使用本应用服务时,应遵守法律法规与平台规则。
</text>
<text class="p">3. 账号与密码由你自行保管,因泄露造成的损失由你自行承担。
</text>
<view class="divider"></view>
<text class="h1">隐私政策</text>
<text class="p">1. 我们可能会收集你提供的邮箱等信息,用于账号注册与登录。
</text>
<text class="p">2. 我们会采取合理的安全措施保护你的信息安全。
</text>
<text class="p">3. 你可以在账号相关页面申请修改或删除个人信息(以实际功能为准)。
</text>
</view>
<view class="footer">
<button class="primary" @click="goBack">我已阅读并同意</button>
</view>
</scroll-view>
</view>
</template>
<script lang="uts">
export default {
methods: {
goBack() {
uni.navigateBack();
}
}
};
</script>
<style>
.page {
min-height: 100vh;
background: #f7f8fa;
display: flex;
flex-direction: column;
}
.topbar {
height: 96rpx;
padding: 0 24rpx;
background: rgba(255, 255, 255, 0.96);
border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
display: flex;
align-items: center;
justify-content: space-between;
}
.back {
font-size: 26rpx;
color: #ff4d4f;
width: 120rpx;
}
.title {
font-size: 30rpx;
font-weight: 700;
color: #111;
}
.ghost {
width: 120rpx;
}
.content {
flex: 1;
padding: 18rpx 24rpx 24rpx;
box-sizing: border-box;
}
.card {
background: rgba(255, 255, 255, 0.96);
border: 1rpx solid rgba(0, 0, 0, 0.06);
border-radius: 20rpx;
padding: 24rpx 22rpx;
box-shadow: 0 16rpx 36rpx rgba(0, 0, 0, 0.06);
}
.h1 {
font-size: 32rpx;
font-weight: 700;
color: #111;
margin-bottom: 12rpx;
display: block;
}
.p {
font-size: 26rpx;
color: rgba(0, 0, 0, 0.65);
line-height: 44rpx;
margin-bottom: 12rpx;
display: block;
}
.divider {
height: 1rpx;
background: rgba(0, 0, 0, 0.08);
margin: 18rpx 0;
}
.footer {
margin-top: 18rpx;
}
.primary {
width: 100%;
height: 92rpx;
border-radius: 18rpx;
background: linear-gradient(135deg, #ff4d4f 0%, #ff7a45 100%);
color: #fff;
font-size: 30rpx;
font-weight: 600;
box-shadow: 0 16rpx 32rpx rgba(255, 77, 79, 0.24);
}
</style>

View File

@@ -0,0 +1,100 @@
# Supabase 配置已修改
## ✅ 已完成的修改
已修改 `supabase_pro/.env` 文件:
```env
ENABLE_EMAIL_AUTOCONFIRM=true # 从 false 改为 true
```
## 🔄 下一步操作
### 重启 Supabase Auth 服务
修改配置后,**必须重启服务**才能生效:
```bash
cd supabase_pro
docker-compose restart auth
```
或者重启整个 Supabase
```bash
docker-compose restart
```
### 验证配置
```bash
# 检查配置是否已修改
grep ENABLE_EMAIL_AUTOCONFIRM supabase_pro/.env
```
应该显示:`ENABLE_EMAIL_AUTOCONFIRM=true`
---
## 📝 配置说明
### 当前配置
-`ENABLE_EMAIL_SIGNUP=true` - 允许邮箱注册
-`ENABLE_EMAIL_AUTOCONFIRM=true` - **跳过邮件验证**,注册后立即可以登录
### 效果
1. **注册时**
- 用户填写邮箱和密码
- 点击注册
- Supabase 直接创建用户(不发送邮件)
- 返回 session用户自动登录
2. **登录时**
- 使用注册的邮箱和密码
- 可以直接登录(无需邮箱确认)
---
## 🧪 测试步骤
1. **重启服务**(如果还没重启)
```bash
cd supabase_pro
docker-compose restart auth
```
2. **测试注册**
- 在前端注册新用户
- 应该看到 "注册成功" 提示
- 自动跳转到登录页面(或直接进入应用)
3. **测试登录**
- 使用注册的邮箱和密码登录
- 应该可以成功登录
4. **验证数据库**
```sql
-- 检查新注册的用户
SELECT id, email, email_confirmed_at, created_at
FROM auth.users
ORDER BY created_at DESC
LIMIT 5;
-- 检查 ak_users 表
SELECT id, email, username, created_at
FROM ak_users
ORDER BY created_at DESC
LIMIT 5;
```
---
## ⚠️ 重要提示
- **修改配置后必须重启服务**,否则配置不会生效
- 如果重启后仍然无法注册,检查服务日志:
```bash
docker-compose logs auth
```

View File

@@ -0,0 +1,167 @@
# 注册问题调试指南
## 🔍 当前问题
修改配置后,注册仍然没有创建用户记录。
## 📋 检查清单
### 1. 确认配置已修改并重启服务
```bash
# 检查配置
cd supabase_pro
grep ENABLE_EMAIL_AUTOCONFIRM .env
# 应该显示: ENABLE_EMAIL_AUTOCONFIRM=true
# 重启服务(必须)
docker-compose restart auth
# 或者
docker-compose restart
```
### 2. 检查 Supabase 服务是否正常运行
```bash
cd supabase_pro
docker-compose ps
```
确保 `auth` 服务状态为 `Up`
### 3. 检查服务日志
```bash
# 查看 auth 服务日志
docker-compose logs auth --tail=50
# 查看是否有错误
docker-compose logs auth | grep -i error
```
### 4. 验证配置是否生效
在 Supabase Dashboard (http://192.168.1.61:3000) 的 SQL Editor 中执行:
```sql
-- 检查当前配置(需要访问 GoTrue 配置)
-- 注意:这个查询可能无法直接执行,但可以通过 API 检查
```
或者直接测试注册,查看返回结果。
---
## 🔧 调试步骤
### 步骤 1检查前端配置
确认 `ak/config.uts` 中的配置正确:
```typescript
export const SUPA_URL: string = 'http://192.168.1.61:8000'
export const SUPA_KEY: string = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
```
### 步骤 2测试注册并查看日志
1. 打开浏览器开发者工具F12
2. 切换到 Console 标签
3. 尝试注册新用户
4. 查看控制台输出:
- `📝 signUp HTTP 状态码: ...`
- `📝 注册返回结果: ...`
- `📝 错误代码: ...`
- `✅ 找到 user 字段: ...``⚠️ 未找到 user 信息`
### 步骤 3检查返回结果
根据控制台日志,判断:
**情况 AHTTP 状态码 200有 user 字段**
- ✅ 注册成功
- 检查 `ak_users` 表是否有记录
- 如果没有,检查 `ensureUserProfile` 是否被调用
**情况 BHTTP 状态码 500错误信息包含 "confirmation email"**
- ❌ 配置未生效或服务未重启
- 需要重启 Supabase Auth 服务
**情况 CHTTP 状态码 400错误信息包含 "already registered"**
- ⚠️ 用户已存在
- 尝试登录或使用其他邮箱
---
## 🐛 常见问题
### 问题 1配置已修改但服务未重启
**症状**:仍然返回 500 错误
**解决**
```bash
cd supabase_pro
docker-compose restart auth
# 等待几秒钟让服务启动
docker-compose ps # 确认服务已启动
```
### 问题 2服务重启失败
**检查**
```bash
docker-compose logs auth
```
**可能原因**
- 配置文件语法错误
- 端口被占用
- Docker 服务未运行
### 问题 3注册成功但 ak_users 没有记录
**检查**
1. 查看控制台是否有 `✅ 用户资料创建成功` 日志
2. 如果没有,检查 `ensureUserProfile` 是否被调用
3. 检查 RLS 策略和触发器是否已创建
---
## 📝 已改进的代码
1. **`signUp` 方法**
- ✅ 添加 HTTP 状态码检查
- ✅ 添加详细日志
- ✅ 返回错误信息时包含状态码
2. **注册页面**
- ✅ 添加更详细的日志输出
- ✅ 检查所有可能的返回结构
- ✅ 明确错误提示
---
## 🎯 下一步操作
1. **重启 Supabase Auth 服务**(如果还没重启)
2. **测试注册**,查看控制台日志
3. **根据日志判断问题**
- 如果 HTTP 状态码是 200 且有 user说明注册成功
- 如果 HTTP 状态码是 500说明配置未生效需要重启服务
- 如果 HTTP 状态码是 400可能是用户已存在或其他错误
4. **检查数据库**
```sql
-- 检查 auth.users
SELECT id, email, email_confirmed_at, created_at
FROM auth.users
ORDER BY created_at DESC
LIMIT 5;
-- 检查 ak_users
SELECT id, email, username, created_at
FROM ak_users
ORDER BY created_at DESC
LIMIT 5;
```

View File

@@ -0,0 +1,121 @@
# 注册邮件发送失败问题修复指南
## 🔍 问题描述
注册时出现错误:`Error sending confirmation email` (500 Internal Server Error)
**原因**
- Supabase 配置了 `ENABLE_EMAIL_AUTOCONFIRM=false`,需要发送确认邮件
- SMTP 配置使用的是假服务(`supabase-mail`, `fake_mail_user`),无法发送邮件
- 当 Supabase 尝试发送邮件时失败,返回 500 错误
## ✅ 解决方案
### 方案一:启用自动确认(推荐,开发环境)
修改 `supabase_pro/.env` 文件:
```env
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=true # 改为 true跳过邮件验证
```
**优点**
- 注册后立即可以登录,无需邮件验证
- 适合开发和测试环境
**缺点**
- 生产环境建议使用真实的邮件服务
---
### 方案二:配置真实的 SMTP 服务
修改 `supabase_pro/.env` 文件,配置真实的 SMTP 服务:
```env
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=false
SMTP_ADMIN_EMAIL=your-admin@example.com
SMTP_HOST=smtp.example.com # 真实的 SMTP 服务器
SMTP_PORT=587 # 或 465 (SSL)
SMTP_USER=your-smtp-user
SMTP_PASS=your-smtp-password
SMTP_SENDER_NAME=Your App Name
```
**常用 SMTP 服务**
- Gmail: `smtp.gmail.com:587`
- 163: `smtp.163.com:465`
- QQ: `smtp.qq.com:587`
- SendGrid, Mailgun 等第三方服务
---
### 方案三:使用 Supabase 本地邮件服务(开发环境)
如果使用 Docker Compose 运行 Supabase可以使用内置的邮件服务
1. 确保 `supabase-mail` 服务正常运行
2. 检查邮件服务日志:
```bash
docker-compose logs supabase-mail
```
3. 如果服务未运行,启动它:
```bash
docker-compose up -d supabase-mail
```
---
## 🔧 已实施的代码修复
已改进注册页面的错误处理:
1. **检查邮件发送失败错误**:如果返回 500 错误且错误信息包含 "confirmation email",会给出友好提示
2. **即使邮件发送失败,用户可能已创建**:提示用户稍后尝试登录
3. **改进错误提示**:更清晰的错误信息
---
## 📝 验证步骤
1. **修改配置后,重启 Supabase**
```bash
cd supabase_pro
docker-compose restart auth
```
2. **测试注册**
- 尝试注册新用户
- 如果使用 `ENABLE_EMAIL_AUTOCONFIRM=true`,应该立即可以登录
- 如果使用真实 SMTP检查邮箱是否收到确认邮件
3. **检查数据库**
```sql
-- 检查 auth.users 表中是否有新用户
SELECT id, email, email_confirmed_at, created_at
FROM auth.users
ORDER BY created_at DESC
LIMIT 5;
-- 检查 ak_users 表中是否有对应记录
SELECT id, email, username, created_at
FROM ak_users
ORDER BY created_at DESC
LIMIT 5;
```
---
## 🎯 推荐配置(开发环境)
```env
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=true # 开发环境跳过邮件验证
```
这样注册后可以立即登录,无需等待邮件确认。

View File

@@ -0,0 +1,115 @@
# 立即修复注册问题
## 🚨 当前问题
注册时返回 500 错误Supabase 中没有创建用户记录。
**原因**
- `ENABLE_EMAIL_AUTOCONFIRM=false` - 需要发送确认邮件
- SMTP 配置错误(`supabase-mail` 服务无法发送邮件)
- 当邮件发送失败时Supabase 不会创建用户
## ✅ 立即解决方案
### 步骤 1修改 Supabase 配置
编辑文件:`supabase_pro/.env`
找到这一行:
```env
ENABLE_EMAIL_AUTOCONFIRM=false
```
改为:
```env
ENABLE_EMAIL_AUTOCONFIRM=true
```
### 步骤 2重启 Supabase Auth 服务
```bash
cd supabase_pro
docker-compose restart auth
```
或者重启整个 Supabase
```bash
docker-compose restart
```
### 步骤 3验证配置
```bash
# 检查配置是否生效
grep ENABLE_EMAIL_AUTOCONFIRM supabase_pro/.env
```
应该显示:`ENABLE_EMAIL_AUTOCONFIRM=true`
### 步骤 4测试注册
1. 在前端注册新用户
2. 应该看到 "注册成功" 提示
3. 自动跳转到登录页面
4. 使用注册的邮箱和密码登录
5. 应该可以成功登录
---
## 🔍 验证用户是否创建
在 Supabase Dashboard (http://192.168.1.61:3000) 的 SQL Editor 中执行:
```sql
-- 检查最新注册的用户
SELECT id, email, email_confirmed_at, created_at
FROM auth.users
ORDER BY created_at DESC
LIMIT 5;
-- 检查 ak_users 表
SELECT id, email, username, created_at
FROM ak_users
ORDER BY created_at DESC
LIMIT 5;
```
---
## 📝 配置说明
### 开发环境推荐配置
```env
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=true # 跳过邮件验证,注册后立即可以登录
```
**优点**
- ✅ 注册后立即可以登录
- ✅ 无需配置 SMTP 服务
- ✅ 适合开发和测试
### 生产环境配置
如果需要邮件验证,配置真实的 SMTP 服务:
```env
ENABLE_EMAIL_AUTOCONFIRM=false
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-smtp-user
SMTP_PASS=your-smtp-password
```
---
## ⚠️ 重要提示
**修改配置后必须重启 Supabase Auth 服务**,否则配置不会生效。
```bash
cd supabase_pro
docker-compose restart auth
```

View File

@@ -0,0 +1,121 @@
# 注册后数据未存储到数据库 - 快速修复指南
## 🔍 问题原因
当前配置 `ENABLE_EMAIL_AUTOCONFIRM=false`,注册后:
-`auth.users` 表中会创建用户记录
- ❌ 没有 session不自动登录
- ❌ 没有 token
- ❌ RLS 策略阻止插入 `ak_users`(因为 `auth.uid()` 返回 null
## ✅ 解决方案(两种方式)
### 方式一:使用数据库触发器(推荐,完全自动化)
**优点**:注册时自动创建 `ak_users` 记录,无需前端处理
**执行步骤**
1. **在 Supabase Dashboard (http://192.168.1.61:3000) 中打开 SQL Editor**
2. **执行 `USER_AUTH_SCHEMA.sql`**
- 创建 `ak_users` 表和 RLS 策略
- 创建 `upsert_user_profile` RPC 函数
3. **执行 `USER_AUTH_TRIGGER.sql`**
- 创建触发器,在 `auth.users` 插入时自动创建 `ak_users` 记录
4. **验证**
```sql
-- 检查触发器是否存在
SELECT tgname FROM pg_trigger WHERE tgname = 'on_auth_user_created';
-- 检查函数是否存在
SELECT proname FROM pg_proc WHERE proname = 'handle_new_user';
```
5. **测试**
- 在前端注册一个新用户
- 检查 `ak_users` 表是否有新记录:
```sql
SELECT * FROM ak_users ORDER BY created_at DESC LIMIT 5;
```
---
### 方式二:仅使用 RPC 函数(如果触发器无法创建)
**执行步骤**
1. **在 Supabase Dashboard 中执行 `USER_AUTH_SCHEMA.sql`**
2. **验证 RPC 函数**
```sql
-- 检查函数是否存在
SELECT proname FROM pg_proc WHERE proname = 'upsert_user_profile';
-- 检查权限
SELECT grantee, privilege_type
FROM information_schema.routine_privileges
WHERE routine_name = 'upsert_user_profile';
```
3. **测试注册**
- 前端代码会自动调用 `upsert_user_profile` RPC 函数
- 检查 `ak_users` 表是否有新记录
---
## 🔧 如果数据仍然没有存储
### 检查清单
1. **确认 RPC 函数已创建**
```sql
SELECT proname, prosrc FROM pg_proc WHERE proname = 'upsert_user_profile';
```
如果返回空,说明函数未创建,需要执行 `USER_AUTH_SCHEMA.sql`
2. **确认触发器已创建**(如果使用了方式一)
```sql
SELECT tgname, tgenabled FROM pg_trigger WHERE tgname = 'on_auth_user_created';
```
如果返回空,需要执行 `USER_AUTH_TRIGGER.sql`
3. **检查浏览器控制台**
- 打开浏览器开发者工具
- 查看 Console 标签
- 注册时应该看到:
- `注册返回结果: {...}`
- `✅ 用户资料创建成功: ...` 或 `⚠️ 用户资料创建失败`
4. **检查 RPC 调用错误**
- 如果看到 `RPC 创建用户资料失败`,检查:
- RPC 函数是否存在
- 函数参数是否正确
- 网络请求是否成功
---
## 📝 当前代码逻辑
注册流程:
1. 调用 `supa.signUp()` → 在 `auth.users` 中创建用户
2. 获取 `user` 对象
3. 调用 `ensureUserProfile(user)` → 内部调用 `upsert_user_profile` RPC 函数
4. RPC 函数使用 `SECURITY DEFINER` → 绕过 RLS创建 `ak_users` 记录
**如果 RPC 函数不存在**,会回退到直接插入,但会失败(因为 RLS 阻止)。
---
## 🎯 推荐操作
**立即执行**
1. 在 Supabase Dashboard 执行 `pages/user/test/USER_AUTH_SCHEMA.sql`
2. 在 Supabase Dashboard 执行 `pages/user/test/USER_AUTH_TRIGGER.sql`
3. 测试注册功能
4. 检查 `ak_users` 表是否有新记录
**如果触发器创建失败**(权限问题),只执行 `USER_AUTH_SCHEMA.sql` 也可以,前端会使用 RPC 函数。

View File

@@ -0,0 +1,166 @@
# 注册和登录问题快速修复指南
## 🔍 当前问题
1. **注册时**:返回 500 错误 `Error sending confirmation email`
2. **登录时**:返回 400 错误 `Invalid login credentials`
**根本原因**
- `ENABLE_EMAIL_AUTOCONFIRM=false` - 需要邮件确认才能登录
- SMTP 配置是假的(`supabase-mail`, `fake_mail_user`),无法发送邮件
- 即使注册时邮件发送失败,用户可能已在 `auth.users` 中创建,但因为邮箱未确认,无法登录
---
## ✅ 立即解决方案(推荐)
### 修改 Supabase 配置
编辑 `supabase_pro/.env` 文件:
```env
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=true # 改为 true跳过邮件验证
```
### 重启 Supabase Auth 服务
```bash
cd supabase_pro
docker-compose restart auth
```
### 验证
1. **测试注册**:注册新用户,应该立即可以登录
2. **测试登录**:使用注册的邮箱和密码登录
---
## 🔧 如果用户已创建但邮箱未确认
如果之前注册的用户因为邮件发送失败而无法登录,可以手动确认邮箱:
### 方法一:在 Supabase Dashboard 中手动确认
1. 打开 Supabase Dashboard: http://192.168.1.61:3000
2. 进入 **Authentication****Users**
3. 找到对应的用户
4. 点击用户,在详情页中点击 **Confirm Email** 按钮
### 方法二:使用 SQL 手动确认
在 Supabase Dashboard 的 SQL Editor 中执行:
```sql
-- 查找未确认的用户
SELECT id, email, email_confirmed_at, created_at
FROM auth.users
WHERE email_confirmed_at IS NULL
ORDER BY created_at DESC;
-- 手动确认邮箱(替换 'user-email@example.com' 为实际邮箱)
UPDATE auth.users
SET email_confirmed_at = NOW()
WHERE email = 'user-email@example.com'
AND email_confirmed_at IS NULL;
```
---
## 📝 已改进的错误处理
### 注册页面
- ✅ 检测邮件发送失败错误500 + "confirmation email"
- ✅ 即使邮件发送失败,也会提示用户稍后尝试登录
- ✅ 更友好的错误提示
### 登录页面
- ✅ 检测邮箱未确认错误
- ✅ 检测凭证错误
- ✅ 更清晰的错误提示
---
## 🎯 推荐配置(开发环境)
```env
## Email auth
ENABLE_EMAIL_SIGNUP=true
ENABLE_EMAIL_AUTOCONFIRM=true # 开发环境跳过邮件验证
```
**优点**
- 注册后立即可以登录
- 无需配置 SMTP 服务
- 适合开发和测试
**注意**:生产环境建议使用真实的 SMTP 服务并启用邮件验证。
---
## 🔍 验证步骤
### 1. 检查配置是否生效
```bash
# 检查环境变量
cd supabase_pro
grep ENABLE_EMAIL_AUTOCONFIRM .env
```
应该显示:`ENABLE_EMAIL_AUTOCONFIRM=true`
### 2. 测试注册流程
1. 在前端注册新用户
2. 应该看到 "注册成功" 提示
3. 自动跳转到登录页面
4. 使用注册的邮箱和密码登录
5. 应该可以成功登录
### 3. 检查数据库
```sql
-- 检查新注册的用户
SELECT id, email, email_confirmed_at, created_at
FROM auth.users
ORDER BY created_at DESC
LIMIT 5;
-- 检查 ak_users 表
SELECT id, email, username, created_at
FROM ak_users
ORDER BY created_at DESC
LIMIT 5;
```
---
## 🐛 如果仍然无法登录
### 检查用户是否已创建
```sql
-- 检查用户是否存在
SELECT id, email, email_confirmed_at, encrypted_password IS NOT NULL as has_password
FROM auth.users
WHERE email = 'your-email@example.com';
```
### 如果用户存在但未确认
使用上面的 SQL 手动确认邮箱。
### 如果用户不存在
重新注册,确保配置 `ENABLE_EMAIL_AUTOCONFIRM=true` 已生效。
---
## 📚 相关文档
- `EMAIL_CONFIG_FIX.md` - 详细的邮件配置说明
- `QUICK_FIX.md` - 注册数据存储问题修复
- `README.md` - 用户认证相关 SQL 文件说明

View File

@@ -0,0 +1,208 @@
# 用户认证相关 SQL 文件说明
> 本目录包含用户登录/注册相关的数据库表结构和触发器。
## 📁 文件说明
### 1. `USER_AUTH_SCHEMA.sql` ⭐ **第一步**
创建用户认证相关的表结构:
- **`ak_users`** - 业务用户资料表(与 `auth.users` 关联)
- **`users`** - 轻量用户表(用于统计)
- **`user_sessions`** - 用户会话表(用于在线统计)
- **RLS 策略** - 行级安全策略
- **触发器** - 自动更新 `updated_at` 字段
- **RPC 函数** - `upsert_user_profile`(用于创建/更新用户资料,绕过 RLS
**执行顺序**:首次部署时执行
**执行方式**:在 Supabase Dashboard 的 SQL Editor 中执行
---
### 2. `USER_AUTH_TRIGGER.sql` ⭐ **第二步(推荐)**
创建数据库触发器,在 `auth.users` 表插入新用户时自动创建 `ak_users` 记录。
**优点**
- 完全自动化,无需前端处理
- 即使邮箱验证开启也能正常工作
- 不依赖前端 token
**执行顺序**:在 `USER_AUTH_SCHEMA.sql` 之后执行
**执行方式**:在 Supabase Dashboard 的 SQL Editor 中执行(需要 superuser 权限Dashboard 默认有)
**注意**:如果无法创建触发器(权限问题),可以跳过此文件,使用 RPC 函数方案。
---
### 3. `USER_AUTH_TEST_DATA.sql`(可选)
插入测试用户数据,用于开发和测试。
**执行顺序**:在表结构创建后执行
---
## 🚀 快速部署
### 方式一:使用触发器(推荐)
1. **执行表结构**
```sql
-- 在 Supabase Dashboard 执行
-- 复制 pages/user/test/USER_AUTH_SCHEMA.sql 的内容并执行
```
2. **创建触发器**
```sql
-- 在 Supabase Dashboard 执行
-- 复制 pages/user/test/USER_AUTH_TRIGGER.sql 的内容并执行
```
3. **验证**
```sql
-- 检查函数是否存在
SELECT * FROM pg_proc WHERE proname = 'upsert_user_profile';
-- 检查触发器是否存在(如果执行了 USER_AUTH_TRIGGER.sql
SELECT * FROM pg_trigger WHERE tgname = 'on_auth_user_created';
```
### 方式二:仅使用 RPC 函数(如果触发器无法创建)
1. **执行表结构**
```sql
-- 在 Supabase Dashboard 执行
-- 复制 pages/user/test/USER_AUTH_SCHEMA.sql 的内容并执行
```
2. **验证 RPC 函数**
```sql
-- 检查函数是否存在
SELECT * FROM pg_proc WHERE proname = 'upsert_user_profile';
```
---
## 🔧 工作原理
### 方案一:数据库触发器(推荐)
1. 用户注册 → Supabase Auth 在 `auth.users` 表中创建记录
2. 数据库触发器自动执行 → 在 `ak_users` 表中创建对应记录
3. 前端无需处理 → 用户资料自动创建
### 方案二RPC 函数
1. 用户注册 → 前端获取 user 对象
2. 前端调用 `ensureUserProfile()` → 内部调用 `upsert_user_profile` RPC 函数
3. RPC 函数使用 `SECURITY DEFINER` → 绕过 RLS 策略,创建用户资料
---
## ⚠️ 重要说明
### RLS 策略
`ak_users` 表已启用 RLS策略如下
- **SELECT**:用户只能查看自己的资料(`auth.uid() = id`
- **INSERT**:用户只能插入自己的资料(`auth.uid() = id`
- **UPDATE**:用户只能更新自己的资料(`auth.uid() = id`
### 注册时的问题
注册时如果邮箱验证未开启Supabase 会返回 session此时有 token可以直接插入。
如果邮箱验证已开启,注册后没有 session此时没有 token`auth.uid()` 返回 `null`RLS 策略会阻止插入。
**解决方案**
1. ✅ 使用数据库触发器(自动创建,无需 token
2. ✅ 使用 `SECURITY DEFINER` RPC 函数(绕过 RLS
3. ⚠️ 用户登录后自动创建(在 `getCurrentUser` 中处理)
---
## 🔍 验证和测试
### 测试注册流程
1. **注册新用户**
- 在前端注册页面输入邮箱和密码
- 点击注册
2. **检查数据库**
```sql
-- 检查 auth.users 表中是否有新用户
SELECT id, email, created_at FROM auth.users ORDER BY created_at DESC LIMIT 5;
-- 检查 ak_users 表中是否有对应记录
SELECT id, email, username, created_at FROM ak_users ORDER BY created_at DESC LIMIT 5;
```
3. **如果 ak_users 中没有记录**
- 检查是否执行了 `USER_AUTH_TRIGGER.sql`
- 检查触发器是否创建成功
- 检查 RPC 函数是否创建成功
- 查看浏览器控制台的错误信息
---
## 📚 相关文件
- `pages/user/register.uvue` - 注册页面
- `pages/user/login.uvue` - 登录页面
- `utils/sapi.uts` - `ensureUserProfile` 函数
- `utils/store.uts` - `getCurrentUser` 函数(登录后自动创建资料)
---
## 🐛 故障排查
### 问题:注册后 `ak_users` 表中没有记录
**可能原因**
1. 未执行 `USER_AUTH_SCHEMA.sql`RPC 函数不存在)
2. 未执行 `USER_AUTH_TRIGGER.sql`(触发器不存在)
3. RLS 策略阻止插入(没有 token
4. 邮箱验证已开启,注册后没有 session
**解决方案**
1. 执行 `USER_AUTH_SCHEMA.sql` 创建 RPC 函数
2. 执行 `USER_AUTH_TRIGGER.sql` 创建触发器(推荐)
3. 或者等待用户登录后自动创建(在 `getCurrentUser` 中处理)
### 问题RPC 函数调用失败
**检查**
```sql
-- 检查函数是否存在
SELECT proname, prosrc FROM pg_proc WHERE proname = 'upsert_user_profile';
-- 检查权限
SELECT grantee, privilege_type
FROM information_schema.routine_privileges
WHERE routine_name = 'upsert_user_profile';
```
**解决**:重新执行 `USER_AUTH_SCHEMA.sql` 中的函数创建部分。
---
## ✅ 下一步
执行完 SQL 文件后:
1. **测试注册功能**
- 在前端注册新用户
- 检查 `ak_users` 表中是否有新记录
2. **测试登录功能**
- 使用注册的账号登录
- 检查是否能正常获取用户资料
3. **检查前端页面**
- 个人中心页面是否能正常显示用户信息

31
mall/pages/user/types.uts Normal file
View File

@@ -0,0 +1,31 @@
// 用户基础信息类型
export type UserProfile ={
id?: string;
username: string;
email: string;
gender?: string;
birthday?: string;
height_cm?: number;
weight_kg?: number;
bio?: string;
avatar_url?: string;
preferred_language?: string;
role?:string;
school_id?: string; // 所属学校ID
grade_id?: string; // 所属年级ID
class_id?: string; // 所属班级ID
}
// 语言选项类型 - 对应 ak_languages 表
export type LanguageOption = {
id: string; // UUID
code: string; // 语言代码,如 'zh-CN', 'en-US'
name: string; // 英文名称
native_name: string; // 本地语言名称
}
export type UserStats = {
trainings: number;
points: number;
streak: number;
}