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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 PasswordRecoverForm, UserRegistrationForm, UserProfileForm, UserActivationForm, UserPasswordChangeForm, PasswordRecoverChangeForm
  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 recover(request):
  57. context = Context(request) # needs to be executed first because of time mesurement
  58. context_adaption(context, request, _('Password Recovery'))
  59. if not request.POST:
  60. form = PasswordRecoverForm(request)
  61. else:
  62. username = request.POST.get("username")
  63. try:
  64. user = User.objects.get(username=username)
  65. except User.DoesNotExist:
  66. pass # hide non existing user (just do nothing)
  67. else:
  68. profile = get_userprofile(user)
  69. if profile.mail_validated:
  70. emails.send_recover_mail(user, request)
  71. #
  72. messages.info(request, _("If the user exists, you will get a reover email."))
  73. return redirect("users-login")
  74. context['form'] = form
  75. return render(request, 'users/recover.html', context)
  76. def register(request):
  77. context = Context(request) # needs to be executed first because of time mesurement
  78. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  79. context_adaption(context, request, _('Register'))
  80. if not request.POST:
  81. form = UserRegistrationForm()
  82. messages.info(request, _('If you already have an account, login <a href="%(url)s">here</a>.') % {'url': users.url_login(request)})
  83. else:
  84. form = UserRegistrationForm(request.POST)
  85. if form.is_valid():
  86. # Deactivate the user, if validation or activation is required
  87. if parameter.get(parameter.USERS_MAIL_VALIDATION) or parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  88. form.instance.is_active = False
  89. form.save()
  90. # Send welcome message
  91. emails.send_welcome_mail(form.instance)
  92. if parameter.get(parameter.USERS_MAIL_VALIDATION):
  93. emails.send_validation_mail(form.instance, request)
  94. # Add success message
  95. messages.success(request, parameter.registration_flow_description(form.cleaned_data.get('username')))
  96. return redirect('users-login')
  97. else:
  98. messages.error(request, _('Registration failed!'))
  99. context['form'] = form
  100. return render(request, 'users/register.html', context)
  101. else:
  102. messages.info(request, _("Self registration is deactivated. Contact your system administrator."))
  103. return redirect('users-login')
  104. def login(request):
  105. context = Context(request) # needs to be executed first because of time mesurement
  106. context_adaption(context, request, _('Login'))
  107. if not request.POST:
  108. form = AuthenticationForm()
  109. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  110. messages.info(request, _('If you don\'t have an acount, register <a href="%(url)s">here</a>.') % {'url': users.url_register(request)})
  111. else:
  112. form = AuthenticationForm(request, data=request.POST)
  113. if form.is_valid():
  114. username = form.cleaned_data.get('username')
  115. user = authenticate(username=username, password=form.cleaned_data.get('password'))
  116. django_login(request, user)
  117. messages.success(request, _('You are now logged in as %(username)s.') % {'username': username})
  118. return redirect(request.GET.get('next') or '/')
  119. else:
  120. username = form.cleaned_data.get('username')
  121. try:
  122. user = User.objects.get(username=username)
  123. except User.DoesNotExist:
  124. is_active = True
  125. else:
  126. is_active = user.is_active
  127. if is_active:
  128. if parameter.get(parameter.USERS_SELF_REGISTRATION):
  129. 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>.') %
  130. {'url_register': users.url_register(request), 'url_recover': users.url_recover(request)})
  131. else:
  132. messages.error(request, _('Login failed! You can do a password recorvery <a href="%(url_recover)s">here</a>.') %
  133. {'url_recover': users.url_recover(request)})
  134. else:
  135. messages.info(request, _("The account is deactivated. Confirm your email adress and wait for the administrator to activate your account."))
  136. context['form'] = form
  137. return render(request, 'users/login.html', context)
  138. def logout(request):
  139. messages.success(request, _('You are no longer logged in as %(username)s.') % {'username': request.user.username})
  140. session_cache = {}
  141. try:
  142. for variable in settings.PERSISTENT_SESSION_VARIABLES:
  143. value = request.session.get(variable)
  144. if value is not None:
  145. session_cache[variable] = value
  146. except AttributeError:
  147. pass # PERSISTENT_SESSION_VARIABLES are possibly not defined in the settings
  148. django_logout(request)
  149. for variable in session_cache:
  150. request.session[variable] = session_cache[variable]
  151. return redirect(request.GET.get('next') or '/')
  152. def validate(request, uidb64, token):
  153. context = Context(request) # needs to be executed first because of time mesurement
  154. try:
  155. uid = force_str(urlsafe_base64_decode(uidb64))
  156. except (TypeError, ValueError, OverflowError, User.DoesNotExist):
  157. uid = None
  158. myuser = None
  159. else:
  160. try:
  161. myuser = User.objects.get(pk=uid)
  162. except User.DoesNotExist:
  163. myuser = None
  164. if myuser is not None and generate_token.check_token(myuser, token):
  165. up = get_userprofile(myuser)
  166. if up.mail_pending:
  167. # change of email-address
  168. myuser.email = up.mail_pending
  169. myuser.save()
  170. up.mail_pending = None
  171. up.save()
  172. messages.success(request, _("Your new email address is now active."))
  173. return redirect("/")
  174. else:
  175. # Store mail validation to user profile
  176. profile = get_userprofile(myuser)
  177. profile.mail_validated = True
  178. profile.save()
  179. if not parameter.get(parameter.USERS_ADMIN_ACTIVATION):
  180. # Activate user
  181. myuser.is_active = True
  182. myuser.save()
  183. messages.success(request, _("Your Account has been activated."))
  184. return redirect('users-login')
  185. else:
  186. emails.send_activation_mail(myuser, request)
  187. messages.success(request, _("Your Email has been validated. Wait for the administrator to activate your account"))
  188. return redirect("/")
  189. else:
  190. context_adaption(
  191. context,
  192. request,
  193. _('Validation failed'),
  194. )
  195. messages.info(request, _("Vaildation failed. The system administrator will be informed."))
  196. emails.send_validation_failed(uid, token)
  197. return redirect("/")
  198. @login_required
  199. def activate(request, pk):
  200. context = Context(request) # needs to be executed first because of time mesurement
  201. if not request.POST:
  202. if request.user.is_superuser:
  203. user_to_be_activated = User.objects.get(pk=pk)
  204. if not user_to_be_activated.is_active:
  205. user_to_be_activated.is_active = True
  206. form = UserActivationForm(instance=user_to_be_activated)
  207. context_adaption(
  208. context,
  209. request,
  210. _('Activation of user: %s') % f"{user_to_be_activated.username} - {user_to_be_activated.email}",
  211. form=form,
  212. )
  213. return render(request, 'users/activate.html', context)
  214. else:
  215. messages.error(request, _("The user %s is already active.") % user_to_be_activated.username)
  216. else:
  217. messages.error(request, _("You are no administrator. Log in as administrator and try again!"))
  218. else:
  219. submit = request.POST.get("submit")
  220. delete = request.POST.get("delete")
  221. user_to_be_activated = User.objects.get(pk=pk)
  222. if submit:
  223. form = UserActivationForm(request.POST, instance=user_to_be_activated)
  224. if form.is_valid():
  225. form.save()
  226. messages.info(request, _("User permissions changed."))
  227. else:
  228. messages.error(request, _("Error while processing user change form"))
  229. if delete:
  230. user_to_be_activated.delete()
  231. messages.info(request, _("User deleted."))
  232. return redirect("/")
  233. def recover_token(request, uidb64, token):
  234. context = Context(request) # needs to be executed first because of time mesurement
  235. print(settings.PASSWORD_RESET_TIMEOUT)
  236. try:
  237. uid = force_str(urlsafe_base64_decode(uidb64))
  238. except (TypeError, ValueError, OverflowError, User.DoesNotExist):
  239. uid = None
  240. myuser = None
  241. else:
  242. try:
  243. myuser = User.objects.get(pk=uid)
  244. except User.DoesNotExist:
  245. myuser = None
  246. if myuser is not None and generate_token.check_token(myuser, token):
  247. if request.POST:
  248. form = PasswordRecoverChangeForm(myuser, data=request.POST)
  249. if form.is_valid():
  250. form.save()
  251. return redirect(request.GET.get('next') or 'users-login')
  252. else:
  253. form = PasswordRecoverChangeForm(myuser)
  254. #
  255. context_adaption(
  256. context,
  257. request,
  258. _('Password recovery for %(username)s') % {'username': myuser.username},
  259. form=form,
  260. )
  261. return render(request, 'users/recover.html', context=context)
  262. else:
  263. context_adaption(
  264. context,
  265. request,
  266. _('Recovery failed'),
  267. )
  268. messages.info(request, _("Recovery failed. The system administrator will be informed."))
  269. emails.send_recover_failed(uid, token)
  270. return redirect("/")