Django Library Users
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

views.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. # External Additional forms
  31. ext_profiles = parameter.get(parameter.USERS_PROFILE_ADDITIONS)
  32. # change class to instance
  33. ext_profiles = {key: ext_profiles[key](request) for key in ext_profiles}
  34. if request.POST:
  35. form_userprofile = UserProfileForm(request.POST, instance=profile)
  36. form_userchange = UserPasswordChangeForm(request)
  37. ext_valid = [form.is_valid() for form in ext_profiles.values()]
  38. if form_userprofile.is_valid() and form_userchange.is_valid() and not False in ext_valid:
  39. form_userprofile.save()
  40. form_userchange.save()
  41. for form in ext_profiles.values():
  42. form.save()
  43. return redirect(request.GET.get('next') or '/')
  44. else:
  45. form_userprofile = UserProfileForm(instance=profile)
  46. form_userchange = UserPasswordChangeForm(request)
  47. context_adaption(
  48. context,
  49. request,
  50. _('Profile for %(username)s') % {'username': request.user.username},
  51. form_userprofile=form_userprofile,
  52. form_userchange=form_userchange,
  53. ext_profiles=ext_profiles,
  54. )
  55. return render(request, 'users/profile.html', context=context)
  56. def register(request):
  57. context = Context(request) # needs to be executed first because of time mesurement
  58. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  59. context_adaption(context, request, _('Register'))
  60. if not request.POST:
  61. form = UserRegistrationForm()
  62. messages.info(request, _('If you already have an account, login <a href="%(url)s">here</a>.') % {'url': users.url_login(request)})
  63. else:
  64. form = UserRegistrationForm(request.POST)
  65. if form.is_valid():
  66. # Deactivate the user, if validation or activation is required
  67. if parameter.get(parameter.USERS_MAIL_VALIDATION) or parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  68. form.instance.is_active = False
  69. form.save()
  70. # Send welcome message
  71. emails.send_welcome_mail(form.instance)
  72. if parameter.get(parameter.USERS_MAIL_VALIDATION):
  73. emails.send_validation_mail(form.instance, request)
  74. # Add success message
  75. messages.success(request, parameter.registration_flow_description(form.cleaned_data.get('username')))
  76. return redirect('users-login')
  77. else:
  78. messages.error(request, _('Registration failed!'))
  79. context['form'] = form
  80. return render(request, 'users/register.html', context)
  81. else:
  82. messages.info(request, _("Self registration is deactivated. Contact your system administrator."))
  83. return redirect('users-login')
  84. def login(request):
  85. context = Context(request) # needs to be executed first because of time mesurement
  86. context_adaption(context, request, _('Login'))
  87. if not request.POST:
  88. form = AuthenticationForm()
  89. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  90. messages.info(request, _('If you don\'t have an acount, register <a href="%(url)s">here</a>.') % {'url': users.url_register(request)})
  91. else:
  92. form = AuthenticationForm(request, data=request.POST)
  93. if form.is_valid():
  94. username = form.cleaned_data.get('username')
  95. user = authenticate(username=username, password=form.cleaned_data.get('password'))
  96. django_login(request, user)
  97. messages.success(request, _('You are now logged in as %(username)s.') % {'username': username})
  98. return redirect(request.GET.get('next') or '/')
  99. else:
  100. username = form.cleaned_data.get('username')
  101. try:
  102. user = User.objects.get(username=username)
  103. except User.DoesNotExist:
  104. is_active = True
  105. else:
  106. is_active = user.is_active
  107. if is_active:
  108. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  109. 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>.') %
  110. {'url_register': users.url_register(request), 'url_recover': users.url_password_recovery(request)})
  111. else:
  112. messages.error(request, _('Login failed! You can do a password recorvery <a href="%(url_recover)s">here</a>.') %
  113. {'url_recover': users.url_password_recovery(request)})
  114. else:
  115. messages.info(request, _("The account is deactivated. Confirm your email adress and wait for the administrator to activate your account."))
  116. context['form'] = form
  117. return render(request, 'users/login.html', context)
  118. def logout(request):
  119. messages.success(request, _('You are no longer logged in as %(username)s.') % {'username': request.user.username})
  120. session_cache = {}
  121. try:
  122. for variable in settings.PERSISTENT_SESSION_VARIABLES:
  123. value = request.session.get(variable)
  124. if value is not None:
  125. session_cache[variable] = value
  126. except AttributeError:
  127. pass # PERSISTENT_SESSION_VARIABLES are possibly not defined in the settings
  128. django_logout(request)
  129. for variable in session_cache:
  130. request.session[variable] = session_cache[variable]
  131. return redirect(request.GET.get('next') or '/')
  132. def validate(request, uidb64, token):
  133. context = Context(request) # needs to be executed first because of time mesurement
  134. try:
  135. uid = force_str(urlsafe_base64_decode(uidb64))
  136. except (TypeError, ValueError, OverflowError, User.DoesNotExist):
  137. uid = None
  138. myuser = None
  139. else:
  140. try:
  141. myuser = User.objects.get(pk=uid)
  142. except User.DoesNotExist:
  143. myuser = None
  144. if myuser is not None and generate_token.check_token(myuser, token):
  145. up = get_userprofile(myuser)
  146. if up.mail_pending:
  147. # change of email-address
  148. myuser.email = up.mail_pending
  149. myuser.save()
  150. up.mail_pending = None
  151. up.save()
  152. messages.success(request, _("Your new email address is now active."))
  153. return redirect("/")
  154. else:
  155. # Store mail validation to user profile
  156. profile = get_userprofile(myuser)
  157. profile.mail_validated = True
  158. profile.save()
  159. if not parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  160. # Activate user
  161. myuser.is_active = True
  162. myuser.save()
  163. messages.success(request, _("Your Account has been activated."))
  164. return redirect('users-login')
  165. else:
  166. emails.send_activation_mail(myuser, request)
  167. messages.success(request, _("Your Email has been validated. Wait for the administrator to activate your account"))
  168. return redirect("/")
  169. else:
  170. context_adaption(
  171. context,
  172. request,
  173. _('Validation failed'),
  174. )
  175. messages.info(request, _("Vaildation failed. The system administrator will be informed."))
  176. emails.send_validation_failed(uid, token)
  177. return redirect("/")
  178. @login_required
  179. def activate(request, pk):
  180. context = Context(request) # needs to be executed first because of time mesurement
  181. if not request.POST:
  182. if request.user.is_superuser:
  183. user_to_be_activated = User.objects.get(pk=pk)
  184. if not user_to_be_activated.is_active:
  185. user_to_be_activated.is_active = True
  186. form = UserActivationForm(instance=user_to_be_activated)
  187. context_adaption(
  188. context,
  189. request,
  190. _('Activation of user: %s') % f"{user_to_be_activated.username} - {user_to_be_activated.email}",
  191. form=form,
  192. )
  193. return render(request, 'users/activate.html', context)
  194. else:
  195. messages.error(request, _("The user %s is already active.") % user_to_be_activated.username)
  196. else:
  197. messages.error(request, _("You are no administrator. Log in as administrator and try again!"))
  198. else:
  199. submit = request.POST.get("submit")
  200. delete = request.POST.get("delete")
  201. user_to_be_activated = User.objects.get(pk=pk)
  202. if submit:
  203. form = UserActivationForm(request.POST, instance=user_to_be_activated)
  204. if form.is_valid():
  205. form.save()
  206. messages.info(request, _("User permissions changed."))
  207. else:
  208. messages.error(request, _("Error while processing user change form"))
  209. if delete:
  210. user_to_be_activated.delete()
  211. messages.info(request, _("User deleted."))
  212. return redirect("/")