Django Library Users
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

views.py 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. try:
  99. user = User.objects.get(username=username)
  100. except User.DoesNotExist:
  101. is_active = True
  102. else:
  103. is_active = user.is_active
  104. if is_active:
  105. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  106. 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>.') %
  107. {'url_register': users.url_register(request), 'url_recover': users.url_password_recovery(request)})
  108. else:
  109. messages.error(request, _('Login failed! You can do a password recorvery <a href="%(url_recover)s">here</a>.') %
  110. {'url_recover': users.url_password_recovery(request)})
  111. else:
  112. messages.info(request, _("The account is deactivated. Confirm your email adress and wait for the administrator to activate your account."))
  113. context['form'] = form
  114. return render(request, 'users/login.html', context)
  115. def logout(request):
  116. messages.success(request, _('You are no longer logged in as %(username)s.') % {'username': request.user.username})
  117. session_cache = {}
  118. try:
  119. for variable in settings.PERSISTENT_SESSION_VARIABLES:
  120. value = request.session.get(variable)
  121. if value is not None:
  122. session_cache[variable] = value
  123. except AttributeError:
  124. pass # PERSISTENT_SESSION_VARIABLES are possibly not defined in the settings
  125. django_logout(request)
  126. for variable in session_cache:
  127. request.session[variable] = session_cache[variable]
  128. return redirect(request.GET.get('next') or '/')
  129. def validate(request, uidb64, token):
  130. context = Context(request) # needs to be executed first because of time mesurement
  131. try:
  132. uid = force_str(urlsafe_base64_decode(uidb64))
  133. except (TypeError, ValueError, OverflowError, User.DoesNotExist):
  134. uid = None
  135. myuser = None
  136. else:
  137. try:
  138. myuser = User.objects.get(pk=uid)
  139. except User.DoesNotExist:
  140. myuser = None
  141. if myuser is not None and generate_token.check_token(myuser, token):
  142. # Store mail validation to user profile
  143. profile = get_userprofile(myuser)
  144. profile.mail_validated = True
  145. profile.save()
  146. if not parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  147. # Activate user
  148. myuser.is_active = True
  149. myuser.save()
  150. messages.success(request, _("Your Account has been activated."))
  151. return redirect('users-login')
  152. else:
  153. emails.send_activation_mail(myuser, request)
  154. messages.success(request, _("Your Email has been validated. Wait for the administrator to activate your account"))
  155. return redirect("/")
  156. else:
  157. context_adaption(
  158. context,
  159. request,
  160. _('Validation failed'),
  161. )
  162. messages.info(request, _("Vaildation failed. The system administrator will be informed."))
  163. emails.send_validation_failed(uid, token)
  164. return redirect("/")
  165. @login_required
  166. def activate(request, pk):
  167. context = Context(request) # needs to be executed first because of time mesurement
  168. if not request.POST:
  169. if request.user.is_superuser:
  170. user_to_be_activated = User.objects.get(pk=pk)
  171. if not user_to_be_activated.is_active:
  172. user_to_be_activated.is_active = True
  173. form = UserActivationForm(instance=user_to_be_activated)
  174. context_adaption(
  175. context,
  176. request,
  177. _('Activation of user: %s') % f"{user_to_be_activated.username} - {user_to_be_activated.email}",
  178. form=form,
  179. )
  180. return render(request, 'users/activate.html', context)
  181. else:
  182. messages.error(request, _("The user %s is already active.") % user_to_be_activated.username)
  183. else:
  184. messages.error(request, _("You are no administrator. Log in as administrator and try again!"))
  185. else:
  186. submit = request.POST.get("submit")
  187. delete = request.POST.get("delete")
  188. user_to_be_activated = User.objects.get(pk=pk)
  189. if submit:
  190. form = UserActivationForm(request.POST, instance=user_to_be_activated)
  191. if form.is_valid():
  192. form.save()
  193. messages.info(request, _("User permissions changed."))
  194. else:
  195. messages.error(request, _("Error while processing user change form"))
  196. if delete:
  197. user_to_be_activated.delete()
  198. messages.info(request, _("User deleted."))
  199. return redirect("/")