Django Library Users
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

views.py 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. from .context import context_adaption
  2. from django.shortcuts import render, redirect
  3. from django.conf import settings
  4. from django.contrib import messages
  5. from django.contrib.auth import authenticate
  6. from django.contrib.auth import login as django_login
  7. from django.contrib.auth import logout as django_logout
  8. from django.contrib.auth.decorators import login_required
  9. from django.contrib.auth.forms import AuthenticationForm
  10. from django.contrib.auth.models import User
  11. from django.utils.encoding import force_str
  12. from django.utils.http import urlsafe_base64_decode
  13. from django.utils.translation import gettext as _
  14. from .forms import UserRegistrationForm, UserProfileForm, UserActivationForm
  15. import logging
  16. from .models import get_userprofile
  17. from themes import Context
  18. from . tokens import generate_token
  19. import users
  20. from users import emails
  21. from users import parameter
  22. logger = logging.getLogger(settings.ROOT_LOGGER_NAME).getChild(__name__)
  23. def password_recovery(request):
  24. messages.error(request, "Password recovery is not yet implemented!")
  25. return redirect(request.GET.get('next') or '/')
  26. def profile_post_actions(request, context):
  27. if request.POST:
  28. form = context.get('form_userprofile')
  29. if form.is_valid():
  30. form.save()
  31. return redirect(request.GET.get('next') or '/')
  32. def profile_pre_actions(request, context, form_to_be_used=UserProfileForm):
  33. profile = get_userprofile(request.user)
  34. if request.POST:
  35. form = form_to_be_used(request.POST, instance=profile)
  36. else:
  37. form = form_to_be_used(instance=profile)
  38. context['form_userprofile'] = form
  39. @login_required
  40. def profile(request):
  41. context = Context(request) # needs to be executed first because of time mesurement
  42. profile_pre_actions(request, context)
  43. response = profile_post_actions(request, context)
  44. if response is not None:
  45. return response
  46. else:
  47. context_adaption(
  48. context,
  49. request,
  50. _('Profile for %(username)s') % {'username': request.user.username},
  51. )
  52. return render(request, 'users/profile.html', context=context)
  53. def register(request):
  54. context = Context(request) # needs to be executed first because of time mesurement
  55. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  56. context_adaption(context, request, _('Register'))
  57. if not request.POST:
  58. form = UserRegistrationForm()
  59. messages.info(request, _('If you already have an account, login <a href="%(url)s">here</a>.') % {'url': users.url_login(request)})
  60. else:
  61. form = UserRegistrationForm(request.POST)
  62. if form.is_valid():
  63. # Deactivate the user, if validation or activation is required
  64. if parameter.get(parameter.USERS_MAIL_VALIDATION) or parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  65. form.instance.is_active = False
  66. form.save()
  67. # Send welcome message
  68. emails.send_welcome_mail(form.instance)
  69. if parameter.get(parameter.USERS_MAIL_VALIDATION):
  70. emails.send_validation_mail(form.instance, request)
  71. # Add success message
  72. messages.success(request, parameter.registration_flow_description(form.cleaned_data.get('username')))
  73. return redirect('users-login')
  74. else:
  75. messages.error(request, _('Registration failed!'))
  76. context['form'] = form
  77. return render(request, 'users/register.html', context)
  78. else:
  79. messages.info(request, _("Self registration is deactivated. Contact your system administrator."))
  80. return redirect('users-login')
  81. def login(request):
  82. context = Context(request) # needs to be executed first because of time mesurement
  83. context_adaption(context, request, _('Login'))
  84. if not request.POST:
  85. form = AuthenticationForm()
  86. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  87. messages.info(request, _('If you don\'t have an acount, register <a href="%(url)s">here</a>.') % {'url': users.url_register(request)})
  88. else:
  89. form = AuthenticationForm(request, data=request.POST)
  90. if form.is_valid():
  91. username = form.cleaned_data.get('username')
  92. user = authenticate(username=username, password=form.cleaned_data.get('password'))
  93. django_login(request, user)
  94. messages.success(request, _('You are now logged in as %(username)s.') % {'username': username})
  95. return redirect(request.GET.get('next') or '/')
  96. else:
  97. username = form.cleaned_data.get('username')
  98. user = User.objects.get(username=username)
  99. if user.is_active:
  100. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  101. messages.error(request, _('Login failed! You can do a password recorvery <a href="%(url_recover)s">here</a> or you can register <a href="%(url_register)s">here</a>.') %
  102. {'url_register': users.url_register(request), 'url_recover': users.url_password_recovery(request)})
  103. else:
  104. messages.error(request, _('Login failed! You can do a password recorvery <a href="%(url_recover)s">here</a>.') %
  105. {'url_recover': users.url_password_recovery(request)})
  106. else:
  107. messages.info(request, _("The account is deactivated. Confirm your email adress and wait for the administrator to activate your account."))
  108. context['form'] = form
  109. return render(request, 'users/login.html', context)
  110. def logout(request):
  111. messages.success(request, _('You are no longer logged in as %(username)s.') % {'username': request.user.username})
  112. session_cache = {}
  113. try:
  114. for variable in settings.PERSISTENT_SESSION_VARIABLES:
  115. value = request.session.get(variable)
  116. if value is not None:
  117. session_cache[variable] = value
  118. except AttributeError:
  119. pass # PERSISTENT_SESSION_VARIABLES are possibly not defined in the settings
  120. django_logout(request)
  121. for variable in session_cache:
  122. request.session[variable] = session_cache[variable]
  123. return redirect(request.GET.get('next') or '/')
  124. def validate(request, uidb64, token):
  125. context = Context(request) # needs to be executed first because of time mesurement
  126. try:
  127. uid = force_str(urlsafe_base64_decode(uidb64))
  128. except (TypeError, ValueError, OverflowError, User.DoesNotExist):
  129. uid = None
  130. myuser = None
  131. else:
  132. try:
  133. myuser = User.objects.get(pk=uid)
  134. except User.DoesNotExist:
  135. myuser = None
  136. if myuser is not None and generate_token.check_token(myuser, token):
  137. # Store mail validation to user profile
  138. profile = get_userprofile(myuser)
  139. profile.mail_validated = True
  140. profile.save()
  141. if not parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  142. # Activate user
  143. myuser.is_active = True
  144. myuser.save()
  145. messages.success(request, _("Your Account has been activated."))
  146. return redirect('users-login')
  147. else:
  148. emails.send_activation_mail(myuser, request)
  149. messages.success(request, _("Your Email has been validated. Wait for the administrator to activate your account"))
  150. return redirect("/")
  151. else:
  152. context_adaption(
  153. context,
  154. request,
  155. _('Validation failed'),
  156. )
  157. messages.info(request, _("Vaildation failed. The system administrator will be informed."))
  158. emails.send_validation_failed(uid, token)
  159. return redirect("/")
  160. @login_required
  161. def activate(request, pk):
  162. context = Context(request) # needs to be executed first because of time mesurement
  163. if not request.POST:
  164. if request.user.is_superuser:
  165. user_to_be_activated = User.objects.get(pk=pk)
  166. if not user_to_be_activated.is_active:
  167. user_to_be_activated.is_active = True
  168. form = UserActivationForm(instance=user_to_be_activated)
  169. context_adaption(
  170. context,
  171. request,
  172. _('Activation of user: %s') % f"{user_to_be_activated.username} - {user_to_be_activated.email}",
  173. form=form,
  174. )
  175. return render(request, 'users/activate.html', context)
  176. else:
  177. messages.error(request, _("The user %s is already active.") % user_to_be_activated.username)
  178. else:
  179. messages.error(request, _("You are no administrator. Log in as administrator and try again!"))
  180. else:
  181. submit = request.POST.get("submit")
  182. delete = request.POST.get("delete")
  183. user_to_be_activated = User.objects.get(pk=pk)
  184. if submit:
  185. form = UserActivationForm(request.POST, instance=user_to_be_activated)
  186. if form.is_valid():
  187. form.save()
  188. messages.info(request, _("User permissions changed."))
  189. else:
  190. messages.error(request, _("Error while processing user change form"))
  191. if delete:
  192. user_to_be_activated.delete()
  193. messages.info(request, _("User deleted."))
  194. return redirect("/")