Django Library Users
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

views.py 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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, UserPasswordChangeForm
  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. @login_required
  27. def profile(request):
  28. context = Context(request) # needs to be executed first because of time mesurement
  29. profile = get_userprofile(request.user)
  30. if request.POST:
  31. form_userprofile = UserProfileForm(request.POST, instance=profile)
  32. form_userchange = UserPasswordChangeForm(request)
  33. if form_userprofile.is_valid() and form_userchange.is_valid():
  34. form_userprofile.save()
  35. form_userchange.save()
  36. return redirect(request.GET.get('next') or '/')
  37. else:
  38. form_userprofile = UserProfileForm(instance=profile)
  39. form_userchange = UserPasswordChangeForm(request)
  40. context_adaption(
  41. context,
  42. request,
  43. _('Profile for %(username)s') % {'username': request.user.username},
  44. form_userprofile=form_userprofile,
  45. form_userchange=form_userchange,
  46. )
  47. return render(request, 'users/profile.html', context=context)
  48. def register(request):
  49. context = Context(request) # needs to be executed first because of time mesurement
  50. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  51. context_adaption(context, request, _('Register'))
  52. if not request.POST:
  53. form = UserRegistrationForm()
  54. messages.info(request, _('If you already have an account, login <a href="%(url)s">here</a>.') % {'url': users.url_login(request)})
  55. else:
  56. form = UserRegistrationForm(request.POST)
  57. if form.is_valid():
  58. # Deactivate the user, if validation or activation is required
  59. if parameter.get(parameter.USERS_MAIL_VALIDATION) or parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  60. form.instance.is_active = False
  61. form.save()
  62. # Send welcome message
  63. emails.send_welcome_mail(form.instance)
  64. if parameter.get(parameter.USERS_MAIL_VALIDATION):
  65. emails.send_validation_mail(form.instance, request)
  66. # Add success message
  67. messages.success(request, parameter.registration_flow_description(form.cleaned_data.get('username')))
  68. return redirect('users-login')
  69. else:
  70. messages.error(request, _('Registration failed!'))
  71. context['form'] = form
  72. return render(request, 'users/register.html', context)
  73. else:
  74. messages.info(request, _("Self registration is deactivated. Contact your system administrator."))
  75. return redirect('users-login')
  76. def login(request):
  77. context = Context(request) # needs to be executed first because of time mesurement
  78. context_adaption(context, request, _('Login'))
  79. if not request.POST:
  80. form = AuthenticationForm()
  81. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  82. messages.info(request, _('If you don\'t have an acount, register <a href="%(url)s">here</a>.') % {'url': users.url_register(request)})
  83. else:
  84. form = AuthenticationForm(request, data=request.POST)
  85. if form.is_valid():
  86. username = form.cleaned_data.get('username')
  87. user = authenticate(username=username, password=form.cleaned_data.get('password'))
  88. django_login(request, user)
  89. messages.success(request, _('You are now logged in as %(username)s.') % {'username': username})
  90. return redirect(request.GET.get('next') or '/')
  91. else:
  92. username = form.cleaned_data.get('username')
  93. try:
  94. user = User.objects.get(username=username)
  95. except User.DoesNotExist:
  96. is_active = True
  97. else:
  98. is_active = user.is_active
  99. if 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. up = get_userprofile(myuser)
  138. if up.mail_pending:
  139. # change of email-address
  140. myuser.email = up.mail_pending
  141. myuser.save()
  142. up.mail_pending = None
  143. up.save()
  144. messages.success(request, _("Your new email address is now active."))
  145. return redirect("/")
  146. else:
  147. # Store mail validation to user profile
  148. profile = get_userprofile(myuser)
  149. profile.mail_validated = True
  150. profile.save()
  151. if not parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  152. # Activate user
  153. myuser.is_active = True
  154. myuser.save()
  155. messages.success(request, _("Your Account has been activated."))
  156. return redirect('users-login')
  157. else:
  158. emails.send_activation_mail(myuser, request)
  159. messages.success(request, _("Your Email has been validated. Wait for the administrator to activate your account"))
  160. return redirect("/")
  161. else:
  162. context_adaption(
  163. context,
  164. request,
  165. _('Validation failed'),
  166. )
  167. messages.info(request, _("Vaildation failed. The system administrator will be informed."))
  168. emails.send_validation_failed(uid, token)
  169. return redirect("/")
  170. @login_required
  171. def activate(request, pk):
  172. context = Context(request) # needs to be executed first because of time mesurement
  173. if not request.POST:
  174. if request.user.is_superuser:
  175. user_to_be_activated = User.objects.get(pk=pk)
  176. if not user_to_be_activated.is_active:
  177. user_to_be_activated.is_active = True
  178. form = UserActivationForm(instance=user_to_be_activated)
  179. context_adaption(
  180. context,
  181. request,
  182. _('Activation of user: %s') % f"{user_to_be_activated.username} - {user_to_be_activated.email}",
  183. form=form,
  184. )
  185. return render(request, 'users/activate.html', context)
  186. else:
  187. messages.error(request, _("The user %s is already active.") % user_to_be_activated.username)
  188. else:
  189. messages.error(request, _("You are no administrator. Log in as administrator and try again!"))
  190. else:
  191. submit = request.POST.get("submit")
  192. delete = request.POST.get("delete")
  193. user_to_be_activated = User.objects.get(pk=pk)
  194. if submit:
  195. form = UserActivationForm(request.POST, instance=user_to_be_activated)
  196. if form.is_valid():
  197. form.save()
  198. messages.info(request, _("User permissions changed."))
  199. else:
  200. messages.error(request, _("Error while processing user change form"))
  201. if delete:
  202. user_to_be_activated.delete()
  203. messages.info(request, _("User deleted."))
  204. return redirect("/")