jango用户登录界面

  1. """
  2. Django settings for cnblog project.
  3.  
  4. Generated by 'django-admin startproject' using Django 2.1.2.
  5.  
  6. For more information on this file, see
  7. https://docs.djangoproject.com/en/2.1/topics/settings/
  8.  
  9. For the full list of settings and their values, see
  10. https://docs.djangoproject.com/en/2.1/ref/settings/
  11. """
  12.  
  13. import os
  14.  
  15. # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  16. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  17.  
  18. # Quick-start development settings - unsuitable for production
  19. # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
  20.  
  21. # SECURITY WARNING: keep the secret key used in production secret!
  22. SECRET_KEY = '618*78-lmwto37@v+-7j-(wi#glc=sm_-d63fi5nv%o6zf8#+i'
  23.  
  24. # SECURITY WARNING: don't run with debug turned on in production!
  25. DEBUG = True
  26.  
  27. ALLOWED_HOSTS = []
  28.  
  29. # Application definition
  30.  
  31. INSTALLED_APPS = [
  32. 'django.contrib.admin',
  33. 'django.contrib.auth',
  34. 'django.contrib.contenttypes',
  35. 'django.contrib.sessions',
  36. 'django.contrib.messages',
  37. 'django.contrib.staticfiles',
  38. 'blog.apps.BlogConfig',
  39. ]
  40.  
  41. MIDDLEWARE = [
  42. 'django.middleware.security.SecurityMiddleware',
  43. 'django.contrib.sessions.middleware.SessionMiddleware',
  44. 'django.middleware.common.CommonMiddleware',
  45. 'django.middleware.csrf.CsrfViewMiddleware',
  46. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  47. 'django.contrib.messages.middleware.MessageMiddleware',
  48. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  49. ]
  50.  
  51. ROOT_URLCONF = 'cnblog.urls'
  52.  
  53. TEMPLATES = [
  54. {
  55. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  56. 'DIRS': [os.path.join(BASE_DIR, 'templates')]
  57. ,
  58. 'APP_DIRS': True,
  59. 'OPTIONS': {
  60. 'context_processors': [
  61. 'django.template.context_processors.debug',
  62. 'django.template.context_processors.request',
  63. 'django.contrib.auth.context_processors.auth',
  64. 'django.contrib.messages.context_processors.messages',
  65. 'social_django.context_processors.backends', # for oa auth2
  66. 'social_django.context_processors.login_redirect', # for oa auth2
  67. ],
  68. },
  69. },
  70. ]
  71.  
  72. WSGI_APPLICATION = 'cnblog.wsgi.application'
  73.  
  74. # Database
  75. # https://docs.djangoproject.com/en/2.1/ref/settings/#databases
  76.  
  77. # DATABASES = {
  78. # 'default': {
  79. # 'ENGINE': 'django.db.backends.sqlite3',
  80. # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
  81. # }
  82. # }
  83. DATABASES = {
  84. 'default': {
  85. 'ENGINE': 'django.db.backends.mysql',
  86. 'NAME': 'cnblog',
  87. 'USER': 'root',
  88. 'PASSWORD': '',
  89. 'HOST': 'localhost',
  90. 'PORT': '',
  91. }
  92. }
  93. AUTH_USER_MODEL = 'blog.UserInfo'
  94. # Password validation
  95. # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
  96.  
  97. AUTH_PASSWORD_VALIDATORS = [
  98. {
  99. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  100. },
  101. {
  102. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  103. },
  104. {
  105. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  106. },
  107. {
  108. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  109. },
  110. ]
  111.  
  112. # Internationalization
  113. # https://docs.djangoproject.com/en/2.1/topics/i18n/
  114.  
  115. LANGUAGE_CODE = 'en-us'
  116.  
  117. TIME_ZONE = 'Asia/Shanghai'
  118.  
  119. USE_I18N = True
  120.  
  121. USE_L10N = True
  122.  
  123. USE_TZ = True
  124.  
  125. # Static files (CSS, JavaScript, Images)
  126. # https://docs.djangoproject.com/en/2.1/howto/static-files/
  127.  
  128. STATIC_URL = '/static/'
  129. STATICFILES_DIRS = [
  130. os.path.join(BASE_DIR, 'static')
  131. ]

settings.py

  1. """cnblog URL Configuration
  2.  
  3. The `urlpatterns` list routes URLs to views. For more information please see:
  4. https://docs.djangoproject.com/en/2.1/topics/http/urls/
  5. Examples:
  6. Function views
  7. 1. Add an import: from my_app import views
  8. 2. Add a URL to urlpatterns: path('', views.home, name='home')
  9. Class-based views
  10. 1. Add an import: from other_app.views import Home
  11. 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
  12. Including another URLconf
  13. 1. Import the include() function: from django.urls import include, path
  14. 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
  15. """
  16. from django.contrib import admin
  17. from django.urls import path
  18. from django.conf.urls import url
  19. from blog import views
  20. from blog.check_views import pcgetcaptcha
  21. from blog.check_views import pcvalidate
  22. from blog.check_views import pcajax_validate
  23. from blog.check_views import mobileajax_validate
  24. from blog.check_views import home
  25. urlpatterns = [
  26. path('admin/', admin.site.urls),
  27. path('login/', views.login),
  28. path('get_validCode_img/', views.get_validCode_img),
  29. # 认证路由
  30. url(r'^pc-geetest/register', pcgetcaptcha, name='pcgetcaptcha'),
  31. url(r'^mobile-geetest/register', pcgetcaptcha, name='mobilegetcaptcha'),
  32. url(r'^pc-geetest/validate$', pcvalidate, name='pcvalidate'),
  33. url(r'^pc-geetest/ajax_validate',pcajax_validate, name='pcajax_validate'),
  34. url(r'^mobile-geetest/ajax_validate',mobileajax_validate, name='mobileajax_validate'),
  35. url(r'/*/', home, name='home'),
  36. ]

urls.py

  1. #!coding:utf8
  2. import sys
  3. import random
  4. import json
  5. import requests
  6. import time
  7. from hashlib import md5
  8.  
  9. if sys.version_info >= (3,):
  10. xrange = range
  11.  
  12. VERSION = "3.0.0"
  13.  
  14. class GeetestLib(object):
  15.  
  16. FN_CHALLENGE = "geetest_challenge"
  17. FN_VALIDATE = "geetest_validate"
  18. FN_SECCODE = "geetest_seccode"
  19.  
  20. GT_STATUS_SESSION_KEY = "gt_server_status"
  21.  
  22. API_URL = "http://api.geetest.com"
  23. REGISTER_HANDLER = "/register.php"
  24. VALIDATE_HANDLER = "/validate.php"
  25. JSON_FORMAT = False
  26.  
  27. def __init__(self, captcha_id, private_key):
  28. self.private_key = private_key
  29. self.captcha_id = captcha_id
  30. self.sdk_version = VERSION
  31. self._response_str = ""
  32.  
  33. def pre_process(self, user_id=None,new_captcha=1,JSON_FORMAT=1,client_type="web",ip_address=""):
  34. """
  35. 验证初始化预处理.
  36. //TO DO arrage the parameter
  37. """
  38. status, challenge = self._register(user_id,new_captcha,JSON_FORMAT,client_type,ip_address)
  39. self._response_str = self._make_response_format(status, challenge,new_captcha)
  40. return status
  41.  
  42. def _register(self, user_id=None,new_captcha=1,JSON_FORMAT=1,client_type="web",ip_address=""):
  43. pri_responce = self._register_challenge(user_id,new_captcha,JSON_FORMAT,client_type,ip_address)
  44. if pri_responce:
  45. if JSON_FORMAT == 1:
  46. response_dic = json.loads(pri_responce)
  47. challenge = response_dic["challenge"]
  48. else:
  49. challenge = pri_responce
  50. else:
  51. challenge=" "
  52. if len(challenge) == 32:
  53. challenge = self._md5_encode("".join([challenge, self.private_key]))
  54. return 1,challenge
  55. else:
  56. return 0, self._make_fail_challenge()
  57.  
  58. def get_response_str(self):
  59. return self._response_str
  60.  
  61. def _make_fail_challenge(self):
  62. rnd1 = random.randint(0, 99)
  63. rnd2 = random.randint(0, 99)
  64. md5_str1 = self._md5_encode(str(rnd1))
  65. md5_str2 = self._md5_encode(str(rnd2))
  66. challenge = md5_str1 + md5_str2[0:2]
  67. return challenge
  68.  
  69. def _make_response_format(self, success=1, challenge=None,new_captcha=1):
  70. if not challenge:
  71. challenge = self._make_fail_challenge()
  72. if new_captcha:
  73. string_format = json.dumps(
  74. {'success': success, 'gt':self.captcha_id, 'challenge': challenge,"new_captcha":True})
  75. else:
  76. string_format = json.dumps(
  77. {'success': success, 'gt':self.captcha_id, 'challenge': challenge,"new_captcha":False})
  78. return string_format
  79.  
  80. def _register_challenge(self, user_id=None,new_captcha=1,JSON_FORMAT=1,client_type="web",ip_address=""):
  81. if user_id:
  82. register_url = "{api_url}{handler}?gt={captcha_ID}&user_id={user_id}&json_format={JSON_FORMAT}&client_type={client_type}&ip_address={ip_address}".format(
  83. api_url=self.API_URL, handler=self.REGISTER_HANDLER, captcha_ID=self.captcha_id, user_id=user_id,new_captcha=new_captcha,JSON_FORMAT=JSON_FORMAT,client_type=client_type,ip_address=ip_address)
  84. else:
  85. register_url = "{api_url}{handler}?gt={captcha_ID}&json_format={JSON_FORMAT}&client_type={client_type}&ip_address={ip_address}".format(
  86. api_url=self.API_URL, handler=self.REGISTER_HANDLER, captcha_ID=self.captcha_id,new_captcha=new_captcha,JSON_FORMAT=JSON_FORMAT,client_type=client_type,ip_address=ip_address)
  87. try:
  88. response = requests.get(register_url, timeout=2)
  89. if response.status_code == requests.codes.ok:
  90. res_string = response.text
  91. else:
  92. res_string = ""
  93. except:
  94. res_string = ""
  95. return res_string
  96.  
  97. def success_validate(self, challenge, validate, seccode, user_id=None,gt=None,data='',userinfo='',JSON_FORMAT=1):
  98. """
  99. 正常模式的二次验证方式.向geetest server 请求验证结果.
  100. """
  101. if not self._check_para(challenge, validate, seccode):
  102. return 0
  103. if not self._check_result(challenge, validate):
  104. return 0
  105. validate_url = "{api_url}{handler}".format(
  106. api_url=self.API_URL, handler=self.VALIDATE_HANDLER)
  107. query = {
  108. "seccode": seccode,
  109. "sdk": ''.join( ["python_",self.sdk_version]),
  110. "user_id": user_id,
  111. "data":data,
  112. "timestamp":time.time(),
  113. "challenge":challenge,
  114. "userinfo":userinfo,
  115. "captchaid":gt,
  116. "json_format":JSON_FORMAT
  117. }
  118. backinfo = self._post_values(validate_url, query)
  119. if JSON_FORMAT == 1:
  120. backinfo = json.loads(backinfo)
  121. backinfo = backinfo["seccode"]
  122. if backinfo == self._md5_encode(seccode):
  123. return 1
  124. else:
  125. return 0
  126.  
  127. def _post_values(self, apiserver, data):
  128. response = requests.post(apiserver, data)
  129. return response.text
  130.  
  131. def _check_result(self, origin, validate):
  132. encodeStr = self._md5_encode(self.private_key + "geetest" + origin)
  133. if validate == encodeStr:
  134. return True
  135. else:
  136. return False
  137.  
  138. def failback_validate(self, challenge, validate, seccode):
  139. """
  140. failback模式的二次验证方式.在本地对轨迹进行简单的判断返回验证结果.
  141. """
  142. if not self._check_para(challenge, validate, seccode):
  143. return 0
  144. validate_result = self._failback_check_result(
  145. challenge, validate,)
  146. return validate_result
  147.  
  148. def _failback_check_result(self,challenge,validate):
  149. encodeStr = self._md5_encode(challenge)
  150. if validate == encodeStr:
  151. return True
  152. else:
  153. return False
  154.  
  155. def _check_para(self, challenge, validate, seccode):
  156. return (bool(challenge.strip()) and bool(validate.strip()) and bool(seccode.strip()))
  157.  
  158. def _md5_encode(self, values):
  159. if type(values) == str:
  160. values = values.encode()
  161. m = md5(values)
  162. return m.hexdigest()

geetest.py

  1. # coding:utf-8
  2. import json
  3.  
  4. from django.shortcuts import render
  5. from django.http import HttpResponse
  6. from blog.geetest import GeetestLib
  7. from django.views.decorators.csrf import csrf_exempt
  8.  
  9. pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
  10. pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
  11. mobile_geetest_id = "7c25da6fe21944cfe507d2f9876775a9"
  12. mobile_geetest_key = "f5883f4ee3bd4fa8caec67941de1b903"
  13.  
  14. def home(request):
  15. return render(request, "index.html",)
  16.  
  17. @csrf_exempt
  18. def pcgetcaptcha(request):
  19. user_id = 'test'
  20. gt = GeetestLib(pc_geetest_id, pc_geetest_key)
  21. status = gt.pre_process(user_id)
  22. request.session[gt.GT_STATUS_SESSION_KEY] = status
  23. request.session["user_id"] = user_id
  24. response_str = gt.get_response_str()
  25. return HttpResponse(response_str)
  26.  
  27. def mobilegetcaptcha(request):
  28. user_id = 'test'
  29. gt = GeetestLib(mobile_geetest_id, mobile_geetest_key)
  30. status = gt.pre_process(user_id)
  31. request.session[gt.GT_STATUS_SESSION_KEY] = status
  32. request.session["user_id"] = user_id
  33. response_str = gt.get_response_str()
  34. return HttpResponse(response_str)
  35.  
  36. def pcvalidate(request):
  37. if request.method == "POST":
  38. gt = GeetestLib(pc_geetest_id, pc_geetest_key)
  39. challenge = request.POST.get(gt.FN_CHALLENGE, '')
  40. validate = request.POST.get(gt.FN_VALIDATE, '')
  41. seccode = request.POST.get(gt.FN_SECCODE, '')
  42. status = request.session[gt.GT_STATUS_SESSION_KEY]
  43. user_id = request.session["user_id"]
  44. if status:
  45. result = gt.success_validate(challenge, validate, seccode, user_id)
  46. else:
  47. result = gt.failback_validate(challenge, validate, seccode)
  48. result = "<html><body><h1>登录成功</h1></body></html>" if result else "<html><body><h1>登录失败</h1></body></html>"
  49. return HttpResponse(result)
  50. return HttpResponse("error")
  51.  
  52. @csrf_exempt
  53. def pcajax_validate(request):
  54. if request.method == "POST":
  55. gt = GeetestLib(pc_geetest_id, pc_geetest_key)
  56. challenge = request.POST.get(gt.FN_CHALLENGE, '')
  57. validate = request.POST.get(gt.FN_VALIDATE, '')
  58. seccode = request.POST.get(gt.FN_SECCODE, '')
  59. status = request.session[gt.GT_STATUS_SESSION_KEY]
  60. user_id = request.session["user_id"]
  61. if status:
  62. result = gt.success_validate(challenge, validate, seccode, user_id)
  63. else:
  64. result = gt.failback_validate(challenge, validate, seccode)
  65. result = {"status":"success"} if result else {"status":"fail"}
  66. return HttpResponse(json.dumps(result))
  67. return HttpResponse("error")
  68.  
  69. def mobileajax_validate(request):
  70. if request.method == "POST":
  71. gt = GeetestLib(mobile_geetest_id, mobile_geetest_key)
  72. challenge = request.POST.get(gt.FN_CHALLENGE, '')
  73. validate = request.POST.get(gt.FN_VALIDATE, '')
  74. seccode = request.POST.get(gt.FN_SECCODE, '')
  75. status = request.session[gt.GT_STATUS_SESSION_KEY]
  76. user_id = request.session["user_id"]
  77. if status:
  78. result = gt.success_validate(challenge, validate, seccode, user_id)
  79. else:
  80. result = gt.failback_validate(challenge, validate, seccode)
  81. result = {"status":"success"} if result else {"status":"fail"}
  82. return HttpResponse(json.dumps(result))
  83. return HttpResponse("error")

check_views.py

  1. "v0.4.6 Geetest Inc.";
  2.  
  3. (function (window) {
  4. "use strict";
  5. if (typeof window === 'undefined') {
  6. throw new Error('Geetest requires browser environment');
  7. }
  8.  
  9. var document = window.document;
  10. var Math = window.Math;
  11. var head = document.getElementsByTagName("head")[0];
  12.  
  13. function _Object(obj) {
  14. this._obj = obj;
  15. }
  16.  
  17. _Object.prototype = {
  18. _each: function (process) {
  19. var _obj = this._obj;
  20. for (var k in _obj) {
  21. if (_obj.hasOwnProperty(k)) {
  22. process(k, _obj[k]);
  23. }
  24. }
  25. return this;
  26. }
  27. };
  28.  
  29. function Config(config) {
  30. var self = this;
  31. new _Object(config)._each(function (key, value) {
  32. self[key] = value;
  33. });
  34. }
  35.  
  36. Config.prototype = {
  37. api_server: 'api.geetest.com',
  38. protocol: 'http://',
  39. typePath: '/gettype.php',
  40. fallback_config: {
  41. slide: {
  42. static_servers: ["static.geetest.com", "dn-staticdown.qbox.me"],
  43. type: 'slide',
  44. slide: '/static/js/geetest.0.0.0.js'
  45. },
  46. fullpage: {
  47. static_servers: ["static.geetest.com", "dn-staticdown.qbox.me"],
  48. type: 'fullpage',
  49. fullpage: '/static/js/fullpage.0.0.0.js'
  50. }
  51. },
  52. _get_fallback_config: function () {
  53. var self = this;
  54. if (isString(self.type)) {
  55. return self.fallback_config[self.type];
  56. } else if (self.new_captcha) {
  57. return self.fallback_config.fullpage;
  58. } else {
  59. return self.fallback_config.slide;
  60. }
  61. },
  62. _extend: function (obj) {
  63. var self = this;
  64. new _Object(obj)._each(function (key, value) {
  65. self[key] = value;
  66. })
  67. }
  68. };
  69. var isNumber = function (value) {
  70. return (typeof value === 'number');
  71. };
  72. var isString = function (value) {
  73. return (typeof value === 'string');
  74. };
  75. var isBoolean = function (value) {
  76. return (typeof value === 'boolean');
  77. };
  78. var isObject = function (value) {
  79. return (typeof value === 'object' && value !== null);
  80. };
  81. var isFunction = function (value) {
  82. return (typeof value === 'function');
  83. };
  84.  
  85. var callbacks = {};
  86. var status = {};
  87.  
  88. var random = function () {
  89. return parseInt(Math.random() * 10000) + (new Date()).valueOf();
  90. };
  91.  
  92. var loadScript = function (url, cb) {
  93. var script = document.createElement("script");
  94. script.charset = "UTF-8";
  95. script.async = true;
  96.  
  97. script.onerror = function () {
  98. cb(true);
  99. };
  100. var loaded = false;
  101. script.onload = script.onreadystatechange = function () {
  102. if (!loaded &&
  103. (!script.readyState ||
  104. "loaded" === script.readyState ||
  105. "complete" === script.readyState)) {
  106.  
  107. loaded = true;
  108. setTimeout(function () {
  109. cb(false);
  110. }, 0);
  111. }
  112. };
  113. script.src = url;
  114. head.appendChild(script);
  115. };
  116.  
  117. var normalizeDomain = function (domain) {
  118. // special domain: uems.sysu.edu.cn/jwxt/geetest/
  119. // return domain.replace(/^https?:\/\/|\/.*$/g, ''); uems.sysu.edu.cn
  120. return domain.replace(/^https?:\/\/|\/$/g, ''); // uems.sysu.edu.cn/jwxt/geetest
  121. };
  122. var normalizePath = function (path) {
  123. path = path.replace(/\/+/g, '/');
  124. if (path.indexOf('/') !== 0) {
  125. path = '/' + path;
  126. }
  127. return path;
  128. };
  129. var normalizeQuery = function (query) {
  130. if (!query) {
  131. return '';
  132. }
  133. var q = '?';
  134. new _Object(query)._each(function (key, value) {
  135. if (isString(value) || isNumber(value) || isBoolean(value)) {
  136. q = q + encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&';
  137. }
  138. });
  139. if (q === '?') {
  140. q = '';
  141. }
  142. return q.replace(/&$/, '');
  143. };
  144. var makeURL = function (protocol, domain, path, query) {
  145. domain = normalizeDomain(domain);
  146.  
  147. var url = normalizePath(path) + normalizeQuery(query);
  148. if (domain) {
  149. url = protocol + domain + url;
  150. }
  151.  
  152. return url;
  153. };
  154.  
  155. var load = function (protocol, domains, path, query, cb) {
  156. var tryRequest = function (at) {
  157.  
  158. var url = makeURL(protocol, domains[at], path, query);
  159. loadScript(url, function (err) {
  160. if (err) {
  161. if (at >= domains.length - 1) {
  162. cb(true);
  163. } else {
  164. tryRequest(at + 1);
  165. }
  166. } else {
  167. cb(false);
  168. }
  169. });
  170. };
  171. tryRequest(0);
  172. };
  173.  
  174. var jsonp = function (domains, path, config, callback) {
  175. if (isObject(config.getLib)) {
  176. config._extend(config.getLib);
  177. callback(config);
  178. return;
  179. }
  180. if (config.offline) {
  181. callback(config._get_fallback_config());
  182. return;
  183. }
  184.  
  185. var cb = "geetest_" + random();
  186. window[cb] = function (data) {
  187. if (data.status == 'success') {
  188. callback(data.data);
  189. } else if (!data.status) {
  190. callback(data);
  191. } else {
  192. callback(config._get_fallback_config());
  193. }
  194. window[cb] = undefined;
  195. try {
  196. delete window[cb];
  197. } catch (e) {
  198. }
  199. };
  200. load(config.protocol, domains, path, {
  201. gt: config.gt,
  202. callback: cb
  203. }, function (err) {
  204. if (err) {
  205. callback(config._get_fallback_config());
  206. }
  207. });
  208. };
  209.  
  210. var throwError = function (errorType, config) {
  211. var errors = {
  212. networkError: '网络错误',
  213. gtTypeError: 'gt字段不是字符串类型'
  214. };
  215. if (typeof config.onError === 'function') {
  216. config.onError(errors[errorType]);
  217. } else {
  218. throw new Error(errors[errorType]);
  219. }
  220. };
  221.  
  222. var detect = function () {
  223. return window.Geetest || document.getElementById("gt_lib");
  224. };
  225.  
  226. if (detect()) {
  227. status.slide = "loaded";
  228. }
  229.  
  230. window.initGeetest = function (userConfig, callback) {
  231.  
  232. var config = new Config(userConfig);
  233.  
  234. if (userConfig.https) {
  235. config.protocol = 'https://';
  236. } else if (!userConfig.protocol) {
  237. config.protocol = window.location.protocol + '//';
  238. }
  239.  
  240. // for KFC
  241. if (userConfig.gt === '050cffef4ae57b5d5e529fea9540b0d1' ||
  242. userConfig.gt === '3bd38408ae4af923ed36e13819b14d42') {
  243. config.apiserver = 'yumchina.geetest.com/'; // for old js
  244. config.api_server = 'yumchina.geetest.com';
  245. }
  246.  
  247. if (isObject(userConfig.getType)) {
  248. config._extend(userConfig.getType);
  249. }
  250. jsonp([config.api_server || config.apiserver], config.typePath, config, function (newConfig) {
  251. var type = newConfig.type;
  252. var init = function () {
  253. config._extend(newConfig);
  254. callback(new window.Geetest(config));
  255. };
  256.  
  257. callbacks[type] = callbacks[type] || [];
  258. var s = status[type] || 'init';
  259. if (s === 'init') {
  260. status[type] = 'loading';
  261.  
  262. callbacks[type].push(init);
  263.  
  264. load(config.protocol, newConfig.static_servers || newConfig.domains, newConfig[type] || newConfig.path, null, function (err) {
  265. if (err) {
  266. status[type] = 'fail';
  267. throwError('networkError', config);
  268. } else {
  269. status[type] = 'loaded';
  270. var cbs = callbacks[type];
  271. for (var i = 0, len = cbs.length; i < len; i = i + 1) {
  272. var cb = cbs[i];
  273. if (isFunction(cb)) {
  274. cb();
  275. }
  276. }
  277. callbacks[type] = [];
  278. }
  279. });
  280. } else if (s === "loaded") {
  281. init();
  282. } else if (s === "fail") {
  283. throwError('networkError', config);
  284. } else if (s === "loading") {
  285. callbacks[type].push(init);
  286. }
  287. });
  288.  
  289. };
  290.  
  291. })(window);

gt.js

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>登录界面</title>
  6. <link rel="shortcut icon" href=" /static/imgs/login.ico"/>
  7. <link rel="stylesheet" href="/static/blog/bs/dist/css/bootstrap.min.css">
  8. <link rel="stylesheet" href="/static/blog/fa/web-fonts-with-css/css/fontawesome-all.min.css">
  9. </head>
  10. <body>
  11. {# <h3>登录界面</h3>#}
  12. <div class="container" style="background-color: #eeeeee">
  13. <div class="row">
  14. <div class="col-md-6 col-lg-offset-3">
  15. <div class="form-group col-lg-offset-4">
  16. <i class="fas fa-user-circle fa-10x"></i>
  17. <p>sign in with your account</p>
  18. </div>
  19. <form>
  20. {% csrf_token %}
  21. <div class="form-group">
  22. <label for="users"><i class="fas fa-user"></i>用户名</label>
  23. <input type="text" id="users" class="form-control">
  24. </div>
  25. <div class="form-group">
  26. <label for="pwd"><i class="fas fa-key"></i>密码</label>
  27. <input type="password" id="pwd" class="form-control">
  28. </div>
  29. {# 验证码功能#}
  30. {# <div class="form-group">#}
  31. {# <label for="pwd"><i class="fas fa-check-circle"></i>验证码</label>#}
  32. {# <div class="row">#}
  33. {# <div class="col-md-6">#}
  34. {# <input type="text" class="form-control" id="valid_code"/>#}
  35. {# </div>#}
  36. {# <div class="col-md-6">#}
  37. {# <img id="code_img" width="260" height="32" src="/get_validCode_img/">#}
  38. {# </div>#}
  39. {# </div>#}
  40. {# </div>#}
  41. <button id="popup-submit" type="button" class="btn btn-info login_btn col-lg-3"><i
  42. class="fa fa-sign-in-alt col-lg-pull-1"></i>登录
  43. </button>
  44. <div id="popup-captcha"></div>
  45. <span class="error pull-right form-group"></span>
  46. {# <input type="button" class="btn btn-info login_btn col-lg-3 pull-right" value="sign in">#}
  47.  
  48. </form>
  49. </div>
  50. </div>
  51. </div>
  52. </body>
  53. <script src="/static/JS/jquery-3.3.1.min.js"></script>
  54. <script>
  55. {#刷新验证码#}
  56. $('#code_img').click(function () {
  57. $(this)[0].src+="?";
  58. });
  59.  
  60. </script>
  61. <script src="/static/gt/gt.js"></script>
  62. <script>
  63. var handlerPopup = function (captchaObj) {
  64. // 成功的回调
  65. captchaObj.onSuccess(function () {
  66. var validate = captchaObj.getValidate();
  67. $.ajax({
  68. url: "/pc-geetest/ajax_validate", // 进行二次验证
  69. type: "post",
  70. dataType: "json",
  71. data: {
  72. username: $('#users').val(),
  73. password: $('#pwd').val(),
  74. geetest_challenge: validate.geetest_challenge,
  75. geetest_validate: validate.geetest_validate,
  76. geetest_seccode: validate.geetest_seccode,
  77. csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(),
  78. },
  79. success: function (data) {
  80. if (data && (data.status === "success")) {
  81. location.href = '/index/';
  82. } else {
  83. location.href = '/login/';
  84. }
  85. }
  86. });
  87. });
  88. $("#popup-submit").click(function () {
  89. $.ajax({
  90. url:"",
  91. type:'post',
  92. data:{
  93. user:$('#users').val(),
  94. pwd: $('#pwd').val(),
  95. valid_code: $('#valid_code').val(),
  96. csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(),
  97.  
  98. },
  99. success:function (data) {
  100. if (data.user){
  101. if(location.search){
  102. location.href = location.search.slice(6)
  103. }else {
  104. captchaObj.show();
  105. }
  106. }else{
  107. $('.error').text(data.msg).css({'color':'red'});
  108. setTimeout(function () {
  109. $('.error').text('');
  110. }, 1000);
  111. }
  112. }
  113. });
  114.  
  115. });
  116. // 将验证码加到id为captcha的元素里
  117. captchaObj.appendTo("#popup-captcha");
  118. // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
  119. };
  120. // 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
  121. $.ajax({
  122. url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
  123. type: "get",
  124. dataType: "json",
  125. csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(),
  126. success: function (data) {
  127. // 使用initGeetest接口
  128. // 参数1:配置参数
  129. // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
  130. initGeetest({
  131. gt: data.gt,
  132. challenge: data.challenge,
  133. product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
  134. offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
  135. // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
  136. }, handlerPopup);
  137. }
  138. });
  139. </script>
  140. </html>

login.html

路飞学城Python-Day117的更多相关文章

  1. 路飞学城—Python爬虫实战密训班 第三章

    路飞学城—Python爬虫实战密训班 第三章 一.scrapy-redis插件实现简单分布式爬虫 scrapy-redis插件用于将scrapy和redis结合实现简单分布式爬虫: - 定义调度器 - ...

  2. 路飞学城—Python爬虫实战密训班 第二章

    路飞学城—Python爬虫实战密训班 第二章 一.Selenium基础 Selenium是一个第三方模块,可以完全模拟用户在浏览器上操作(相当于在浏览器上点点点). 1.安装 - pip instal ...

  3. 路飞学城Python爬虫课第一章笔记

    前言 原创文章,转载引用务必注明链接.水平有限,如有疏漏,欢迎指正. 之前看阮一峰的博客文章,介绍到路飞学城爬虫课程限免,看了眼内容还不错,就兴冲冲报了名,99块钱满足以下条件会返还并送书送视频. 缴 ...

  4. 路飞学城-Python开发集训-第3章

    学习心得: 通过这一章的作业,使我对正则表达式的使用直接提升了一个level,虽然作业完成的不怎么样,重复代码有点多,但是收获还是非常大的,有点找到写代码的感觉了,遗憾的是,这次作业交过,这次集训就结 ...

  5. 路飞学城-Python开发集训-第1章

    学习体会: 在参加这次集训之前我自己学过一段时间的Python,看过老男孩的免费视频,自我感觉还行,老师写的代码基本上都能看懂,但是实际呢?....今天是集训第一次交作业的时间,突然发现看似简单升级需 ...

  6. 路飞学城-Python开发集训-第4章

    学习心得: 学习笔记: 在python中一个py文件就是一个模块 模块好处: 1.提高可维护性 2.可重用 3.避免函数名和变量名冲突 模块分为三种: 1.内置标准模块(标准库),查看所有自带和第三方 ...

  7. 路飞学城-Python开发集训-第2章

    学习心得: 这章对编码的讲解超级赞,现在对于编码终于有一点认知了,但还没有大彻大悟,还需要更加细心的琢磨一下Alex博客和视频,以前真的是被编码折磨死了,因为编码的问题而浪费的时间很多很多,现在终于感 ...

  8. 路飞学城-Python开发-第二章

    ''' 数据结构: menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家' ...

  9. 路飞学城-Python开发-第三章

    # 数据结构: # goods = [ # {"name": "电脑", "price": 1999}, # {"name&quo ...

  10. 路飞学城-Python开发-第一章

    # 基础需求: # 让用户输入用户名密码 # 认证成功后显示欢迎信息 # 输错三次后退出程序 username = 'pandaboy' password = ' def Login(username ...

随机推荐

  1. 调用的方法里接收一个List<>类型的参数,里面是自定义的EC类, 我要通过反射构建这List对象

              public static object CreateGeneric(Type generic, Type innerType, params object[] args)     ...

  2. elasticsearch 权威指南入门阅读笔记(一)

    相关文档 esapi:https://es.xiaoleilu.com/010_Intro/10_Installing_ES.html     https://esdoc.bbossgroups.co ...

  3. 转载 - 算法实践——舞蹈链(Dancing Links)算法求解数独

    出处:http://www.cnblogs.com/grenet/p/3163550.html 在“跳跃的舞者,舞蹈链(Dancing Links)算法——求解精确覆盖问题”一文中介绍了舞蹈链(Dan ...

  4. JAVA的输入输出基本操作样例

    这些类的继承关系有些类似,弄一个作为样例,理解一下其中的机制. package cc.openhome; import java.io.*; public class Member { private ...

  5. linux 线程切换效率与进程切换效率相差究竟有多大?

    Author:DriverMonkey Mail:bookworepeng@Hotmail.com Phone:13410905075 QQ:196568501 Are Linux threads t ...

  6. 推断一个点是否在某个区域内。百度,高德,腾讯都能用。(php版)

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/ ...

  7. Warning: File `src/core/nginx.h&#39; has modification time 1.2e+07 s in the future

    Nginx安装时Warning: File `src/core/nginx.h' has modification time 1.2e+07 s in the future问题的解决方法 问题场景: ...

  8. Java-Maven:Maven清单

    ylbtech-Java-Maven:Maven清单 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部     6.返回顶部   作者:ylbtech出处:http ...

  9. 框架-Eureka:初识 Eureka

    ylbtech-框架-Eureka:初识 Eureka 1.返回顶部 1. 1.1. http://localhost:2100/ 1.2. 2. Eureka - Last N events 3. ...

  10. [牛客挑战赛 30D] 小A的昆特牌 解题报告 (组合数学)

    interlinkage: https://ac.nowcoder.com/acm/contest/375/D description: solution: 我们枚举步兵的数量$x$,还剩下$S-x$ ...