dynamic create crypto_key when django running

This commit is contained in:
向乐🌌 2021-05-20 13:11:55 +08:00
parent ca84457c1f
commit 28661b0d9c
4 changed files with 42 additions and 47 deletions

View File

@ -5,6 +5,7 @@ from django_redis import get_redis_connection
from utils.storage.memorystorage import MemoryStorage
from utils.storage.kvstorage import KvStorage
from cryptography.fernet import Fernet
try:
redis_conn = get_redis_connection()
@ -18,3 +19,5 @@ except Exception as e:
print("如果确定需要使用Redis作为缓存请排查Redis配置错误信息如下")
print("Redis Exception: {}".format(e))
crypto_key = Fernet.generate_key()

View File

@ -7,10 +7,12 @@
# @Date 2021/5/20 8:47
from django.shortcuts import render
from django.http import HttpResponseRedirect
import logging
from utils.crypto import Crypto
from pwdselfservice.local_settings import CRYPTO_KEY
from pwdselfservice.local_settings import TMPID_COOKIE_AGE
from django.conf import settings
from pwdselfservice import crypto_key
logger = logging.getLogger('django')
@ -36,13 +38,13 @@ def code_2_user_id(ops, request, msg_template, home_url, code):
return user_id, user_info
def tmpid_2_user_info(ops, request, msg_template, home_url, scan_app_tag):
def crypto_id_2_user_info(ops, request, msg_template, home_url, scan_app_tag):
try:
tmpid_crypto = request.COOKIES.get('tmpid')
crypto_tmp_id = request.COOKIES.get('tmpid')
except Exception as e:
tmpid_crypto = None
crypto_tmp_id = None
logger.error('[异常] %s' % str(e))
if not tmpid_crypto:
if not crypto_tmp_id:
logger.error('[异常] 请求方法:%s,请求路径:%s未能拿到TmpID或会话己超时。' % (request.method, request.path))
context = {
'msg': "会话己超时,请重新扫码验证用户信息。",
@ -51,8 +53,8 @@ def tmpid_2_user_info(ops, request, msg_template, home_url, scan_app_tag):
}
return render(request, msg_template, context)
# 解密
crypto = Crypto(CRYPTO_KEY)
user_id = crypto.decrypt(tmpid_crypto)
crypto = Crypto(crypto_key)
user_id = crypto.decrypt(crypto_tmp_id)
# 通过user_id拿到用户的邮箱并格式化为username
userid_status, user_info = ops.get_user_detail_by_user_id(user_id)
if not userid_status:
@ -66,9 +68,19 @@ def tmpid_2_user_info(ops, request, msg_template, home_url, scan_app_tag):
return user_info
def tmpid_2_user_id(request, msg_template, home_url):
def crypto_user_id_2_cookie(user_id):
crypto = Crypto(crypto_key)
# 对user_id进行加密因为user_id基本上固定不变的为了防止user_id泄露而导致重复使用进行加密后再传回。
_id_cryto = crypto.encrypt(user_id)
# 配置cookie通过cookie把加密后的用户user_id传到重置密码页面并重定向到重置密码页面。
set_cookie = HttpResponseRedirect('resetPassword')
set_cookie.set_cookie('tmpid', _id_cryto, expires=TMPID_COOKIE_AGE)
return set_cookie
def crypto_id_2_user_id(request, msg_template, home_url):
try:
tmpid_crypto = request.COOKIES.get('tmpid')
crypto_tmp_id = request.COOKIES.get('tmpid')
except Exception as e:
logger.error('[异常] %s' % str(e))
logger.error('[异常] 请求方法:%s,请求路径:%s未能拿到TmpID或会话己超时。' % (request.method, request.path))
@ -79,8 +91,8 @@ def tmpid_2_user_id(request, msg_template, home_url):
}
return render(request, msg_template, context)
# 解密
crypto = Crypto(CRYPTO_KEY)
return crypto.decrypt(tmpid_crypto)
crypto = Crypto(crypto_key)
return crypto.decrypt(crypto_tmp_id)
def ops_account(ad_ops, request, msg_template, home_url, username, new_password):

View File

@ -2,13 +2,13 @@ import logging
from django.http import HttpResponseRedirect
from django.shortcuts import render
from pwdselfservice.local_settings import SCAN_CODE_TYPE, DING_MO_APP_ID, WEWORK_CORP_ID, WEWORK_AGENT_ID, HOME_URL, CRYPTO_KEY, TMPID_COOKIE_AGE
from pwdselfservice.local_settings import SCAN_CODE_TYPE, DING_MO_APP_ID, WEWORK_CORP_ID, WEWORK_AGENT_ID, HOME_URL, TMPID_COOKIE_AGE
from utils.ad_ops import AdOps
from utils.crypto import Crypto
from utils.format_username import format2username, get_user_is_active
from .form import CheckForm
from .utils import code_2_user_id, tmpid_2_user_info, ops_account, tmpid_2_user_id
from .utils import code_2_user_id, crypto_id_2_user_info, ops_account, crypto_id_2_user_id, crypto_user_id_2_cookie
msg_template = 'messages.html'
logger = logging.getLogger('django')
@ -33,9 +33,10 @@ scan_params = PARAMS()
_ops = scan_params.ops
try:
ad_ops = AdOps()
print("初始化Active Directory连接成功...")
except Exception as e:
ad_ops = None
print("初始化Active Directory连接失败")
print("初始化Active Directory连接失败...")
print(str(e))
@ -105,18 +106,17 @@ def callback_check(request):
logger.info('[成功] 请求方法:%s,请求路径:%sCODE%s' % (request.method, request.path, code))
else:
logger.error('[异常] 请求方法:%s,请求路径:%s未能拿到CODE。' % (request.method, request.path))
context = {
'msg': "错误,临时授权码己失效,请从主页重新扫码验证。",
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
return render(request, msg_template, context)
try:
user_id, user_info = code_2_user_id(_ops, request, msg_template, home_url, code)
# 账号是否是激活的
if get_user_is_active(user_info):
crypto = Crypto(CRYPTO_KEY)
# 对user_id进行加密因为user_id基本上固定不变的为了防止user_id泄露而导致重复使用进行加密后再传回。
_id_cryto = crypto.encrypt(user_id)
# 配置cookie通过cookie把加密后的用户user_id传到重置密码页面并重定向到重置密码页面。
set_cookie = HttpResponseRedirect('resetPassword')
set_cookie.set_cookie('tmpid', _id_cryto, expires=TMPID_COOKIE_AGE)
return set_cookie
return crypto_user_id_2_cookie(user_id)
else:
context = {
'msg': '[%s]在钉钉中未激活或可能己离职' % format2username(user_info.get('name')),
@ -124,14 +124,6 @@ def callback_check(request):
'button_display': "返回主页"
}
return render(request, msg_template, context)
except KeyError:
context = {
'msg': "错误,临时授权码己失效,请从主页重新扫码验证。",
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
logger.error('[异常] %s' % str(KeyError))
return render(request, msg_template, context)
except Exception as callback_e:
context = {
'msg': "错误[%s],请与管理员联系." % str(callback_e),
@ -151,7 +143,7 @@ def reset_pwd_by_callback(request):
home_url = '%s://%s' % (request.scheme, HOME_URL)
# 从cookie中提取union_id并解密然后对当前union_id的用户进行重置密码
if request.method == 'GET':
user_id = tmpid_2_user_id(request, msg_template, home_url)
user_id = crypto_id_2_user_id(request, msg_template, home_url)
userid_status, user_info = _ops.get_user_detail_by_user_id(user_id)
if not userid_status:
context = {
@ -179,7 +171,7 @@ def reset_pwd_by_callback(request):
# 重置密码页面,输入新密码后点击提交
elif request.method == 'POST':
_new_password = request.POST.get('new_password').strip()
user_info = tmpid_2_user_info(_ops, request, msg_template, home_url, scan_params.SCAN_APP)
user_info = crypto_id_2_user_info(_ops, request, msg_template, home_url, scan_params.SCAN_APP)
username = format2username(user_info.get('email'))
return ops_account(ad_ops, request, msg_template, home_url, username, _new_password)
else:
@ -199,7 +191,7 @@ def unlock_account(request):
"""
home_url = '%s://%s' % (request.scheme, HOME_URL)
if request.method == 'GET':
user_info = tmpid_2_user_info(_ops, request, msg_template, home_url, scan_params.SCAN_APP)
user_info = crypto_id_2_user_info(_ops, request, msg_template, home_url, scan_params.SCAN_APP)
username = format2username(user_info.get('email'))
context = {
'username': username,
@ -207,7 +199,7 @@ def unlock_account(request):
return render(request, 'resetPassword.html', context)
elif request.method == 'POST':
user_info = tmpid_2_user_info(_ops, request, msg_template, home_url, scan_params.SCAN_APP)
user_info = crypto_id_2_user_info(_ops, request, msg_template, home_url, scan_params.SCAN_APP)
username = format2username(user_info.get('email'))
return ops_account(ad_ops, request, msg_template, home_url, username, None)
else:

View File

@ -1,10 +1,3 @@
import os
import random
try:
from cryptography.fernet import Fernet
except ImportError:
os.system('pip3 install cryptography')
from cryptography.fernet import Fernet
@ -22,8 +15,3 @@ class Crypto(object):
def decrypt(self, token):
string = self.factory.decrypt(bytes(token.encode('utf-8'))).decode('utf-8')
return string
if __name__ == '__main__':
key = Fernet.generate_key()
print(key)