Commit bb73c81d by Sendya

refactor: login

parent 1f7068a7
const api = { const api = {
Login: '/auth/login', Login: '/auth/login',
Logout: '/auth/logout', Logout: '/auth/logout',
ForgePassword: '/auth/forge-password', ForgePassword: '/auth/forge-password',
Register: '/auth/register', Register: '/auth/register',
SendSms: '/account/sms', twoStepCode: '/auth/2step-code',
SendSmsErr: '/account/sms_err', SendSms: '/account/sms',
// get my info SendSmsErr: '/account/sms_err',
UserInfo: '/user/info' // get my info
} UserInfo: '/user/info'
}
export default api export default api
\ No newline at end of file
import api from './index' import api from './index'
import { axios } from '@/utils/request' import { axios } from '@/utils/request'
/** /**
* login func * login func
* parameter: { * parameter: {
* username: '', * username: '',
* password: '', * password: '',
* remember_me: true, * remember_me: true,
* captcha: '12345' * captcha: '12345'
* } * }
* @param parameter * @param parameter
* @returns {*} * @returns {*}
*/ */
export function login(parameter) { export function login(parameter) {
return axios({ return axios({
url: '/auth/login', url: '/auth/login',
method: 'post', method: 'post',
data: parameter data: parameter
}) })
} }
export function getSmsCaptcha(parameter) { export function getSmsCaptcha(parameter) {
return axios({ return axios({
url: api.SendSms, url: api.SendSms,
method: 'post', method: 'post',
data: parameter data: parameter
}) })
} }
export function getInfo() { export function getInfo() {
return axios({ return axios({
url: '/user/info', url: '/user/info',
method: 'get', method: 'get',
headers: { headers: {
'Content-Type': 'application/json;charset=UTF-8' 'Content-Type': 'application/json;charset=UTF-8'
} }
}) })
} }
export function logout() { export function logout() {
return axios({ return axios({
url: '/auth/logout', url: '/auth/logout',
method: 'post', method: 'post',
headers: { headers: {
'Content-Type': 'application/json;charset=UTF-8' 'Content-Type': 'application/json;charset=UTF-8'
} }
}) })
}
/**
* get user 2step code open?
* @param parameter {*}
*/
export function get2step(parameter) {
return axios({
url: api.twoStepCode,
method: 'post',
data: parameter
})
} }
\ No newline at end of file
<template> <template>
<div class="main"> <div class="main">
<a-form <a-form
id="formLogin"
class="user-layout-login" class="user-layout-login"
ref="formLogin" ref="formLogin"
:autoFormCreate="(form)=>{this.form = form}" :form="form"
id="formLogin"
> >
<a-tabs <a-tabs
:activeKey="customActiveKey" :activeKey="customActiveKey"
...@@ -12,41 +12,46 @@ ...@@ -12,41 +12,46 @@
@change="handleTabClick" @change="handleTabClick"
> >
<a-tab-pane key="tab1" tab="账号密码登陆"> <a-tab-pane key="tab1" tab="账号密码登陆">
<a-form-item <a-form-item>
fieldDecoratorId="username" <a-input
:fieldDecoratorOptions="{rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: this.handleUsernameOrEmail }], validateTrigger: 'change'}" size="large"
> type="text"
<a-input size="large" type="text" placeholder="帐户名或邮箱地址 / admin"> placeholder="帐户名或邮箱地址 / admin"
v-decorator="[
'username',
{rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
]"
>
<a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/> <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
</a-input> </a-input>
</a-form-item> </a-form-item>
<a-form-item <a-form-item>
fieldDecoratorId="password" <a-input
:fieldDecoratorOptions="{rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}" size="large"
> type="password"
<a-input size="large" type="password" autocomplete="false" placeholder="密码 / admin"> autocomplete="false"
placeholder="密码 / admin"
v-decorator="[
'password',
{rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
]"
>
<a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/> <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
</a-input> </a-input>
</a-form-item> </a-form-item>
</a-tab-pane> </a-tab-pane>
<a-tab-pane key="tab2" tab="手机号登陆"> <a-tab-pane key="tab2" tab="手机号登陆">
<a-form-item <a-form-item>
fieldDecoratorId="mobile" <a-input size="large" type="text" placeholder="手机号" v-decorator="['mobile', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }], validateTrigger: 'change'}]">
:fieldDecoratorOptions="{rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号' }], validateTrigger: 'change'}"
>
<a-input size="large" type="text" placeholder="手机号">
<a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/> <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
</a-input> </a-input>
</a-form-item> </a-form-item>
<a-row :gutter="16"> <a-row :gutter="16">
<a-col class="gutter-row" :span="16"> <a-col class="gutter-row" :span="16">
<a-form-item <a-form-item>
fieldDecoratorId="captcha" <a-input size="large" type="text" placeholder="验证码" v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]">
:fieldDecoratorOptions="{rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}"
>
<a-input size="large" type="text" placeholder="验证码">
<a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/> <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
</a-input> </a-input>
</a-form-item> </a-form-item>
...@@ -65,7 +70,7 @@ ...@@ -65,7 +70,7 @@
</a-tabs> </a-tabs>
<a-form-item> <a-form-item>
<a-checkbox v-model="formLogin.rememberMe">自动登陆</a-checkbox> <a-checkbox v-decorator="['rememberMe']">自动登陆</a-checkbox>
<router-link <router-link
:to="{ name: 'recover', params: { user: 'aaa'} }" :to="{ name: 'recover', params: { user: 'aaa'} }"
class="forge-password" class="forge-password"
...@@ -77,11 +82,10 @@ ...@@ -77,11 +82,10 @@
<a-button <a-button
size="large" size="large"
type="primary" type="primary"
htmlType="submit"
class="login-button" class="login-button"
:loading="loginBtn" :loading="state.loginBtn"
:disabled="state.loginBtn"
@click.stop.prevent="handleSubmit" @click.stop.prevent="handleSubmit"
:disabled="loginBtn"
>确定</a-button> >确定</a-button>
</a-form-item> </a-form-item>
...@@ -111,10 +115,10 @@ ...@@ -111,10 +115,10 @@
<script> <script>
import md5 from 'md5' import md5 from 'md5'
import api from '@/api'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha' import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex' import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util' import { timeFix } from '@/utils/util'
import { getSmsCaptcha, get2step } from '@/api/login'
export default { export default {
components: { components: {
...@@ -128,28 +132,23 @@ export default { ...@@ -128,28 +132,23 @@ export default {
loginType: 0, loginType: 0,
requiredTwoStepCaptcha: false, requiredTwoStepCaptcha: false,
stepCaptchaVisible: false, stepCaptchaVisible: false,
form: null, form: this.$form.createForm(this),
state: { state: {
time: 60, time: 60,
loginBtn: false,
// login type: 0 email, 1 username, 2 telephone
loginType: 0,
smsSendBtn: false smsSendBtn: false
},
formLogin: {
username: '',
password: '',
captcha: '',
mobile: '',
rememberMe: true
} }
} }
}, },
created() { created() {
this.$http get2step({ })
.get('/auth/2step-code')
.then(res => { .then(res => {
this.requiredTwoStepCaptcha = res.result.stepCode this.requiredTwoStepCaptcha = res.result.stepCode
}) })
.catch(err => { .catch(() => {
console.log('2step-code:', err) this.requiredTwoStepCaptcha = false
}) })
// this.requiredTwoStepCaptcha = true // this.requiredTwoStepCaptcha = true
}, },
...@@ -157,11 +156,12 @@ export default { ...@@ -157,11 +156,12 @@ export default {
...mapActions(['Login', 'Logout']), ...mapActions(['Login', 'Logout']),
// handler // handler
handleUsernameOrEmail(rule, value, callback) { handleUsernameOrEmail(rule, value, callback) {
const { state } = this
const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/ const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
if (regex.test(value)) { if (regex.test(value)) {
this.loginType = 0 state.loginType = 0
} else { } else {
this.loginType = 1 state.loginType = 1
} }
callback() callback()
}, },
...@@ -170,83 +170,68 @@ export default { ...@@ -170,83 +170,68 @@ export default {
// this.form.resetFields() // this.form.resetFields()
}, },
handleSubmit() { handleSubmit() {
const that = this const {
let flag = false form: { validateFields },
state,
let loginParams = { customActiveKey,
remember_me: that.formLogin.rememberMe Login
} } = this
// 使用账户密码登陆
if (that.customActiveKey === 'tab1') {
that.form.validateFields(['username', 'password'], { force: true }, (err, values) => {
if (!err) {
flag = true
loginParams[!that.loginType ? 'email' : 'username'] = values.username
loginParams.password = md5(values.password)
}
})
// 使用手机号登陆
} else {
that.form.validateFields(['mobile', 'captcha'], { force: true }, (err, values) => {
if (!err) {
flag = true
loginParams = Object.assign(loginParams, values)
}
})
}
if (!flag) return state.loginBtn = true
that.loginBtn = true const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['mobile', 'captcha']
that validateFields(validateFieldsKey, { force: true }, (err, values) => {
.Login(loginParams) if (!err) {
.then(() => { console.log('login form', values)
if (that.requiredTwoStepCaptcha) { const loginParams = {...values}
that.stepCaptchaVisible = true delete loginParams.username
} else { loginParams[!state.loginType ? 'email' : 'username'] = values.username
that.loginSuccess() loginParams.password = md5(values.password)
} Login(loginParams)
}) .then((res) => this.loginSuccess(res))
.catch(err => { .catch(err => this.requestFailed(err))
that.requestFailed(err) .finally(() => {
}) state.loginBtn = false
})
} else {
setTimeout(() => {
state.loginBtn = false
}, 600)
}
})
}, },
getCaptcha(e) { getCaptcha(e) {
e.preventDefault() e.preventDefault()
const that = this const { form: { validateFields }, state } = this
this.form.validateFields(['mobile'], { force: true }, err => { validateFields(['mobile'], { force: true }, (err, values) => {
if (!err) { if (!err) {
this.state.smsSendBtn = true state.smsSendBtn = true
const interval = window.setInterval(() => { const interval = window.setInterval(() => {
if (that.state.time-- <= 0) { if (state.time-- <= 0) {
that.state.time = 60 state.time = 60
that.state.smsSendBtn = false state.smsSendBtn = false
window.clearInterval(interval) window.clearInterval(interval)
} }
}, 1000) }, 1000)
const hide = this.$message.loading('验证码发送中..', 0) const hide = this.$message.loading('验证码发送中..', 0)
this.$http getSmsCaptcha({ mobile: values.mobile }).then(res => {
.post(api.SendSms, { mobile: that.formLogin.mobile }) setTimeout(hide, 2500)
.then(res => { this.$notification['success']({
setTimeout(hide, 2500) message: '提示',
this.$notification['success']({ description: '验证码获取成功,您的验证码为:' + res.result.captcha,
message: '提示', duration: 8
description: '验证码获取成功,您的验证码为:' + res.result.captcha,
duration: 8
})
})
.catch(err => {
setTimeout(hide, 1)
clearInterval(interval)
that.state.time = 60
that.state.smsSendBtn = false
this.requestFailed(err)
}) })
}).catch(err => {
setTimeout(hide, 1)
clearInterval(interval)
state.time = 60
state.smsSendBtn = false
this.requestFailed(err)
})
} }
}) })
}, },
...@@ -259,8 +244,8 @@ export default { ...@@ -259,8 +244,8 @@ export default {
this.stepCaptchaVisible = false this.stepCaptchaVisible = false
}) })
}, },
loginSuccess() { loginSuccess(res) {
this.loginBtn = false console.log(res)
this.$router.push({ name: 'dashboard' }) this.$router.push({ name: 'dashboard' })
this.$notification.success({ this.$notification.success({
message: '欢迎', message: '欢迎',
...@@ -273,7 +258,6 @@ export default { ...@@ -273,7 +258,6 @@ export default {
description: ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试', description: ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试',
duration: 4 duration: 4
}) })
this.loginBtn = false
} }
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment