web-class-frontend/app/stores/login.ts

153 lines
3.6 KiB
TypeScript

interface RegisterData {
email: string;
username: string;
identifyingCode: string;
password: string;
passwordRepeat: string;
birth: string;
avatarFile: string;
}
interface LoginData {
usernameOrEmail: string;
password: string;
}
interface resetData {
usernameOrEmail: string;
identifyingCode: string;
password: string;
passwordRepeat: string;
}
export enum PageType {
'login',
'register',
'reset',
}
export interface LoginStore {
loginForm: LoginData;
registerForm: RegisterData;
resetForm: resetData;
currentType: PageType;
}
export const useLoginStore = defineStore('Login', {
state: (): LoginStore => ({
loginForm: { usernameOrEmail: '', password: '' },
registerForm: {
email: '',
identifyingCode: '',
username: '',
password: '',
passwordRepeat: '',
birth: '',
avatarFile: '',
},
resetForm: {
usernameOrEmail: '',
identifyingCode: '',
password: '',
passwordRepeat: '',
},
currentType: PageType.login,
}),
actions: {
async login() {
const { $http } = useNuxtApp();
try {
await $http.POST('/login/', this.loginForm);
} catch {
return false;
}
return true;
},
async sendRegisterIdentifyingCode(): Promise<boolean> {
const email = this.registerForm.email;
if (email === '') {
await MessagePlugin.error('请输入邮箱');
return false;
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
await MessagePlugin.error('请输入正确的邮箱');
return false;
}
const { $http } = useNuxtApp();
let result: APIResponse<unknown>;
try {
result = await $http.GET('/login/register/identifyingCode', {
email: email,
});
} catch (e) {
await MessagePlugin.error(e as string);
return false;
}
if (result.code === 200) {
return true;
} else {
await MessagePlugin.error(result.message);
}
return false;
},
async sendResetIdentifyingCode(): Promise<boolean> {
const { $http } = useNuxtApp();
const usernameOrEmail = this.resetForm.usernameOrEmail;
if (usernameOrEmail === '') {
await MessagePlugin.error('请输入用户名或邮箱');
return false;
}
const result = await $http.GET('/login/passwordReset/identifyingCode', {
usernameOrEmail: usernameOrEmail,
});
if (result.code === 200) {
return true;
} else {
await MessagePlugin.error(result.message);
}
return false;
},
async register(recallWhenSuccess: () => void) {
const { $http } = useNuxtApp();
try {
await $http.POST('/login/register', this.registerForm);
recallWhenSuccess();
} catch {
return;
}
},
async reset(recallWhenSuccess: () => void) {
const { $http } = useNuxtApp();
try {
await $http.POST('/login/passwordReset', this.resetForm);
recallWhenSuccess();
} catch {
return;
}
},
async logout() {
const { $http } = useNuxtApp();
try {
await $http.GET('/login/logout');
} catch {
return;
}
const router = useRouter();
await router.push('/login');
},
},
getters: {
getTypeName: (state) => {
switch (state.currentType) {
case PageType.login:
return '登录';
case PageType.register:
return '注册';
case PageType.reset:
return '重置密码';
default:
return '未知';
}
},
},
});