#手机验证码

This commit is contained in:
Bob 2020-10-13 21:33:48 +08:00
parent 3c976c69d8
commit 84b8ee5a73
9 changed files with 434 additions and 156 deletions

View File

@ -24,7 +24,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'tj5m7-ns_6x_fvn2^q+7+2fopq!#7taqv!9ai(c_45i5!%m=*z'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
DEBUG = True
ALLOWED_HOSTS = ['*']

View File

@ -605,3 +605,9 @@ class News(models.Model):
def __str__(self):
return self.title
#手机验证码验证表
class CheckCode(models.Model):
phone_code = models.CharField('手机验证码',max_length=256,null=True,blank=True)
phone = models.CharField('电话号',max_length=256,null=True,blank=True)
c_time = models.DateField('时间',null=True,blank=True)

View File

@ -0,0 +1,133 @@
{% extends 'dashboard/base/base.html' %}
{% load static %}
{% block css %}
<style>
body.login_page {
background-color: rgba(116, 77, 144, 1.0)
/*#744d90*/;
background-image: url('{% static 'image/login-bg.png' %}');
background-attachment: fixed;
height: 100%;
max-height: 100%;
min-height: 99%;
overflow: hidden;
width: 100%;
}
.loginpage h1 a {
height: 92px;
margin: 0px auto 0px auto;
padding: 0;
text-decoration: none;
-moz-background-size: 345px 92px;
-o-background-size: 345px 92px;
background-size: 345px 92px;
background-color: transparent;
min-height: 92px;
width: auto;
background-image: url("{% static 'image/login-logo.png' %}");
background-position: center top;
background-repeat: no-repeat;
text-indent: -9999px;
outline: 0;
overflow: hidden;
display: block;
}
</style>
{% endblock %}
{% block header %} {% endblock %}
{% block content %}
<body class=" login_page">
<div class="login-wrapper">
{% if messages %}
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">&times;</span>
<span class="sr-only">Close</span>
</button>
{% for message in messages %}
{{ message }}.<br/>
{% endfor %}
</div>
{% endif %}
<div id="login"
class="login loginpage col-lg-offset-4 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-offset-2 col-xs-8">
<h1><a href="#" title="Login Page" tabindex="-1">Ultra Admin</a></h1>
<form name="loginform" id="loginform" action="{% url 'dashboard-login-for-phone' %}" method="post">{% csrf_token %}
<p>
<label for="user_login">手机号<br/>
<input type="text" name="username" id="user_login" class="input" size="20" placeholder="请输入手机号"/><button type="button" class="btn btn-success">获取验证码</button></label>
</p>
<p>
<label for="user_pass">验证码<br/>
<input type="text" name="password" id="user_pass" class="input" size="20"
placeholder="请输入验证码"/></label>
</p>
<p class="submit">
<input type="submit" name="wp-submit" id="wp-submit" class="btn btn-orange btn-block"
value="登录"/>
</p>
</form>
<p id="nav">
<a class="pull-left" href="#" title="Password Lost and Found">忘记密码</a>
<a href="#" title="Password Lost and Found" style="margin-left: 30%">账号登录</a>
<a class="pull-right" href="{% url 'dashboard-register' %}" title="Sign Up">注册</a>
</p>
</div>
</div>
<!-- LOAD FILES AT PAGE END FOR FASTER LOADING -->
<!-- General section box modal start -->
<div class="modal" id="section-settings" tabindex="-1" role="dialog" aria-labelledby="ultraModal-Label"
aria-hidden="true">
<div class="modal-dialog animated bounceInDown">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title">Section Settings</h4>
</div>
<div class="modal-body">
Body goes here...
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
<button class="btn btn-success" type="button">Save changes</button>
</div>
</div>
</div>
</div>
<!-- modal end -->
</body>
{% endblock %}
{% block add_js %}
<script>
$(function () {
$(".next-captcha").click(function (e) {
e.preventDefault();
$.getJSON("{% url 'refresh-captcha' %}", function (json) {
// This should update your captcha image src and captcha hidden input
// debugger;
var status = json['status'];
console.log(status);
console.log("6666666666666666666666666666666");
var new_cptch_key = json['new_cptch_key'];
var new_cptch_image = json['new_cptch_image'];
id_captcha_0 = $("#id_reg_captcha_0");
img = $(".captcha");
id_captcha_0.attr("value", new_cptch_key);
img.attr("src", new_cptch_image);
});
});
})
</script>
{% endblock %}

View File

@ -93,6 +93,7 @@
</form>
<p id="nav">
<a class="pull-left" href="#" title="Password Lost and Found">忘记密码</a>
<a href="{% url 'dashboard-login-for-phone' %}" title="Password Lost and Found" style="margin-left: 30%">手机号登录</a>
<a class="pull-right" href="{% url 'dashboard-register' %}" title="Sign Up">注册</a>
</p>

View File

@ -10,7 +10,6 @@
{% endfor %}
</ul>
<script>
$(function () {
console.log("2222222222222222")
$('.autocomplete-panel-item').click(function (e) {

40
dashboard/test.py Normal file
View File

@ -0,0 +1,40 @@
import http.client
from urllib import parse
import json
#服务地址
sms_host = "sms.yunpian.com"
voice_host = "voice.yunpian.com"
#端口号
port = 443
#版本号
version = "v2"
#模板短信接口的URI
sms_tpl_send_uri = "/" + version + "/sms/tpl_single_send.json"
def tpl_send_sms(apikey, tpl_id, tpl_value, mobile):
"""
模板接口发短信
"""
params = parse.urlencode({
'apikey': apikey,
'tpl_id': tpl_id,
'tpl_value': parse.urlencode(tpl_value),
'mobile': mobile
})
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
conn = http.client.HTTPSConnection(sms_host, port=port, timeout=30)
conn.request("POST", sms_tpl_send_uri, params, headers)
response = conn.getresponse()
response_str = response.read()
conn.close()
return response_str
#【甘肃大未来科技】政务新媒体监测预警:#dateStart#至#dateEnd##type# #name# 无更新,请予以关注提醒。
apikey = "304eb08353f7ebf00596737acfc31f53"
mobile = "18119305139"
tpl_id = 4041392 #【甘肃大未来科技】政务新媒体监测预警:#dateStart#至#dateEnd##type# #name# 无更新,请予以关注提醒。
tpl_value = {'#dateStart#':'10月1日','#dateEnd#':'10日','#type#':'微信公众号','#name#':'武山县人民政府网'}
print (tpl_send_sms(apikey, tpl_id, tpl_value, mobile) )

View File

@ -6,6 +6,9 @@ from dashboard import views
urlpatterns = [
path('index/', views.index, name='dashboard-index'),
path('', views.user_login, name='dashboard-login'),
path('user/login/for/phone/', views.user_login_for_phone, name='dashboard-login-for-phone'),
#发送手机验证码
path('author/code/',views.author_code,name='author-code'),
path('refresh_captcha/', views.refresh_captcha, name='refresh-captcha'),
path('logout/', views.user_logout, name='dashboard-logout'),
path('register/', views.register, name='dashboard-register'),

View File

@ -1,8 +1,12 @@
import json
import http.client
import random
import time
from urllib import parse
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from dateutil import relativedelta
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.models import User
@ -12,7 +16,9 @@ from django.shortcuts import render
import datetime
# Create your views here.
from dashboard.models import Userprofile, Organization, Area_code_2020, Weixin, Weibo, Toutiao, Qita, News, Douyin
from dashboard.models import Userprofile, Organization, Area_code_2020, Weixin, Weibo, Toutiao, Qita, News, Douyin, \
CheckCode
from dashboard.yunpian import YunPian
def refresh_captcha(request):
@ -78,7 +84,72 @@ def user_login(request):
messages.error(request, '账号或密码错误,请您确认账号和密码')
return render(request, 'dashboard/login.html', {'hash_key': hash_key, 'image_url': image_url})
def user_login_for_phone(request):
if request.method == 'GET':
return render(request,'dashboard/login-for-phone.html')
elif request.method == 'POST':
p_code = request.POST.get('check_code')
phone = request.POST.get('phone')
try:
check_code = CheckCode.objects.get(phone_code=p_code, phone=phone)
if float(time.time()) - float(check_code.c_time) > 60:
check_code.delete()
return '验证码超时已被删除'
print(21333333333)
check_code.delete()
return '登录成功'
except:
print(1233333333)
def author_code(request):
sms_host = "sms.yunpian.com"
voice_host = "voice.yunpian.com"
# 端口号
port = 443
# 版本号
version = "v2"
# 模板短信接口的URI
sms_tpl_send_uri = "/" + version + "/sms/tpl_single_send.json"
# if request.method == 'GET':
# phone = request.POST.get('phone')
apikey = "304eb08353f7ebf00596737acfc31f53"
mobile = "18119305139"
tpl_id = 4041392
str = ""
for i in range(6):
ch = chr(random.randrange(ord('0'), ord('9') + 1))
str += ch
print(str)
tpl_value = {'#dateStart#': '10月1日', '#dateEnd#': '10日', '#type#': '微信公众号', '#name#': str}
params = parse.urlencode({
'apikey': apikey,
'tpl_id': tpl_id,
'tpl_value': parse.urlencode(tpl_value),
'mobile': mobile
})
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"
}
conn = http.client.HTTPSConnection(sms_host, port=port, timeout=30)
conn.request("POST", sms_tpl_send_uri, params, headers)
response = conn.getresponse()
response_str = response.read()
conn.close()
return response_str
# return HttpResponse('ok')
# a = YunPian(settings.API_KEY)
# a.send_sms(phone_code, mobile)
# try:
# check_code = CheckCode.objects.get(phone=mobile)
#
# check_code.phone_code = phone_code
# check_code.save()
# except:
# print(phone_code, mobile, 1111111111)
# check_code = CheckCode(phone_code=phone_code, phone=mobile)
# check_code.save()
# return JsonResponse({'data': '验证码发送成功'})
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
@ -93,7 +164,7 @@ def register(request):
# phone = None
image = None
flag = False
o = None
user_organization = None
sex = None
hash_key = CaptchaStore.generate_key()
image_url = captcha_image_url(hash_key)
@ -103,6 +174,7 @@ def register(request):
messages.error(request, '请选择单位')
else:
o = request.POST.get('organization')
user_organization = Organization.objects.get(name=o).id
if not request.POST.get('name'):
messages.error(request, '请输入姓名')
else:
@ -159,9 +231,10 @@ def register(request):
# user.is_staff = True
# user.first_name = phone
userprofile = Userprofile(name=name, image=image, user_id=user.id, organization_id=o, sex=sex, status=0)
user.save()
userprofile = Userprofile(name=name, image=image, user_id=user.id, organization_id=user_organization, sex=sex, status=0)
userprofile.save()
user.save()
messages.success(request, '注册成功,请登录')
return HttpResponseRedirect('/')
return render(request, 'dashboard/register.html',
@ -225,6 +298,7 @@ def get_organization(request):
topten_list = []
for i in o:
d = dict()
d['id'] = str(i.id)
d['name'] = i.name
if i.province:
d['province'] = Area_code_2020.objects.get(code=i.province).name

22
dashboard/yunpian.py Normal file
View File

@ -0,0 +1,22 @@
import requests
class YunPian(object):
def __init__(self, api_key):
self.api_key = api_key
self.single_send_url = 'https://sms.yunpian.com/v2/sms/single_send.json'
def send_sms(self, code, mobile):
params = {
'apikey': self.api_key,
'mobile': mobile,
'text': {'#dateStart#':'10月1日','#dateEnd#':'10日','#type#':'微信公众号','#name#':'武山县人民政府网'}
}
# text必须要跟云片后台的模板内容 保持一致,不然发送不出去!
r = requests.post(self.single_send_url, data=params)
print(r)
if __name__ == '__main__':
yun_pian = YunPian('304eb08353f7ebf00596737acfc31f53')
yun_pian.send_sms('1862', '18119305139')