增加邮箱和手机号登录

pull/1/head
xiaoyu 5 years ago
parent d02a7a74b8
commit d5c8a09ce6
  1. 73
      fir_client/src/components/FirLogin.vue
  2. 25
      fir_client/src/components/FirRegist.vue
  3. 224
      fir_client/src/components/FirUserProfileInfo.vue
  4. 15
      fir_client/src/restful/index.js
  5. 2
      fir_ser/api/models.py
  6. 3
      fir_ser/api/urls.py
  7. 18
      fir_ser/api/utils/utils.py
  8. 344
      fir_ser/api/views/login.py

@ -16,9 +16,21 @@
<el-form ref="form" :model="form"> <el-form ref="form" :model="form">
<el-tabs v-model="activeName">
<el-tab-pane label="用户名登录" name="username" v-if="allow_ways.up">
<el-form-item> <el-form-item>
<el-input v-model="form.email" prefix-icon="el-icon-user" placeholder="邮箱" autofocus></el-input> <el-input v-model="form.email" prefix-icon="el-icon-user" placeholder="用户名" autofocus
clearable></el-input>
</el-form-item> </el-form-item>
</el-tab-pane>
<el-tab-pane :label="rutitle+'登录'" name="smsemail" v-if="allow_ways.sms || allow_ways.email">
<el-form-item>
<el-input v-model="form.email" prefix-icon="el-icon-user" :placeholder="rutitle" autofocus
clearable></el-input>
</el-form-item>
</el-tab-pane>
</el-tabs>
<el-form-item> <el-form-item>
<el-input v-model="form.password" prefix-icon="el-icon-lock" placeholder="密码" <el-input v-model="form.password" prefix-icon="el-icon-lock" placeholder="密码"
@ -71,6 +83,11 @@
authcode: '' authcode: ''
}, },
cptch: {"cptch_image": '', "cptch_key": '', "length": 8}, cptch: {"cptch_image": '', "cptch_key": '', "length": 8},
activeName: 'username',
allow_ways: {},
rutitle: '',
rctitle: ''
} }
}, },
methods: { methods: {
@ -78,8 +95,19 @@
let email = this.form.email; let email = this.form.email;
let password = this.form.password; let password = this.form.password;
let authcode = this.form.authcode; let authcode = this.form.authcode;
let login_type = 'up';
if (authcode.length === this.cptch.length) { if (authcode.length === this.cptch.length) {
if (this.activeName === "username") {
if (email.length < 6) {
this.$message({
message: '用户名至少6位',
type: 'error'
});
return
}
} else if (this.activeName === "smsemail") {
let checkp = checkphone(this.form.email); let checkp = checkphone(this.form.email);
let checke = checkEmail(this.form.email); let checke = checkEmail(this.form.email);
if (!checkp && !checke) { if (!checkp && !checke) {
@ -87,7 +115,22 @@
message: '邮箱或者手机号输入有误', message: '邮箱或者手机号输入有误',
type: 'error' type: 'error'
}); });
return
} }
if (checkp) {
login_type = 'sms';
} else if (checke) {
login_type = 'email';
}
} else {
this.$message({
message: '未知登录方式',
type: 'error'
});
return
}
if (password.length > 6) { if (password.length > 6) {
loginFun(data => { loginFun(data => {
if (data.code == 1000) { if (data.code == 1000) {
@ -115,7 +158,8 @@
"username": email, "username": email,
"password": password, "password": password,
"authcode": authcode, "authcode": authcode,
"cptch_key": this.cptch.cptch_key "cptch_key": this.cptch.cptch_key,
"login_type": login_type,
} }
}); });
@ -136,16 +180,31 @@
onRegister() { onRegister() {
this.$router.push({name: 'FirRegist'}) this.$router.push({name: 'FirRegist'})
}, },
isEmail(input) { set_activename() {
if (input.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) { if (this.allow_ways.up) {
return true; this.activeName = 'username';
} else {
this.activeName = 'smsemail';
} }
return false; },
set_rtitle() {
this.rutitle = '';
if (this.allow_ways.sms) {
this.rutitle = this.rutitle + '手机号 ';
}
if (this.allow_ways.email) {
this.rutitle = this.rutitle + '邮箱 ';
}
this.rutitle = this.rutitle.trim().replace(' ', '或');
}, },
get_auth_code() { get_auth_code() {
loginFun(data => { loginFun(data => {
if (data.code == 1000) { if (data.code === 1000) {
this.cptch = data.data; this.cptch = data.data;
this.allow_ways = data.data.login_type;
this.set_rtitle();
this.set_activename();
} else { } else {
this.$message({ this.$message({
message: data.msg, message: data.msg,

@ -26,11 +26,10 @@
clearable></el-input> clearable></el-input>
</el-form-item> </el-form-item>
<el-form-item style="height: 40px"> <el-form-item style="height: 40px">
<el-row style="height: 40px"> <el-row style="height: 40px">
<el-col :span="16"> <el-col :span="16">
<el-input placeholder="请输入验证码" v-model="form.authcode" maxlength="6"></el-input> <el-input placeholder="请输入图片验证码" v-model="form.authcode" maxlength="6"></el-input>
</el-col> </el-col>
<el-col :span="8"> <el-col :span="8">
<el-image <el-image
@ -112,7 +111,6 @@
methods: { methods: {
set_rtitle() { set_rtitle() {
this.rutitle = ''; this.rutitle = '';
this.rctitle = '';
if (this.allow_ways.sms) { if (this.allow_ways.sms) {
this.rutitle = this.rutitle + '手机号 '; this.rutitle = this.rutitle + '手机号 ';
} }
@ -121,15 +119,14 @@
} }
this.rutitle = this.rutitle.trim().replace(' ', '或'); this.rutitle = this.rutitle.trim().replace(' ', '或');
this.rctitle = this.rctitle.trim().replace(' ', '或');
}, },
get_auth_code() { get_auth_code() {
registerFun(data => { registerFun(data => {
if (data.code == 1000) { if (data.code === 1000) {
let jdata = data.data; let jdata = data.data;
if (jdata.enable) { if (jdata.enable) {
this.allow_r = true; this.allow_r = true;
this.allow_ways = jdata.ways; this.allow_ways = jdata.register_type;
this.set_rtitle(); this.set_rtitle();
this.cptch = data.data; this.cptch = data.data;
} else { } else {
@ -151,7 +148,7 @@
}); });
}, },
getphonecode() { getphonecode() {
let act = 'ways'; let act = 'up';
if (!this.docheck()) { if (!this.docheck()) {
return return
} }
@ -244,7 +241,7 @@
if (authcode.length === this.cptch.length) { if (authcode.length === this.cptch.length) {
if (password === password2 && password.length >= 6) { if (password === password2 && password.length >= 6) {
registerFun(data => { registerFun(data => {
if (data.code == 1000) { if (data.code === 1000) {
this.$message({ this.$message({
message: '注册成功', message: '注册成功',
type: 'success' type: 'success'
@ -286,12 +283,12 @@
onLogin() { onLogin() {
this.$router.push({name: 'FirLogin'}) this.$router.push({name: 'FirLogin'})
}, },
isEmail(input) { // isEmail(input) {
if (input.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) { // if (input.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) {
return true; // return true;
} // }
return false; // return false;
} // }
} }
, ,
created() { created() {

@ -2,51 +2,61 @@
<div> <div>
<el-form ref="form" :model="userinfo"> <el-form ref="form" :model="userinfo">
<el-form-item>
<el-row>
<el-col :span="22">
<el-input v-model="userinfo.username" prefix-icon="el-icon-user" placeholder="用户名"
disabled></el-input>
</el-col>
</el-row>
</el-form-item>
<el-form-item> <el-form-item>
<el-row> <el-row>
<el-col :span="18"> <el-col :span="18">
<el-input v-model="userinfo.domain_name" :readonly="editdomain_name !== true" ref="domain_name" <el-input v-model="userinfo.username" :readonly="edituser_name !== true"
prefix-icon="el-icon-download" prefix-icon="el-icon-user" placeholder="用户名" ref="user_name"
placeholder="下载页域名"></el-input> ></el-input>
</el-col> </el-col>
<el-col :span="2"> <el-col :span="2">
<el-button icon="el-icon-edit" @click="changeDomainValue"> <el-button icon="el-icon-edit" @click="changeUsernameValue">
</el-button> </el-button>
</el-col> </el-col>
<el-col :span="4" v-if="editdomain_name === true"> <el-col :span="4" v-if="edituser_name === true">
<el-button type="success" @click="saveDomain" plain <el-button type="success" @click="saveUsername" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat"> style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat">
保存 保存
</el-button> </el-button>
</el-col> </el-col>
</el-row> </el-row>
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
<el-row> <el-row>
<el-col :span="18"> <el-col :span="18">
<el-input v-model="userinfo.job" ref="position" :readonly="editposition !== true" <el-input v-model="userinfo.mobile" ref="phone" :readonly="editphone !== true"
prefix-icon="el-icon-postcard" placeholder="职位"></el-input> prefix-icon="el-icon-mobile" placeholder="手机" maxlength="11"></el-input>
</el-col> </el-col>
<el-col :span="2"> <el-col :span="2">
<el-button icon="el-icon-edit" @click="changePositionValue"> <el-button icon="el-icon-edit" @click="changePhoneValue">
</el-button> </el-button>
</el-col> </el-col>
<el-col :span="4" v-if="editposition === true"> <el-col :span="4" v-if="editphone === true">
<el-button type="success" @click="savePositionValue" plain <el-button type="success" @click="savePhone" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat"> style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat">
保存 保存
</el-button>
</el-col>
</el-row>
</el-form-item>
<el-form-item v-if="editphone === true">
<el-row :gutter="10">
<el-col :span="12">
<el-input v-model="userinfo.auth_key" prefix-icon="el-icon-mobile" placeholder="验证码"
maxlength="6"></el-input>
</el-col>
<el-col :span="6">
<el-button type="info" @click="getsmsemailcode('sms',userinfo.mobile)" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 40px;background-color: #ecf5ff;color: #dd6161">
获取验证码
</el-button> </el-button>
</el-col> </el-col>
</el-row> </el-row>
</el-form-item> </el-form-item>
@ -54,15 +64,15 @@
<el-form-item> <el-form-item>
<el-row> <el-row>
<el-col :span="18"> <el-col :span="18">
<el-input v-model="userinfo.mobile" ref="phone" :readonly="editphone !== true" <el-input v-model="userinfo.email" ref="email" :readonly="editemail !== true"
prefix-icon="el-icon-mobile" placeholder="手机" maxlength="11"></el-input> prefix-icon="el-icon-bank-card" placeholder="邮箱" maxlength="20"></el-input>
</el-col> </el-col>
<el-col :span="2"> <el-col :span="2">
<el-button icon="el-icon-edit" @click="changePhoneValue"> <el-button icon="el-icon-edit" @click="changeemailValue">
</el-button> </el-button>
</el-col> </el-col>
<el-col :span="4" v-if="editphone === true"> <el-col :span="4" v-if="editemail === true">
<el-button type="success" @click="savePhone" plain <el-button type="success" @click="saveemail" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat"> style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat">
保存 保存
</el-button> </el-button>
@ -70,14 +80,30 @@
</el-row> </el-row>
</el-form-item> </el-form-item>
<el-form-item v-if="editphone === true">
<el-form-item style="height: 40px" v-if="editemail === true">
<el-row style="height: 40px" :gutter="10">
<el-col :span="11">
<el-input placeholder="请输入图片验证码" v-model="userinfo.authcode" maxlength="6"></el-input>
</el-col>
<el-col :span="8">
<el-image
style="margin:0px 4px;border-radius:4px;cursor:pointer;height: 40px"
:src="cptch.cptch_image"
fit="contain" @click="get_auth_code">
</el-image>
</el-col>
</el-row>
</el-form-item>
<el-form-item v-if="editemail === true">
<el-row :gutter="10"> <el-row :gutter="10">
<el-col :span="12"> <el-col :span="12">
<el-input v-model="userinfo.sms_code" prefix-icon="el-icon-mobile" placeholder="验证码" <el-input v-model="userinfo.auth_key" prefix-icon="el-icon-mobile" placeholder="验证码"
maxlength="6"></el-input> maxlength="6"></el-input>
</el-col> </el-col>
<el-col :span="6"> <el-col :span="6">
<el-button type="info" @click="getphonecode" plain <el-button type="info" @click="getsmsemailcode('email',userinfo.email)" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 40px;background-color: #ecf5ff;color: #dd6161"> style="margin:0 4px;border-radius:4px;cursor:pointer;height: 40px;background-color: #ecf5ff;color: #dd6161">
获取验证码 获取验证码
</el-button> </el-button>
@ -86,6 +112,48 @@
</el-row> </el-row>
</el-form-item> </el-form-item>
<el-form-item>
<el-row>
<el-col :span="18">
<el-input v-model="userinfo.domain_name" :readonly="editdomain_name !== true" ref="domain_name"
prefix-icon="el-icon-download"
placeholder="下载页域名"></el-input>
</el-col>
<el-col :span="2">
<el-button icon="el-icon-edit" @click="changeDomainValue">
</el-button>
</el-col>
<el-col :span="4" v-if="editdomain_name === true">
<el-button type="success" @click="saveDomain" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat">
保存
</el-button>
</el-col>
</el-row>
</el-form-item>
<el-form-item>
<el-row>
<el-col :span="18">
<el-input v-model="userinfo.job" ref="position" :readonly="editposition !== true"
prefix-icon="el-icon-postcard" placeholder="职位"></el-input>
</el-col>
<el-col :span="2">
<el-button icon="el-icon-edit" @click="changePositionValue">
</el-button>
</el-col>
<el-col :span="4" v-if="editposition === true">
<el-button type="success" @click="savePositionValue" plain
style="margin:0 4px;border-radius:4px;cursor:pointer;height: 36px;background-color: #f56c6c;color: wheat">
保存
</el-button>
</el-col>
</el-row>
</el-form-item>
</el-form> </el-form>
@ -93,7 +161,7 @@
</template> </template>
<script> <script>
import {userinfos, getAuthTokenFun} from '../restful' import {userinfos, getAuthcTokenFun, registerFun} from '../restful'
import {deepCopy} from "../utils"; import {deepCopy} from "../utils";
export default { export default {
@ -105,10 +173,38 @@
}, },
orguserinfo: {}, orguserinfo: {},
editphone: false, editphone: false,
editemail: false,
editdomain_name: false, editdomain_name: false,
editposition: false edituser_name: false,
editposition: false,
cptch: '',
} }
}, methods: { }, methods: {
get_auth_code() {
registerFun(data => {
if (data.code === 1000) {
this.cptch = data.data;
this.userinfo.cptch_key = this.cptch.cptch_key;
} else {
this.$message({
message: data.msg,
type: 'error'
});
}
}, {
"methods": "GET",
"data": {}
});
},
saveemail() {
this.updateUserInfo({"methods": 'PUT', 'data': this.userinfo});
this.changeemailValue()
},
saveUsername() {
this.updateUserInfo({"methods": 'PUT', 'data': this.userinfo});
this.changeUsernameValue()
},
saveDomain() { saveDomain() {
this.updateUserInfo({"methods": 'PUT', 'data': this.userinfo}); this.updateUserInfo({"methods": 'PUT', 'data': this.userinfo});
this.changeDomainValue() this.changeDomainValue()
@ -122,24 +218,29 @@
this.changePhoneValue() this.changePhoneValue()
}, },
updateUserInfo(datainfo) { updateUserInfo(datainfo) {
if (datainfo.data.username.toString().length < 6) {
this.$message.error("密码至少6位");
return
}
userinfos(data => { userinfos(data => {
if (data.code === 1000) { if (data.code === 1000) {
let phonenumber = null; // let phonenumber = null;
if (data.data.sms_code) { // if (data.data.sms_code) {
phonenumber = this.userinfo.mobile; // phonenumber = this.userinfo.mobile;
this.$notify({ // this.$notify({
title: '验证码', // title: '',
message: '您正在修改手机号码,验证码为:' + data.data.sms_code, // message: ':' + data.data.sms_code,
type: 'success' // type: 'success'
}); // });
} // }
this.userinfo = data.data; this.userinfo = data.data;
this.$store.dispatch("doUserinfo", data.data); this.$store.dispatch("doUserinfo", data.data);
this.orguserinfo = deepCopy(data.data); this.orguserinfo = deepCopy(data.data);
if (phonenumber) { // if (phonenumber) {
this.userinfo.mobile = phonenumber; // this.userinfo.mobile = phonenumber;
} // }
if (datainfo.data) { if (datainfo.data) {
this.$message.success("更新成功") this.$message.success("更新成功")
@ -152,6 +253,16 @@
} }
}, datainfo) }, datainfo)
}, },
changeemailValue() {
this.get_auth_code();
this.editemail = !this.editemail;
if (this.$refs.email.$el.children[0].style.backgroundColor) {
this.$refs.email.$el.children[0].style.backgroundColor = ''
} else {
this.$refs.email.$el.children[0].style.backgroundColor = '#f6ffdc';
}
},
changePhoneValue() { changePhoneValue() {
this.editphone = !this.editphone; this.editphone = !this.editphone;
if (this.$refs.phone.$el.children[0].style.backgroundColor) { if (this.$refs.phone.$el.children[0].style.backgroundColor) {
@ -170,6 +281,14 @@
} }
}, },
changeUsernameValue() {
this.edituser_name = !this.edituser_name;
if (this.$refs.user_name.$el.children[0].style.backgroundColor) {
this.$refs.user_name.$el.children[0].style.backgroundColor = ''
} else {
this.$refs.user_name.$el.children[0].style.backgroundColor = '#f6ffdc';
}
},
changeDomainValue() { changeDomainValue() {
this.editdomain_name = !this.editdomain_name; this.editdomain_name = !this.editdomain_name;
if (this.$refs.domain_name.$el.children[0].style.backgroundColor) { if (this.$refs.domain_name.$el.children[0].style.backgroundColor) {
@ -178,20 +297,29 @@
this.$refs.domain_name.$el.children[0].style.backgroundColor = '#f6ffdc'; this.$refs.domain_name.$el.children[0].style.backgroundColor = '#f6ffdc';
} }
}, },
getphonecode() { getsmsemailcode(act, target) {
getAuthTokenFun(data => { let picode = {
"authcode": this.userinfo.authcode,
"cptch_key": this.cptch.cptch_key,
};
getAuthcTokenFun(data => {
if (data.code === 1000) { if (data.code === 1000) {
this.userinfo.act = act;
let msg = '您正在修改手机号码,验证码已经发送您手机';
if (act === "email") {
msg = '您正在修改邮箱,验证码已经发送您邮箱';
}
this.$notify({ this.$notify({
title: '验证码', title: '验证码',
message: '您正在修改手机号码,验证码已经发送您手机', message: msg,
type: 'success' type: 'success'
}); });
}
this.userinfo.auth_token = data.data.auth_token; this.userinfo.auth_token = data.data.auth_token;
} else {
this.$message.error(data.msg)
}
}, {"methods": 'GET', 'data': {'act': 'sms', 'phone': this.userinfo.mobile}}) }, {"methods": 'GET', 'data': {'act': act, 'target': target, 'ext': picode}})
// this.updateUserInfo({"methods": 'GET', 'data': {'act': 'sms','phone':this.userinfo.mobile}});
} }
}, mounted() { }, mounted() {
this.$store.dispatch('douserInfoIndex', 0); this.$store.dispatch('douserInfoIndex', 0);

@ -190,6 +190,21 @@ export function getAuthTokenFun(callBack, params, load = true) {
); );
} }
/**获取信息修改token */
export function getAuthcTokenFun(callBack, params, load = true) {
getData(
params.methods,
USERSEVER + '/authc',
params.data,
data => {
callBack(data);
},
load,
true,
true
);
}
/**用户注册 */ /**用户注册 */
export function registerFun(callBack, params, load = true) { export function registerFun(callBack, params, load = true) {
getData( getData(

@ -3,7 +3,7 @@ from django.db import models
# Create your models here. # Create your models here.
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from api.utils.app.randomstrings import make_random_uuid, make_app_uuid from api.utils.app.randomstrings import make_random_uuid
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser

@ -16,7 +16,7 @@ Including another URLconf
from django.contrib import admin from django.contrib import admin
from django.urls import path, re_path, include from django.urls import path, re_path, include
from api.views.login import LoginView, UserInfoView, RegistView, AuthorizationView from api.views.login import LoginView, UserInfoView, RegistView, AuthorizationView, ChangeAuthorizationView
from api.views.logout import LogoutView from api.views.logout import LogoutView
from api.views.apps import AppsView, AppInfoView, AppReleaseinfoView from api.views.apps import AppsView, AppInfoView, AppReleaseinfoView
from api.views.download import ShortDownloadView from api.views.download import ShortDownloadView
@ -33,6 +33,7 @@ urlpatterns = [
# path("",include(router.urls)), # path("",include(router.urls)),
re_path("^login", LoginView.as_view()), re_path("^login", LoginView.as_view()),
re_path("^auth", AuthorizationView.as_view()), re_path("^auth", AuthorizationView.as_view()),
re_path("^authc", ChangeAuthorizationView.as_view()),
re_path("^register", RegistView.as_view()), re_path("^register", RegistView.as_view()),
re_path("^logout", LogoutView.as_view()), re_path("^logout", LogoutView.as_view()),
re_path("^apps$", AppsView.as_view()), re_path("^apps$", AppsView.as_view()),

@ -6,12 +6,12 @@
import os, re import os, re
from fir_ser.settings import SUPER_SIGN_ROOT, SERVER_DOMAIN, CAPTCHA_LENGTH, MEDIA_ROOT from fir_ser.settings import SUPER_SIGN_ROOT, SERVER_DOMAIN, CAPTCHA_LENGTH, MEDIA_ROOT
from api.models import APPSuperSignUsedInfo, APPToDeveloper, \ from api.models import APPSuperSignUsedInfo, APPToDeveloper, \
UDIDsyncDeveloper UDIDsyncDeveloper, UserInfo
from api.utils.app.randomstrings import make_app_uuid from api.utils.app.randomstrings import make_app_uuid
from api.utils.storage.localApi import LocalStorage from api.utils.storage.localApi import LocalStorage
from api.utils.storage.storage import Storage from api.utils.storage.storage import Storage
from api.utils.tempcaches import tmpCache from api.utils.tempcaches import tmpCache
from api.utils.TokenManager import DownloadToken, generateNumericTokenOfLength from api.utils.TokenManager import DownloadToken, generateNumericTokenOfLength, generateAlphanumericTokenOfLength
from api.utils.sendmsg.sendmsg import SendMessage from api.utils.sendmsg.sendmsg import SendMessage
from django.db.models import Sum from django.db.models import Sum
from captcha.models import CaptchaStore from captcha.models import CaptchaStore
@ -164,3 +164,17 @@ def is_valid_sender_code(key, token, code):
def get_sender_email_token(key, email): def get_sender_email_token(key, email):
sender = SendMessage('email') sender = SendMessage('email')
return get_sender_token(sender, key, email) return get_sender_token(sender, key, email)
def check_username_exists(username):
user_obj = UserInfo.objects.filter(username=username).values("username").first()
if user_obj and user_obj['username'] == username:
return True
return False
def get_random_username(length=16):
username = generateAlphanumericTokenOfLength(length)
if check_username_exists(username):
return get_random_username(length)
return username

@ -7,20 +7,165 @@ from rest_framework.views import APIView
import binascii import binascii
import os, datetime, json import os, datetime, json
from api.utils.utils import get_captcha, valid_captcha, is_valid_domain, is_valid_phone, \ from api.utils.utils import get_captcha, valid_captcha, is_valid_domain, is_valid_phone, \
get_sender_sms_token, is_valid_email, is_valid_sender_code, get_sender_email_token get_sender_sms_token, is_valid_email, is_valid_sender_code, get_sender_email_token, get_random_username, \
check_username_exists
from api.utils.auth import ExpiringTokenAuthentication from api.utils.auth import ExpiringTokenAuthentication
from api.utils.response import BaseResponse from api.utils.response import BaseResponse
from django.middleware import csrf from fir_ser.settings import CACHE_KEY_TEMPLATE, SERVER_DOMAIN, REGISTER, LOGIN
from fir_ser.settings import CACHE_KEY_TEMPLATE, SERVER_DOMAIN, REGISTER
from api.utils.storage.caches import login_auth_failed, set_default_app_wx_easy from api.utils.storage.caches import login_auth_failed, set_default_app_wx_easy
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def get_token(request): def get_login_type():
token = csrf.get_token(request) return LOGIN.get("login_type")
return {'csrf_token': token}
def get_register_type():
return REGISTER.get("register_type")
def GetAuthenticate(target, password, act, allow_type):
user_obj = None
if act == 'email' and allow_type[act]:
if is_valid_email(target):
user_obj = UserInfo.objects.filter(email=target).values('username').first()
elif act == 'sms' and allow_type[act]:
if is_valid_phone(target):
user_obj = UserInfo.objects.filter(mobile=target).values('username').first()
elif act == 'up' and allow_type[act]:
user_obj = auth.authenticate(username=target, password=password)
if user_obj and act in ['email', 'sms']:
user_obj = auth.authenticate(username=user_obj['username'], password=password)
return user_obj
def CheckRegisterUerinfo(target, act, key):
res = BaseResponse()
res.data = {}
times_key = "%s_%s_%s" % (key, act, target)
if key == "register":
if not get_register_type()[act]:
res.code = 1002
res.msg = "暂不允许该类型注册"
return res
if act == "sms":
if is_valid_phone(target):
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(mobile=target):
res.code = 1005
res.msg = "手机号已经存在"
else:
token, code = get_sender_sms_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "该手机号今日注册次数已经达到上限"
else:
res.code = 1005
res.msg = "手机号校验失败"
elif act == "email":
if is_valid_email(target):
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(email=target):
res.code = 1005
res.msg = "邮箱已经存在"
else:
token, code = get_sender_email_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "该邮箱今日注册次数已经达到上限"
else:
res.code = 1006
res.msg = "邮箱校验失败"
elif act == "up":
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(username=target):
res.code = 1005
res.msg = "用户名已经存在"
else:
token, code = get_sender_email_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "用户名已经存在"
else:
res.code = 1007
res.msg = "信息发送失败"
return res
def CheckChangeUerinfo(target, act, key, user):
res = BaseResponse()
res.data = {}
if key == "change":
if not get_login_type()[act]:
res.code = 1002
res.msg = "暂不允许该类型修改"
return res
times_key = "%s_%s_%s" % (user.uid, act, target)
if act == "sms":
if is_valid_phone(target) and str(user.mobile) != str(target):
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(mobile=target):
res.code = 1005
res.msg = "手机号已经存在"
else:
token, code = get_sender_sms_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "该手机号今日注册次数已经达到上限"
else:
res.code = 1005
res.msg = "手机号校验失败"
elif act == "email":
if is_valid_email(target) and str(user.email) != str(target):
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(email=target):
res.code = 1005
res.msg = "邮箱已经存在"
else:
token, code = get_sender_email_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "该邮箱今日注册次数已经达到上限"
else:
res.code = 1006
res.msg = "邮箱校验失败"
elif act == "up":
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(username=target):
res.code = 1005
res.msg = "用户名已经存在"
else:
token, code = get_sender_email_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "用户名已经存在"
else:
res.code = 1007
res.msg = "信息发送失败"
return res
class LoginView(APIView): class LoginView(APIView):
@ -33,11 +178,12 @@ class LoginView(APIView):
username = receive.get("username", None) username = receive.get("username", None)
is_valid = valid_captcha(receive.get("cptch_key", None), receive.get("authcode", None), username) is_valid = valid_captcha(receive.get("cptch_key", None), receive.get("authcode", None), username)
if is_valid: if is_valid:
login_type = receive.get("login_type", None)
if login_auth_failed("get", username): if login_auth_failed("get", username):
password = receive.get("password") password = receive.get("password")
user = auth.authenticate(username=username, password=password) user = GetAuthenticate(username, password, login_type, get_login_type())
logger.info("username:%s password:%s" % (username, password)) logger.info("username:%s password:%s" % (username, password))
if user is not None: if user:
if user.is_active: if user.is_active:
login_auth_failed("del", username) login_auth_failed("del", username)
# update the token # update the token
@ -59,13 +205,14 @@ class LoginView(APIView):
response.code = 1005 response.code = 1005
else: else:
login_auth_failed("set", username) login_auth_failed("set", username)
try: #
UserInfo.objects.get(username=username) # try:
# UserInfo.objects.get(username=username)
response.msg = "密码或者账户有误" response.msg = "密码或者账户有误"
response.code = 1002 response.code = 1002
except UserInfo.DoesNotExist: # except UserInfo.DoesNotExist:
response.msg = "用户不存在!" # response.msg = "用户不存在!"
response.code = 1003 # response.code = 1003
else: else:
response.code = 1006 response.code = 1006
logger.error("username:%s failed too try , locked" % (username,)) logger.error("username:%s failed too try , locked" % (username,))
@ -78,7 +225,9 @@ class LoginView(APIView):
def get(self, request): def get(self, request):
response = BaseResponse() response = BaseResponse()
response.data = {}
response.data = get_captcha() response.data = get_captcha()
response.data['login_type'] = get_login_type()
return Response(response.dict) return Response(response.dict)
@ -91,28 +240,39 @@ class RegistView(APIView):
receive = request.data receive = request.data
username = receive.get("username", None) username = receive.get("username", None)
act = 'sms'
if is_valid_email(username): if is_valid_email(username):
act = 'email' act = 'email'
elif is_valid_phone(username):
act = 'sms'
else:
response.code = 1001
response.msg = "邮箱或手机校验有误"
return Response(response.dict)
if not get_register_type()[act]:
response.code = 1002
response.msg = "不允许该类型注册"
return Response(response.dict)
is_valid, target = is_valid_sender_code(act, receive.get("auth_token", None), receive.get("auth_key", None)) is_valid, target = is_valid_sender_code(act, receive.get("auth_token", None), receive.get("auth_key", None))
if is_valid and str(target) == str(username): if is_valid and str(target) == str(username):
if login_auth_failed("get", username): if login_auth_failed("get", username):
password = receive.get("password") password = receive.get("password")
password2 = receive.get("password2") password2 = receive.get("password2")
if password == password2: if password == password2:
try: random_username = get_random_username()
UserInfo.objects.get(username=username)
login_auth_failed("set", username)
response.msg = "邮箱已经存在,请更换其他邮箱"
response.code = 1002
except UserInfo.DoesNotExist:
if is_valid_email(username): if is_valid_email(username):
user_obj = UserInfo.objects.create_user(username, email=username, password=password, user_obj = UserInfo.objects.create_user(random_username, email=username, password=password,
first_name=username[:8]) first_name=random_username[:8])
elif is_valid_phone(username):
user_obj = UserInfo.objects.create_user(random_username, mobile=username, password=password,
first_name=random_username[:8])
else: else:
user_obj = UserInfo.objects.create_user(username, mobile=username, password=password, user_obj = None
first_name=username[:8]) response.msg = "注册异常"
response.code = 1000
if user_obj: if user_obj:
response.msg = "注册成功" response.msg = "注册成功"
response.code = 1000 response.code = 1000
@ -135,7 +295,7 @@ class RegistView(APIView):
allow_f = REGISTER.get("enable") allow_f = REGISTER.get("enable")
if allow_f: if allow_f:
response.data = get_captcha() response.data = get_captcha()
response.data['ways'] = REGISTER.get("ways") response.data['register_type'] = get_register_type()
response.data['enable'] = allow_f response.data['enable'] = allow_f
return Response(response.dict) return Response(response.dict)
@ -159,6 +319,12 @@ class UserInfoView(APIView):
oldpassword = data.get("oldpassword", None) oldpassword = data.get("oldpassword", None)
surepassword = data.get("surepassword", None) surepassword = data.get("surepassword", None)
is_valid = valid_captcha(data.get("cptch_key", None), data.get("authcode", None), request)
if not is_valid:
res.code = 1008
res.msg = "图片验证码异常"
return Response(res.dict)
if oldpassword and surepassword: if oldpassword and surepassword:
user = auth.authenticate(username=request.user.username, password=oldpassword) user = auth.authenticate(username=request.user.username, password=oldpassword)
if user is not None: if user is not None:
@ -211,23 +377,46 @@ class UserInfoView(APIView):
Apps.objects.filter(user_id=request.user).update(wxeasytype=True) Apps.objects.filter(user_id=request.user).update(wxeasytype=True)
set_default_app_wx_easy(request.user) set_default_app_wx_easy(request.user)
username = data.get("username", None)
if username and username != request.user.username:
if check_username_exists(username):
res.msg = "用户名已经存在"
logger.error("User %s info save failed. Excepiton:%s" % (request.user, 'username already exists'))
return Response(res.dict)
if len(username) < 6:
res.msg = "用户名至少6位"
return Response(res.dict)
request.user.job = data.get("job", request.user.job) request.user.job = data.get("job", request.user.job)
request.user.first_name = data.get("first_name", request.user.first_name) request.user.first_name = data.get("first_name", request.user.first_name)
request.user.username = data.get("username", request.user.username)
sms_token = data.get("auth_token", None) sms_token = data.get("auth_token", None)
if sms_token: if sms_token:
status, target = is_valid_sender_code(request.user.uid, sms_token, data.get("sms_code", None)) act = data.get("act", None)
mobile = data.get("mobile", request.user.mobile) status, target = is_valid_sender_code(act, data.get("auth_token", None), data.get("auth_key", None))
if target == mobile: if status:
mobile = data.get("mobile", None)
email = data.get("email", None)
if act == 'sms' and mobile:
if str(target) == str(mobile):
if is_valid_phone(mobile): if is_valid_phone(mobile):
request.user.mobile = data.get("mobile", request.user.mobile) request.user.mobile = data.get("mobile", request.user.mobile)
else: else:
res.code = 1005 res.code = 1005
res.msg = "手机号异常" res.msg = "手机号异常"
elif act == 'email' and email:
if str(target) == str(email):
if is_valid_email(email):
request.user.email = data.get("email", request.user.email)
else:
res.code = 1005
res.msg = "邮箱异常"
if res.code != 1000:
return Response(res.dict) return Response(res.dict)
else: else:
res.code = 1005 res.code = 1005
res.msg = "手机号校验失败" res.msg = "验证码校验失败"
return Response(res.dict) return Response(res.dict)
try: try:
@ -247,7 +436,6 @@ class UserInfoView(APIView):
class AuthorizationView(APIView): class AuthorizationView(APIView):
def get(self, request): def get(self, request):
res = BaseResponse() res = BaseResponse()
res.data = {} res.data = {}
@ -256,8 +444,8 @@ class AuthorizationView(APIView):
ext = request.query_params.get("ext", None) ext = request.query_params.get("ext", None)
if ext: if ext:
ext = json.loads(ext) ext = json.loads(ext)
ways = REGISTER.get("ways") register_type = get_register_type()
if ways.get('code') and ext and ext.get('icode'): if register_type.get('code') and ext and ext.get('icode'):
if ext.get('icode') == '689888666': if ext.get('icode') == '689888666':
pass pass
else: else:
@ -272,60 +460,13 @@ class AuthorizationView(APIView):
res.msg = "图片验证码有误" res.msg = "图片验证码有误"
return Response(res.dict) return Response(res.dict)
times_key = "register_%s_%s" % (act, target) res = CheckRegisterUerinfo(target, act, 'register')
if act == "sms":
if is_valid_phone(target):
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(mobile=target):
res.code = 1005
res.msg = "手机号已经存在"
else:
token, code = get_sender_sms_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "该手机号今日注册次数已经达到上限"
else:
res.code = 1005
res.msg = "手机号校验失败"
elif act == "email":
if is_valid_email(target):
if login_auth_failed("get", times_key):
login_auth_failed("set", times_key)
if UserInfo.objects.filter(email=target):
res.code = 1005
res.msg = "邮箱已经存在"
else:
token, code = get_sender_email_token(act, target)
res.data["auth_token"] = token
else:
res.code = 1009
res.msg = "该邮箱今日注册次数已经达到上限"
else:
res.code = 1006
res.msg = "邮箱校验失败"
elif act == "ways":
if ways['sms']:
pass
elif ways['email']:
pass
elif ways['code']:
pass
else:
pass
else:
res.code = 1007
res.msg = "信息发送失败"
return Response(res.dict) return Response(res.dict)
class AuthorizationViewbak(APIView): class ChangeAuthorizationView(APIView):
# authentication_classes = [ExpiringTokenAuthentication, ] authentication_classes = [ExpiringTokenAuthentication, ]
def get(self, request): def get(self, request):
res = BaseResponse() res = BaseResponse()
@ -333,43 +474,14 @@ class AuthorizationViewbak(APIView):
act = request.query_params.get("act", None) act = request.query_params.get("act", None)
target = request.query_params.get("target", None) target = request.query_params.get("target", None)
ext = request.query_params.get("ext", None) ext = request.query_params.get("ext", None)
ways = REGISTER.get("ways") if ext:
if ways.get('code') and ext: ext = json.loads(ext)
if ext == '689888666': if ext and valid_captcha(ext.get("cptch_key", None), ext.get("authcode", None), target):
pass pass
else: else:
res.code = 1008 res.code = 1008
res.msg = "邀请码已失效" res.msg = "图片验证码有误"
return Response(res.dict) return Response(res.dict)
if act == "sms": res = CheckChangeUerinfo(target, act, 'change', request.user)
if is_valid_phone(target) and str(request.user.mobile) != str(target):
token, code = get_sender_sms_token(request.user.uid, target)
res.data["auth_token"] = token
else:
res.code = 1005
res.msg = "手机号校验失败"
elif act == "email":
if is_valid_email(target) and str(request.user.email) != str(target):
token, code = get_sender_email_token(request.user.uid, target)
res.data["auth_token"] = token
else:
res.code = 1006
res.msg = "邮箱校验失败"
elif act == "ways":
if ways['sms']:
pass
elif ways['email']:
pass
elif ways['code']:
pass
else:
pass
else:
res.code = 1007
res.msg = "信息发送失败"
return Response(res.dict) return Response(res.dict)

Loading…
Cancel
Save