views.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. from django.shortcuts import render
  2. # Create your views here.
  3. from django.conf import settings
  4. from django.http import HttpResponse, HttpResponseRedirect
  5. from django.contrib.auth import get_user_model
  6. from .models import OAuthUser
  7. from django.contrib.auth import login
  8. from django.shortcuts import get_object_or_404
  9. from django.views.generic import FormView, RedirectView
  10. from oauth.forms import RequireEmailForm
  11. from django.urls import reverse
  12. from website.utils import send_email, get_md5, save_user_avatar
  13. from django.contrib.sites.models import Site
  14. from django.core.exceptions import ObjectDoesNotExist
  15. from django.http import HttpResponseForbidden
  16. from .oauthmanager import get_manager_by_type
  17. import logging
  18. logger = logging.getLogger(__name__)
  19. def oauthlogin(request):
  20. type = request.GET.get('type', None)
  21. if not type:
  22. return HttpResponseRedirect('/')
  23. manager = get_manager_by_type(type)
  24. if not manager:
  25. return HttpResponseRedirect('/')
  26. nexturl = request.GET.get('next_url', None)
  27. if not nexturl or nexturl == '/login/':
  28. nexturl = '/'
  29. authorizeurl = manager.get_authorization_url(nexturl)
  30. return HttpResponseRedirect(authorizeurl)
  31. def authorize(request):
  32. manager = None
  33. type = request.GET.get('type', None)
  34. if not type:
  35. return HttpResponseRedirect('/')
  36. manager = get_manager_by_type(type)
  37. if not manager:
  38. return HttpResponseRedirect('/')
  39. code = request.GET.get('code', None)
  40. rsp = manager.get_access_token_by_code(code)
  41. nexturl = request.GET.get('next_url', None)
  42. if not nexturl:
  43. nexturl = '/'
  44. if not rsp:
  45. return HttpResponseRedirect(manager.get_authorization_url(nexturl))
  46. user = manager.get_oauth_userinfo()
  47. logger.info('user:' + user.nikename)
  48. if user:
  49. if user.picture:
  50. user.picture = save_user_avatar(user.picture)
  51. if not user.nikename:
  52. import datetime
  53. user.nikename = "website" + datetime.datetime.now().strftime('%y%m%d%I%M%S')
  54. try:
  55. user = OAuthUser.objects.get(type=type, openid=user.openid)
  56. except ObjectDoesNotExist:
  57. pass
  58. # facebook的token过长
  59. if type == 'facebook':
  60. user.token = ''
  61. email = user.email
  62. if email:
  63. author = None
  64. try:
  65. author = get_user_model().objects.get(id=user.author_id)
  66. except ObjectDoesNotExist:
  67. pass
  68. if not author:
  69. result = get_user_model().objects.get_or_create(email=user.email)
  70. author = result[0]
  71. if result[1]:
  72. author.username = user.nikename
  73. author.save()
  74. user.author = author
  75. user.save()
  76. login(request, author)
  77. return HttpResponseRedirect(nexturl)
  78. if not email:
  79. user.save()
  80. url = reverse('oauth:require_email', kwargs={
  81. 'oauthid': user.id
  82. })
  83. return HttpResponseRedirect(url)
  84. else:
  85. return HttpResponseRedirect(nexturl)
  86. def emailconfirm(request, id, sign):
  87. if not sign:
  88. return HttpResponseForbidden()
  89. if not get_md5(settings.SECRET_KEY + str(id) + settings.SECRET_KEY).upper() == sign.upper():
  90. return HttpResponseForbidden()
  91. oauthuser = get_object_or_404(OAuthUser, pk=id)
  92. author = None
  93. if oauthuser.author:
  94. author = get_user_model().objects.get(pk=oauthuser.author_id)
  95. else:
  96. result = get_user_model().objects.get_or_create(email=oauthuser.email)
  97. author = result[0]
  98. if result[1]:
  99. author.username = oauthuser.nikename
  100. author.save()
  101. """
  102. if oauthuser.email and author.email:
  103. login(request, author)
  104. return HttpResponseRedirect('/')
  105. """
  106. oauthuser.author = author
  107. oauthuser.save()
  108. login(request, author)
  109. site = Site.objects.get_current().domain
  110. content = '''
  111. <p>恭喜您,您已经成功绑定您的邮箱,您可以使用{type}来直接免密码登录本网站.欢迎您继续关注本站,地址是</p>
  112. <a href="{url}" rel="bookmark">{url}</a>
  113. 再次感谢您!
  114. <br />
  115. 如果上面链接无法打开,请将此链接复制至浏览器。
  116. {url}
  117. '''.format(type=oauthuser.type, url='http://' + site)
  118. send_email(emailto=[oauthuser.email, ], title='恭喜您绑定成功!', content=content)
  119. url = reverse('oauth:bindsuccess', kwargs={
  120. 'oauthid': id
  121. })
  122. url = url + '?type=success'
  123. return HttpResponseRedirect(url)
  124. class RequireEmailView(FormView):
  125. form_class = RequireEmailForm
  126. template_name = 'oauth/require_email.html'
  127. def get(self, request, *args, **kwargs):
  128. oauthid = self.kwargs['oauthid']
  129. oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
  130. if oauthuser.email:
  131. pass
  132. # return HttpResponseRedirect('/')
  133. return super(RequireEmailView, self).get(request, *args, **kwargs)
  134. def get_initial(self):
  135. oauthid = self.kwargs['oauthid']
  136. return {
  137. 'email': '',
  138. 'oauthid': oauthid
  139. }
  140. def get_context_data(self, **kwargs):
  141. oauthid = self.kwargs['oauthid']
  142. oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
  143. if oauthuser.picture:
  144. kwargs['picture'] = oauthuser.picture
  145. return super(RequireEmailView, self).get_context_data(**kwargs)
  146. def form_valid(self, form):
  147. email = form.cleaned_data['email']
  148. oauthid = form.cleaned_data['oauthid']
  149. oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
  150. oauthuser.email = email
  151. oauthuser.save()
  152. sign = get_md5(settings.SECRET_KEY + str(oauthuser.id) + settings.SECRET_KEY)
  153. site = Site.objects.get_current().domain
  154. if settings.DEBUG:
  155. site = '127.0.0.1:8000'
  156. path = reverse('oauth:email_confirm', kwargs={
  157. 'id': oauthid,
  158. 'sign': sign
  159. })
  160. url = "http://{site}{path}".format(site=site, path=path)
  161. content = """
  162. <p>请点击下面链接绑定您的邮箱</p>
  163. <a href="{url}" rel="bookmark">{url}</a>
  164. 再次感谢您!
  165. <br />
  166. 如果上面链接无法打开,请将此链接复制至浏览器。
  167. {url}
  168. """.format(url=url)
  169. send_email(emailto=[email, ], title='绑定您的电子邮箱', content=content)
  170. url = reverse('oauth:bindsuccess', kwargs={
  171. 'oauthid': oauthid
  172. })
  173. url = url + '?type=email'
  174. return HttpResponseRedirect(url)
  175. def bindsuccess(request, oauthid):
  176. type = request.GET.get('type', None)
  177. title = ''
  178. content = ''
  179. oauthuser = get_object_or_404(OAuthUser, pk=oauthid)
  180. if type == 'email':
  181. title = '绑定成功'
  182. content = "恭喜您,还差一步就绑定成功了,请登录您的邮箱查看邮件完成绑定,谢谢。"
  183. else:
  184. title = '绑定成功'
  185. content = "恭喜您绑定成功,您以后可以使用{type}来直接免密码登录本站啦,感谢您对本站对关注。".format(type=oauthuser.type)
  186. return render(request, 'oauth/bindsuccess.html', {
  187. 'title': title,
  188. 'content': content
  189. })