目的:jumpserver 3.0登录页面加入验证码。
网上有第三方包Django Simple Captcha可以实现这个图片验证,用起来相对比较方便的。但是我实践时候是另一种方法,就当过程学习了。
1、代码生成验证码图片(结尾附上),验证码的值存入django cache
调用的库 from django.core.cache import cache
2、jumpserver的视图文件view.py的Login函数增加验证码方法
# 调用verify_code.py生成验证码值和图片
today_str = datetime.date.today().strftime("%Y%m%d")
verify_code_img_path = "%s/%s" % (settings.VERIFICATION_CODE_IMGS_DIR,
today_str)
if not os.path.isdir(verify_code_img_path):
os.makedirs(verify_code_img_path)
print("session:", request.session.session_key)
random_filename = "".join(random.sample(string.ascii_lowercase,4))
random_code = verify_code.gene_code(verify_code_img_path,random_filename)
cache.set(random_filename, random_code,30)
#账号验证,先验证验证码
username = request.POST.get('username')
password = request.POST.get('password')
_verify_code = request.POST.get('verify_code')
_verify_code_key = request.POST.get('verify_code_key')
if cache.get(_verify_code_key) == _verify_code:
if username and password:
user = authenticate(username=username, password=password)
3、前端页面添加验证码
附网上一份生成验证码的代码:
#_*_coding:utf-8_*_
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import random
import math, string
#字体的位置,不同版本的系统会有不同
font_path = '/Library/Fonts/Arial.ttf'
#font_path = '/Library/Fonts/Hanzipen.ttc'
#生成几位数的验证码
number = 4
#生成验证码图片的高度和宽度
size = (100,30)
#背景颜色,默认为白色
bgcolor = (255,255,255)
#字体颜色,默认为蓝色
fontcolor = (0,0,255)
#干扰线颜色。默认为红色
linecolor = (255,0,0)
#是否要加入干扰线
draw_line = True
#加入干扰线条数的上下限
line_number = (1,5)
def gen_text():
source = list(string.ascii_letters)
for index in range(0,10):
source.append(str(index))
return ''.join(random.sample(source,number))#number是生成验证码的位数
#用来绘制干扰线
def gene_line(draw,width,height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill = linecolor)
def gene_code(save_path,filename):
width,height = size #宽和高
image = Image.new('RGBA',(width,height),bgcolor) #创建图片
font = ImageFont.truetype(font_path,25) #验证码的字体和字体大小
#font = ImageFont.truetype(25) #验证码的字体和字体大小
draw = ImageDraw.Draw(image) #创建画笔
#text = "我是中国人" #生成字符串
text = gen_text() #生成字符串
print(text)
font_width, font_height = font.getsize(text)
draw.text(((width - font_width) / number, (height - font_height) / number),text,\
font= font,fill=fontcolor) #填充字符串
if draw_line:
gene_line(draw, width, height)
gene_line(draw, width, height)
gene_line(draw, width, height)
gene_line(draw, width, height)
image = image.transform((width + 20, height +10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 创建扭曲
image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强
image.save('%s/%s.png' %(save_path,filename)) # 保存验证码图片
print("savepath:",save_path)
return text
if __name__ == "__main__":
gene_code('/tmp','test') #会把生成的图片存成/tmp/test.png
随机验证码代码
需要安装python Pillow-1.7.8库,先安装依赖
# yum install -y libjpeg-devel freetype-devel libpng-devel
不然直接安装python包,生成图片会报错
参考网址:https://www.cnblogs.com/alex3714/articles/6662365.html