Django Library Users
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

views.py 13KB

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