views.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. from django.shortcuts import render, redirect
  2. from .form import UserLoginForm, UserRegisterForm
  3. from django.contrib.auth import authenticate, login, logout
  4. from django.http import HttpResponse
  5. from .models import Profile, Devices
  6. from django.contrib.auth.models import User
  7. from django.contrib.auth.decorators import login_required
  8. from .form import ProfileForm
  9. import random
  10. import datetime
  11. import json
  12. """
  13. 在此处修改token过期时间,30代表30天过期
  14. """
  15. expiration_date = 30
  16. def user_login(request):
  17. if request.method == 'POST':
  18. user_login_form = UserLoginForm(request.POST)
  19. if user_login_form.is_valid():
  20. # 清洗出合法的数据
  21. data = user_login_form.cleaned_data
  22. # 检测是否有登录凭证
  23. if data['token'] != 'token':
  24. try:
  25. device = Devices.objects.filter(token__exact=data['token']).get()
  26. sub_time = (device.last_login_time - datetime.date).total_seconds() / (3600 * 24)
  27. # 检查token是否过期
  28. if sub_time < expiration_date:
  29. # 更新此user此设备的token
  30. # token由设备uid、用户名、当前时间hash得来
  31. device.token = hash(
  32. device.device_uid + device.user.username + datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
  33. device.save()
  34. # 登录
  35. user = device.user
  36. login(request, user)
  37. response = ['login successfully', device.token]
  38. return HttpResponse(json.dumps(response))
  39. # return redirect("chat:index")
  40. else:
  41. response = ['token time out']
  42. return HttpResponse(json.dumps(response))
  43. # 已过期的token并且已经被删除
  44. except Devices.DoesNotExist:
  45. response = ['detected new device, please login']
  46. return HttpResponse(json.dumps(response))
  47. else:
  48. # 检测账号密码是否匹配数据库中的一个用户
  49. # 如果均匹配,则返回此User对象
  50. user = authenticate(username=data['username'], password=data['password'])
  51. if user:
  52. if data['token'] == 'token':
  53. # 新建一个该user的设备
  54. device = create_new_device(user)
  55. else:
  56. # 此时,客户端带来了过期的旧token,现在需要更新旧的token
  57. try:
  58. device = Devices.objects.filter(token__exact=data['token']).get()
  59. device.token = hash(
  60. device.device_uid + device.user.username + datetime.datetime.now().strftime(
  61. "%Y%m%d%H%M%S"))
  62. device.save()
  63. except Devices.DoesNotExist:
  64. # 新建一个该user的设备
  65. device = create_new_device(user)
  66. login(request, user)
  67. response = ['login successfully', device.token]
  68. return HttpResponse(json.dumps(response))
  69. else:
  70. response = ['wrong account or password']
  71. return HttpResponse(json.dumps(response))
  72. else:
  73. response = ['illegal input']
  74. return HttpResponse(json.dumps(response))
  75. # 用于测试,登录界面
  76. # elif request.method == 'GET':
  77. # user_login_form = UserLoginForm()
  78. # context = {'form': user_login_form}
  79. # return render(request, 'login.html', context)
  80. else:
  81. # 请求方法错误,请使用POST
  82. response = ['illegal method, please use post']
  83. return HttpResponse(json.dumps(response))
  84. # 新建一个该user的设备
  85. def create_new_device(user):
  86. device = Devices()
  87. device.user = user
  88. device.device_uid = generate_random_str(10)
  89. device.token = hash(
  90. device.device_uid + device.user.username + datetime.datetime.now().strftime("%Y%m%d%H%M%S"))
  91. device.save()
  92. return device
  93. def generate_random_str(random_length=16):
  94. """
  95. 生成一个指定长度的随机字符串
  96. """
  97. random_str = ''
  98. base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
  99. length = len(base_str) - 1
  100. for i in range(random_length):
  101. random_str += base_str[random.randint(0, length)]
  102. return random_str
  103. def user_logout(request):
  104. logout(request)
  105. response = ['logout successfully']
  106. return HttpResponse(json.dumps(response))
  107. def user_register(request):
  108. if request.method == 'POST':
  109. user_register_form = UserRegisterForm(data=request.POST)
  110. if user_register_form.is_valid():
  111. # 新建一个user,但是不提交
  112. new_user = user_register_form.save(commit=False)
  113. # 设置密码
  114. new_user.set_password(user_register_form.cleaned_data['password'])
  115. # 保存
  116. new_user.save()
  117. response = ['reg successfully']
  118. return HttpResponse(json.dumps(response))
  119. else:
  120. response = ['illegal input']
  121. return HttpResponse(json.dumps(response))
  122. # 用于测试
  123. # elif request.method == 'GET':
  124. # user_register_form = UserRegisterForm()
  125. # context = {'form': user_register_form}
  126. # return render(request, 'register.html', context)
  127. else:
  128. response = ['illegal method, please use post']
  129. return HttpResponse(json.dumps(response))
  130. @login_required(login_url='/account/login/')
  131. def profile_detail(request, r_username):
  132. user = User.objects.get(username=r_username)
  133. profile = Profile.objects.get(user__exact=user)
  134. if request.method == 'POST':
  135. # 判断此用户是否正在修改自身账号信息
  136. if request.user != user:
  137. response = ['You do not have permission to do this']
  138. return HttpResponse(json.dumps(response))
  139. profile_form = ProfileForm(request.POST, request.FILES)
  140. if profile_form.is_valid():
  141. # 填入信息
  142. profile_cd = profile_form.cleaned_data
  143. profile.phone = profile_cd['phone']
  144. profile.bio = profile_cd['bio']
  145. profile.avatar = profile_cd["avatar"]
  146. profile.save()
  147. response = ['edit successfully']
  148. return HttpResponse(json.dumps(response))
  149. else:
  150. response = ['illegal input']
  151. return HttpResponse(json.dumps(response))
  152. # 用于测试
  153. # elif request.method == 'GET':
  154. # profile_form = ProfileForm()
  155. # context = {'profile_form': profile_form, 'profile': profile, 'user': user}
  156. # return render(request, 'edit.html', context)
  157. else:
  158. response = ['illegal method, please use post']
  159. return HttpResponse(json.dumps(response))