当前位置:   article > 正文

Django Session与用户认证模块_django用户登录session验证

django用户登录session验证

Django中的Session是一种在Web应用程序中跟踪用户状态的机制。它允许您在多个HTTP请求之间存储和检索用户特定的信息。Session通常用于跟踪用户的登录状态、存储用户首选项、购物车信息等。

简单的cookie验证

敏感信息不宜使用cookie,我们应该用cookie记录简单配置.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  7. <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
  8. </head>
  9. <body>
  10. <form action="/" method="post">
  11. <input type="text" name="username" />
  12. <input type="button" value="获取cookie" id="get_cook"/>
  13. <input type="button" value="设置cookie" id="set_cook"/>
  14. <input type="submit" value="提交"/>
  15. </form>
  16. </body>
  17. <script type="text/javascript">
  18. $("#get_cook").bind("click",function(){
  19. var cook = $.cookie("username");
  20. $('input[name="username"]').val(cook);
  21. });
  22. $("#set_cook").bind("click",function(){
  23. var cook = $('input[name="username"]').val(cook);
  24. $.cookie("username","10");
  25. });
  26. </script>
  27. </html>
  1. from django.shortcuts import render,HttpResponse
  2. from django.forms import Form,fields,widgets
  3. def index(request):
  4. if request.method == "GET":
  5. obj = render(request,"index.html")
  6. obj.set_cookie("username", "lyshark") # 设置一个cookie
  7. return obj # 返回页面
  8. else:
  9. cook = request.COOKIES.get("username") # 获取到cookie
  10. print("获取到cookie:{}".format(cook))
  11. return render(request,"index.html")

使用Session进行验证

  1. <!--name:login.html-->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Title</title>
  7. </head>
  8. <body>
  9. <form action="/login/" method="post">
  10. <input type="text" name="username"/>
  11. <input type="password" name="password"/>
  12. <input type="submit" value="用户登录"/>
  13. </form>
  14. </body>
  15. </html>
  1. # name: urls.py
  2. from MyWeb import views
  3. urlpatterns = [
  4. path('login/', views.login),
  5. path('logout/',views.logout),
  6. path('index/',views.index)
  7. ]
  1. # name: views.py
  2. from django.shortcuts import render,HttpResponse,redirect
  3. def index(request):
  4. is_login = request.session.get("is_login",False)
  5. if is_login:
  6. cookie_content = request.COOKIES
  7. session_content = request.session.get("username")
  8. return HttpResponse("**欢迎用户 {} 你已经是登录状态,SessionID:{}:**".format(session_content,cookie_content))
  9. else:
  10. return redirect('/login/')
  11. def login(request):
  12. if request.method=="GET":
  13. is_login = request.session.get("is_login", False)
  14. if is_login:
  15. cookie_content = request.COOKIES
  16. session_content = request.session.get("username")
  17. return HttpResponse("**欢迎用户 {} 你已经是登录状态,SessionID:{}:**".format(session_content, cookie_content))
  18. else:
  19. return render(request,"login.html")
  20. elif request.method == "POST":
  21. username = request.POST['username']
  22. password = request.POST['password']
  23. print(username,password)
  24. if username == "admin" and password =="123123":
  25. request.session['is_login'] = "True"
  26. request.session['username'] = username
  27. return redirect('/index/')
  28. return render(request, "login.html")
  29. def logout(request):
  30. try:
  31. del request.session['is_login']
  32. except KeyError:
  33. pass
  34. return redirect("/login/")

默认的session键值对,会存储在django的数据库中,其中的配置settings.py如下

  1. SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认)
  2. SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
  3. SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认)
  4. SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认)
  5. SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认)
  6. SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认)
  7. SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认)
  8. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
  9. SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)

使用auth模块实现创建用户

django为我们提供了一套完备的验证机制,如下是简单的用户创建命令.

  1. from django.shortcuts import render,HttpResponse
  2. from MyWeb import models
  3. from django.contrib.auth.models import User,auth
  4. def index(request):
  5. if request.method == "GET":
  6. # -------------------------------------------
  7. # 创建用户操作
  8. User.objects.create_user(username="lyshark",password="123123",email="lyshark@163.com") # 创建用户
  9. User.objects.create_superuser(username="admin", password="123123", email="admin@163.com") # 创建超级用户
  10. # -------------------------------------------
  11. # 修改密码操作
  12. user = User.objects.get(username="lyshark")
  13. user.set_password(raw_password="123456")
  14. user.save()
  15. # -------------------------------------------
  16. # 判断用户名密码是否有效(成功返回用户名,失败返回none)
  17. user = auth.authenticate(username="lyshark",password="123456")
  18. print(user)
  19. return HttpResponse("hello lyshark")
  20. return render(request,"index.html")

使用auth模块完成登录认证

登录失败会自动跳转到/account/login/你可以自定义修改LOGIN_URL=/login/即可.

  1. from django.shortcuts import render,HttpResponse
  2. from MyWeb import models
  3. from django.contrib.auth.models import User,auth
  4. from django.contrib.auth.decorators import login_required
  5. def login(request):
  6. if request.method == "GET":
  7. return HttpResponse("""
  8. <form action="/login/" method="post">
  9. <input type="text" name="username">
  10. <input type="password" name="password">
  11. <input type="submit" value="登陆系统">
  12. </form>
  13. """)
  14. else:
  15. username = request.POST.get("username")
  16. password = request.POST.get("password")
  17. # 判断用户名密码是否有效
  18. user = auth.authenticate(username=username,password=password)
  19. if user:
  20. auth.login(request,user) # 执行登录函数
  21. return HttpResponse("登陆成功.")
  22. else:
  23. #auth.logout(request,user) # 执行登出函数
  24. return HttpResponse("登录失败..")
  25. # 下方的login_required装饰器,用于验证是否登录完成
  26. @login_required
  27. def is_login(request):
  28. return HttpResponse("用户已经登陆完成了...")
  29. # 下方程序用户登出用户
  30. def logout(request):
  31. auth.logout(request) # 执行登出函数
  32. return HttpResponse("用户注销完成..")

使用auth模块实现用户认证

django为我们提供了一套完备的验证机制,如下是简单的用户创建命令.

  1. from django.shortcuts import render,HttpResponse
  2. from django.contrib.auth.models import User,auth
  3. from django.contrib.auth.decorators import login_required
  4. # 实现用户注册流程
  5. def register(request):
  6. if request.method == "GET":
  7. return HttpResponse("""
  8. <form action="/register/" method="post">
  9. 账号: <input type="text" name="username"><br>
  10. 密码: <input type="password" name="password"><br>
  11. 邮箱: <input type="text", name="email"><br>
  12. <input type="submit" value="用户注册">
  13. </form>
  14. """)
  15. else:
  16. u_username = request.POST.get("username")
  17. u_password = request.POST.get("password")
  18. u_email = request.POST.get("email")
  19. # 先判断账号是否存在
  20. if User.objects.filter(username=u_username):
  21. return HttpResponse("{} 用户名已被注册".format(u_username))
  22. else:
  23. # 创建普通用户
  24. User.objects.create_user(username=u_username, password=u_password, email=u_email)
  25. return HttpResponse("注册 {} 成功".format(u_username))
  26. return HttpResponse("注册出现未知错误.")
  27. # 实现用户登录
  28. def login(request):
  29. if request.method == "GET":
  30. return HttpResponse("""
  31. <form action="/login/" method="post">
  32. 账号: <input type="text" name="username"><br>
  33. 密码: <input type="password" name="password"><br>
  34. <input type="submit" value="登陆系统">
  35. </form>
  36. """)
  37. else:
  38. u_username = request.POST.get("username")
  39. u_password = request.POST.get("password")
  40. # 判断用户名密码是否有效(成功返回用户名,失败返回none)
  41. user = auth.authenticate(username=u_username, password=u_password)
  42. if user:
  43. # 执行用户登录函数
  44. auth.login(request, user)
  45. # 设置用户名session_name的一个Session
  46. request.session['session_name'] = u_username
  47. return HttpResponse("用户: {} 登陆成功.".format(u_username))
  48. else:
  49. return HttpResponse("登录失败..")
  50. # 执行密码修改
  51. @login_required(login_url="/login/")
  52. def modify(request):
  53. if request.method == "GET":
  54. return HttpResponse("""
  55. <form action="/modify/" method="post">
  56. 原密码: <input type="text" name="old_password"><br>
  57. 新密码: <input type="password" name="new_password"><br>
  58. <input type="submit" value="修改密码">
  59. </form>
  60. """)
  61. if request.method == "POST":
  62. uname = request.session.get('session_name') # 先得到用户名
  63. old_password = request.POST.get("old_password") # 得到原始密码
  64. new_password = request.POST.get("new_password") # 设置新密码
  65. # 判断原始用户名密码是否有效(成功返回用户名,失败返回none)
  66. is_true = auth.authenticate(username= uname, password= old_password)
  67. # 验证通过执行改密码
  68. if is_true != None:
  69. # 开始修改密码
  70. user_obj = User.objects.get(username = uname)
  71. user_obj.set_password(raw_password= new_password)
  72. user_obj.save()
  73. auth.logout(request)
  74. return HttpResponse("用户: {} 修改密码完成,请重新登录.".format(uname))
  75. else:
  76. return HttpResponse("用户: {} 原始密码不正确.".format(uname))
  77. return HttpResponse("未知错误.")
  78. # 下方的login_required装饰器,用于验证是否登录完成,失败则跳转 /login/
  79. @login_required(login_url="/login/")
  80. def is_login(request):
  81. uuid = request.session.get('_auth_user_id')
  82. uname = request.session.get('session_name')
  83. return HttpResponse("ID: {} 用户名: {} 已登陆.".format(uuid,uname))
  84. # 执行用户注销操作
  85. def logout(request):
  86. uuid = request.session.get('_auth_user_id')
  87. uname = request.session.get('session_name')
  88. if uname == None:
  89. return HttpResponse("未登录,请先登录..")
  90. # 执行登出
  91. auth.logout(request)
  92. # 删除保存的用户名Session
  93. try:
  94. del request.session['session_name']
  95. except KeyError:
  96. pass
  97. return HttpResponse("ID: {} 用户名: {} 注销完成..".format(uuid,uname))
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/442710
推荐阅读
相关标签
  

闽ICP备14008679号