admin.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. from django import forms
  2. from django.contrib.auth import get_user_model
  3. from django.contrib.auth.password_validation import validate_password
  4. from django.db.models import Q
  5. from django.utils.translation import gettext_lazy as _
  6. from django.utils.translation import ngettext
  7. from ...acl.models import Role
  8. from ...admin.forms import IsoDateTimeField, YesNoSwitch
  9. from ...core.validators import validate_sluggable
  10. from ..models import Ban, DataDownload, Rank
  11. from ..profilefields import profilefields
  12. from ..utils import hash_email
  13. from ..validators import validate_email, validate_username
  14. User = get_user_model()
  15. class UserBaseForm(forms.ModelForm):
  16. username = forms.CharField(label=_("Username"))
  17. title = forms.CharField(label=_("Custom title"), required=False)
  18. email = forms.EmailField(label=_("E-mail address"))
  19. class Meta:
  20. model = User
  21. fields = ["username", "email", "title"]
  22. def __init__(self, *args, **kwargs):
  23. self.request = kwargs.pop("request")
  24. self.settings = self.request.settings
  25. super().__init__(*args, **kwargs)
  26. def clean_username(self):
  27. data = self.cleaned_data["username"]
  28. validate_username(self.settings, data, exclude=self.instance)
  29. return data
  30. def clean_email(self):
  31. data = self.cleaned_data["email"]
  32. validate_email(data, exclude=self.instance)
  33. return data
  34. def clean_new_password(self):
  35. data = self.cleaned_data["new_password"]
  36. if data:
  37. validate_password(data, user=self.instance)
  38. return data
  39. def clean_roles(self):
  40. data = self.cleaned_data["roles"]
  41. for role in data:
  42. if role.special_role == "authenticated":
  43. break
  44. else:
  45. message = _('All registered members must have "Member" role.')
  46. raise forms.ValidationError(message)
  47. return data
  48. class NewUserForm(UserBaseForm):
  49. new_password = forms.CharField(
  50. label=_("Password"), strip=False, widget=forms.PasswordInput
  51. )
  52. class Meta:
  53. model = User
  54. fields = ["username", "email", "title"]
  55. class EditUserForm(UserBaseForm):
  56. IS_STAFF_LABEL = _("Is administrator")
  57. IS_STAFF_HELP_TEXT = _(
  58. "Designates whether the user can log into admin sites. "
  59. "If Django admin site is enabled, this user will need "
  60. "additional permissions assigned within it to admin "
  61. "Django modules."
  62. )
  63. IS_SUPERUSER_LABEL = _("Is superuser")
  64. IS_SUPERUSER_HELP_TEXT = _(
  65. "Only administrators can access admin sites. "
  66. "In addition to admin site access, superadmins "
  67. "can also change other members admin levels."
  68. )
  69. IS_ACTIVE_LABEL = _("Is active")
  70. IS_ACTIVE_HELP_TEXT = _(
  71. "Designates whether this user should be treated as active. "
  72. "Turning this off is non-destructible way to remove user accounts."
  73. )
  74. IS_ACTIVE_STAFF_MESSAGE_LABEL = _("Staff message")
  75. IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT = _(
  76. "Optional message for forum team members explaining "
  77. "why user's account has been disabled."
  78. )
  79. new_password = forms.CharField(
  80. label=_("Change password to"),
  81. strip=False,
  82. widget=forms.PasswordInput,
  83. required=False,
  84. )
  85. is_avatar_locked = YesNoSwitch(
  86. label=_("Lock avatar"),
  87. help_text=_(
  88. "Setting this to yes will stop user from changing "
  89. "his/her avatar, and will reset his/her avatar to "
  90. "procedurally generated one."
  91. ),
  92. )
  93. avatar_lock_user_message = forms.CharField(
  94. label=_("User message"),
  95. help_text=_(
  96. "Optional message for user explaining "
  97. "why he/she is banned form changing avatar."
  98. ),
  99. widget=forms.Textarea(attrs={"rows": 3}),
  100. required=False,
  101. )
  102. avatar_lock_staff_message = forms.CharField(
  103. label=_("Staff message"),
  104. help_text=_(
  105. "Optional message for forum team members explaining "
  106. "why user is banned form changing avatar."
  107. ),
  108. widget=forms.Textarea(attrs={"rows": 3}),
  109. required=False,
  110. )
  111. signature = forms.CharField(
  112. label=_("Signature contents"),
  113. widget=forms.Textarea(attrs={"rows": 3}),
  114. required=False,
  115. )
  116. is_signature_locked = YesNoSwitch(
  117. label=_("Lock signature"),
  118. help_text=_(
  119. "Setting this to yes will stop user from "
  120. "making changes to his/her signature."
  121. ),
  122. )
  123. signature_lock_user_message = forms.CharField(
  124. label=_("User message"),
  125. help_text=_(
  126. "Optional message to user explaining why his/hers signature is locked."
  127. ),
  128. widget=forms.Textarea(attrs={"rows": 3}),
  129. required=False,
  130. )
  131. signature_lock_staff_message = forms.CharField(
  132. label=_("Staff message"),
  133. help_text=_(
  134. "Optional message to team members explaining why user signature is locked."
  135. ),
  136. widget=forms.Textarea(attrs={"rows": 3}),
  137. required=False,
  138. )
  139. is_hiding_presence = YesNoSwitch(label=_("Hides presence"))
  140. limits_private_thread_invites_to = forms.TypedChoiceField(
  141. label=_("Who can add user to private threads"),
  142. coerce=int,
  143. choices=User.LIMIT_INVITES_TO_CHOICES,
  144. )
  145. subscribe_to_started_threads = forms.TypedChoiceField(
  146. label=_("Started threads"), coerce=int, choices=User.SUBSCRIPTION_CHOICES
  147. )
  148. subscribe_to_replied_threads = forms.TypedChoiceField(
  149. label=_("Replid threads"), coerce=int, choices=User.SUBSCRIPTION_CHOICES
  150. )
  151. class Meta:
  152. model = User
  153. fields = [
  154. "username",
  155. "email",
  156. "title",
  157. "is_avatar_locked",
  158. "avatar_lock_user_message",
  159. "avatar_lock_staff_message",
  160. "signature",
  161. "is_signature_locked",
  162. "is_hiding_presence",
  163. "limits_private_thread_invites_to",
  164. "signature_lock_user_message",
  165. "signature_lock_staff_message",
  166. "subscribe_to_started_threads",
  167. "subscribe_to_replied_threads",
  168. ]
  169. def __init__(self, *args, **kwargs):
  170. super().__init__(*args, **kwargs)
  171. profilefields.add_fields_to_admin_form(self.request, self.instance, self)
  172. def get_profile_fields_groups(self):
  173. profile_fields_groups = []
  174. for group in self._profile_fields_groups:
  175. fields_group = {"name": group["name"], "fields": []}
  176. for fieldname in group["fields"]:
  177. fields_group["fields"].append(self[fieldname])
  178. profile_fields_groups.append(fields_group)
  179. return profile_fields_groups
  180. def clean_signature(self):
  181. data = self.cleaned_data["signature"]
  182. length_limit = self.settings.signature_length_max
  183. if len(data) > length_limit:
  184. message = ngettext(
  185. "Signature can't be longer than %(limit)s character.",
  186. "Signature can't be longer than %(limit)s characters.",
  187. length_limit,
  188. )
  189. raise forms.ValidationError(message % {"limit": length_limit})
  190. return data
  191. def clean(self):
  192. data = super().clean()
  193. return profilefields.clean_form(self.request, self.instance, self, data)
  194. def UserFormFactory(FormType, instance):
  195. extra_fields = {}
  196. extra_fields["rank"] = forms.ModelChoiceField(
  197. label=_("Rank"),
  198. help_text=_(
  199. "Ranks are used to group and distinguish users. They are "
  200. "also used to add permissions to groups of users."
  201. ),
  202. queryset=Rank.objects.order_by("name"),
  203. initial=instance.rank,
  204. )
  205. roles = Role.objects.order_by("name")
  206. extra_fields["roles"] = forms.ModelMultipleChoiceField(
  207. label=_("Roles"),
  208. help_text=_(
  209. 'Individual roles of this user. All users must have "member" role.'
  210. ),
  211. queryset=roles,
  212. initial=instance.roles.all() if instance.pk else None,
  213. widget=forms.CheckboxSelectMultiple,
  214. )
  215. return type("UserFormFinal", (FormType,), extra_fields)
  216. def StaffFlagUserFormFactory(FormType, instance):
  217. staff_fields = {
  218. "is_staff": YesNoSwitch(
  219. label=EditUserForm.IS_STAFF_LABEL,
  220. help_text=EditUserForm.IS_STAFF_HELP_TEXT,
  221. initial=instance.is_staff,
  222. ),
  223. "is_superuser": YesNoSwitch(
  224. label=EditUserForm.IS_SUPERUSER_LABEL,
  225. help_text=EditUserForm.IS_SUPERUSER_HELP_TEXT,
  226. initial=instance.is_superuser,
  227. ),
  228. }
  229. return type("StaffUserForm", (FormType,), staff_fields)
  230. def UserIsActiveFormFactory(FormType, instance):
  231. is_active_fields = {
  232. "is_active": YesNoSwitch(
  233. label=EditUserForm.IS_ACTIVE_LABEL,
  234. help_text=EditUserForm.IS_ACTIVE_HELP_TEXT,
  235. initial=instance.is_active,
  236. ),
  237. "is_active_staff_message": forms.CharField(
  238. label=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_LABEL,
  239. help_text=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT,
  240. initial=instance.is_active_staff_message,
  241. widget=forms.Textarea(attrs={"rows": 3}),
  242. required=False,
  243. ),
  244. }
  245. return type("UserIsActiveForm", (FormType,), is_active_fields)
  246. def EditUserFormFactory(
  247. FormType, instance, add_is_active_fields=False, add_admin_fields=False
  248. ):
  249. FormType = UserFormFactory(FormType, instance)
  250. if add_is_active_fields:
  251. FormType = UserIsActiveFormFactory(FormType, instance)
  252. if add_admin_fields:
  253. FormType = StaffFlagUserFormFactory(FormType, instance)
  254. return FormType
  255. class BaseFilterUsersForm(forms.Form):
  256. username = forms.CharField(label=_("Username starts with"), required=False)
  257. email = forms.CharField(label=_("E-mail starts with"), required=False)
  258. profilefields = forms.CharField(label=_("Profile fields contain"), required=False)
  259. is_inactive = forms.BooleanField(label=_("Requires activation"))
  260. is_disabled = forms.BooleanField(label=_("Account disabled"))
  261. is_staff = forms.BooleanField(label=_("Administrator"))
  262. is_deleting_account = forms.BooleanField(label=_("Deletes their account"))
  263. def filter_queryset(self, criteria, queryset):
  264. if criteria.get("username"):
  265. queryset = queryset.filter(
  266. slug__startswith=criteria.get("username").lower()
  267. )
  268. if criteria.get("email"):
  269. queryset = queryset.filter(email__istartswith=criteria.get("email"))
  270. if criteria.get("rank"):
  271. queryset = queryset.filter(rank_id=criteria.get("rank"))
  272. if criteria.get("role"):
  273. queryset = queryset.filter(roles__id=criteria.get("role"))
  274. if criteria.get("is_inactive"):
  275. queryset = queryset.filter(requires_activation__gt=0)
  276. if criteria.get("is_disabled"):
  277. queryset = queryset.filter(is_active=False)
  278. if criteria.get("is_staff"):
  279. queryset = queryset.filter(is_staff=True)
  280. if criteria.get("is_deleting_account"):
  281. queryset = queryset.filter(is_deleting_account=True)
  282. if criteria.get("profilefields", "").strip():
  283. queryset = profilefields.search_users(
  284. criteria.get("profilefields").strip(), queryset
  285. )
  286. return queryset
  287. def create_filter_users_form():
  288. """
  289. Factory that uses cache for ranks and roles,
  290. and makes those ranks and roles typed choice fields that play nice
  291. with passing values via GET
  292. """
  293. ranks_choices = [("", _("All ranks"))]
  294. for rank in Rank.objects.order_by("name").iterator():
  295. ranks_choices.append((rank.pk, rank.name))
  296. roles_choices = [("", _("All roles"))]
  297. for role in Role.objects.order_by("name").iterator():
  298. roles_choices.append((role.pk, role.name))
  299. extra_fields = {
  300. "rank": forms.TypedChoiceField(
  301. label=_("Has rank"), coerce=int, required=False, choices=ranks_choices
  302. ),
  303. "role": forms.TypedChoiceField(
  304. label=_("Has role"), coerce=int, required=False, choices=roles_choices
  305. ),
  306. }
  307. return type("FilterUsersForm", (BaseFilterUsersForm,), extra_fields)
  308. class RankForm(forms.ModelForm):
  309. name = forms.CharField(
  310. label=_("Name"),
  311. validators=[validate_sluggable()],
  312. help_text=_(
  313. "Short and descriptive name of all users with this rank. "
  314. '"The Team" or "Game Masters" are good examples.'
  315. ),
  316. )
  317. title = forms.CharField(
  318. label=_("User title"),
  319. required=False,
  320. help_text=_(
  321. "Optional, singular version of rank name displayed by user names. "
  322. 'For example "GM" or "Dev".'
  323. ),
  324. )
  325. description = forms.CharField(
  326. label=_("Description"),
  327. max_length=2048,
  328. required=False,
  329. widget=forms.Textarea(attrs={"rows": 3}),
  330. help_text=_(
  331. "Optional description explaining function or status of "
  332. "members distincted with this rank."
  333. ),
  334. )
  335. roles = forms.ModelMultipleChoiceField(
  336. label=_("User roles"),
  337. widget=forms.CheckboxSelectMultiple,
  338. queryset=Role.objects.order_by("name"),
  339. required=False,
  340. help_text=_("Rank can give additional roles to users with it."),
  341. )
  342. css_class = forms.CharField(
  343. label=_("CSS class"),
  344. required=False,
  345. help_text=_(
  346. "Optional css class added to content belonging to this rank owner."
  347. ),
  348. )
  349. is_tab = YesNoSwitch(
  350. label=_("Give rank dedicated tab on users list"),
  351. required=False,
  352. help_text=_(
  353. "Selecting this option will make users with this rank easily discoverable "
  354. "by others through dedicated page on forum users list."
  355. ),
  356. )
  357. class Meta:
  358. model = Rank
  359. fields = ["name", "description", "css_class", "title", "roles", "is_tab"]
  360. def clean_name(self):
  361. data = self.cleaned_data["name"]
  362. self.instance.set_name(data)
  363. unique_qs = Rank.objects.filter(slug=self.instance.slug)
  364. if self.instance.pk:
  365. unique_qs = unique_qs.exclude(pk=self.instance.pk)
  366. if unique_qs.exists():
  367. raise forms.ValidationError(_("This name collides with other rank."))
  368. return data
  369. class BanUsersForm(forms.Form):
  370. ban_type = forms.MultipleChoiceField(
  371. label=_("Values to ban"), widget=forms.CheckboxSelectMultiple, choices=[]
  372. )
  373. user_message = forms.CharField(
  374. label=_("User message"),
  375. required=False,
  376. max_length=1000,
  377. help_text=_("Optional message displayed to users instead of default one."),
  378. widget=forms.Textarea(attrs={"rows": 3}),
  379. error_messages={
  380. "max_length": _("Message can't be longer than 1000 characters.")
  381. },
  382. )
  383. staff_message = forms.CharField(
  384. label=_("Team message"),
  385. required=False,
  386. max_length=1000,
  387. help_text=_("Optional ban message for moderators and administrators."),
  388. widget=forms.Textarea(attrs={"rows": 3}),
  389. error_messages={
  390. "max_length": _("Message can't be longer than 1000 characters.")
  391. },
  392. )
  393. expires_on = IsoDateTimeField(label=_("Expiration date"), required=False)
  394. def __init__(self, *args, **kwargs):
  395. users = kwargs.pop("users")
  396. super().__init__(*args, **kwargs)
  397. self.fields["ban_type"].choices = [
  398. ("usernames", _("Usernames")),
  399. ("emails", _("E-mails")),
  400. ("domains", _("E-mail domains")),
  401. ]
  402. enable_ip_bans = list(filter(None, [u.joined_from_ip for u in users]))
  403. if enable_ip_bans:
  404. self.fields["ban_type"].choices += [
  405. ("ip", _("IP addresses")),
  406. ("ip_first", _("First segment of IP addresses")),
  407. ("ip_two", _("First two segments of IP addresses")),
  408. ]
  409. class BanForm(forms.ModelForm):
  410. check_type = forms.TypedChoiceField(
  411. label=_("Check type"), coerce=int, choices=Ban.CHOICES
  412. )
  413. registration_only = YesNoSwitch(
  414. label=_("Restrict this ban to registrations"),
  415. help_text=_(
  416. "Changing this to yes will make this ban check be only performed on "
  417. "registration step. This is good if you want to block certain "
  418. "registrations like ones from recently comprimised e-mail providers, "
  419. "without harming existing users."
  420. ),
  421. )
  422. banned_value = forms.CharField(
  423. label=_("Banned value"),
  424. max_length=250,
  425. help_text=_(
  426. "This value is case-insensitive and accepts asterisk (*) "
  427. "for rought matches. For example, making IP ban for value "
  428. '"83.*" will ban all IP addresses beginning with "83.".'
  429. ),
  430. error_messages={
  431. "max_length": _("Banned value can't be longer than 250 characters.")
  432. },
  433. )
  434. user_message = forms.CharField(
  435. label=_("User message"),
  436. required=False,
  437. max_length=1000,
  438. help_text=_("Optional message displayed to user instead of default one."),
  439. widget=forms.Textarea(attrs={"rows": 3}),
  440. error_messages={
  441. "max_length": _("Message can't be longer than 1000 characters.")
  442. },
  443. )
  444. staff_message = forms.CharField(
  445. label=_("Team message"),
  446. required=False,
  447. max_length=1000,
  448. help_text=_("Optional ban message for moderators and administrators."),
  449. widget=forms.Textarea(attrs={"rows": 3}),
  450. error_messages={
  451. "max_length": _("Message can't be longer than 1000 characters.")
  452. },
  453. )
  454. expires_on = IsoDateTimeField(label=_("Expiration date"), required=False)
  455. class Meta:
  456. model = Ban
  457. fields = [
  458. "check_type",
  459. "registration_only",
  460. "banned_value",
  461. "user_message",
  462. "staff_message",
  463. "expires_on",
  464. ]
  465. def clean_banned_value(self):
  466. data = self.cleaned_data["banned_value"]
  467. while "**" in data:
  468. data = data.replace("**", "*")
  469. if data == "*":
  470. raise forms.ValidationError(_("Banned value is too vague."))
  471. return data
  472. class FilterBansForm(forms.Form):
  473. check_type = forms.ChoiceField(
  474. label=_("Type"),
  475. required=False,
  476. choices=[
  477. ("", _("All bans")),
  478. ("names", _("Usernames")),
  479. ("emails", _("E-mails")),
  480. ("ips", _("IPs")),
  481. ],
  482. )
  483. value = forms.CharField(label=_("Banned value begins with"), required=False)
  484. registration_only = forms.ChoiceField(
  485. label=_("Registration only"),
  486. required=False,
  487. choices=[("", _("Any")), ("only", _("Yes")), ("exclude", _("No"))],
  488. )
  489. state = forms.ChoiceField(
  490. label=_("State"),
  491. required=False,
  492. choices=[("", _("Any")), ("used", _("Active")), ("unused", _("Expired"))],
  493. )
  494. def filter_queryset(self, criteria, queryset):
  495. if criteria.get("check_type") == "names":
  496. queryset = queryset.filter(check_type=0)
  497. if criteria.get("check_type") == "emails":
  498. queryset = queryset.filter(check_type=1)
  499. if criteria.get("check_type") == "ips":
  500. queryset = queryset.filter(check_type=2)
  501. if criteria.get("value"):
  502. queryset = queryset.filter(
  503. banned_value__startswith=criteria.get("value").lower()
  504. )
  505. if criteria.get("state") == "used":
  506. queryset = queryset.filter(is_checked=True)
  507. if criteria.get("state") == "unused":
  508. queryset = queryset.filter(is_checked=False)
  509. if criteria.get("registration_only") == "only":
  510. queryset = queryset.filter(registration_only=True)
  511. if criteria.get("registration_only") == "exclude":
  512. queryset = queryset.filter(registration_only=False)
  513. return queryset
  514. class RequestDataDownloadsForm(forms.Form):
  515. user_identifiers = forms.CharField(
  516. label=_("Usernames or emails"),
  517. help_text=_(
  518. "Enter every item in new line. Duplicates will be ignored. "
  519. "This field is case insensitive. Depending on site configuration and "
  520. "amount of data to archive it may take up to few days for requests to "
  521. "complete. E-mail will notification will be sent to every user once their "
  522. "download is ready."
  523. ),
  524. widget=forms.Textarea,
  525. )
  526. def clean_user_identifiers(self):
  527. user_identifiers = self.cleaned_data["user_identifiers"].lower().splitlines()
  528. user_identifiers = list(filter(bool, user_identifiers))
  529. user_identifiers = list(set(user_identifiers))
  530. if len(user_identifiers) > 20:
  531. raise forms.ValidationError(
  532. _(
  533. "You may not enter more than 20 items at single time "
  534. "(You have entered %(show_value)s)."
  535. )
  536. % {"show_value": len(user_identifiers)}
  537. )
  538. return user_identifiers
  539. def clean(self):
  540. data = super().clean()
  541. if data.get("user_identifiers"):
  542. username_match = Q(slug__in=data["user_identifiers"])
  543. email_match = Q(email_hash__in=map(hash_email, data["user_identifiers"]))
  544. data["users"] = list(User.objects.filter(username_match | email_match))
  545. if len(data["users"]) != len(data["user_identifiers"]):
  546. raise forms.ValidationError(
  547. _("One or more specified users could not be found.")
  548. )
  549. return data
  550. class FilterDataDownloadsForm(forms.Form):
  551. status = forms.ChoiceField(
  552. label=_("Status"), required=False, choices=DataDownload.STATUS_CHOICES
  553. )
  554. user = forms.CharField(label=_("User"), required=False)
  555. requested_by = forms.CharField(label=_("Requested by"), required=False)
  556. def filter_queryset(self, criteria, queryset):
  557. if criteria.get("status") is not None:
  558. queryset = queryset.filter(status=criteria["status"])
  559. if criteria.get("user"):
  560. queryset = queryset.filter(user__slug__istartswith=criteria["user"])
  561. if criteria.get("requested_by"):
  562. queryset = queryset.filter(
  563. requester__slug__istartswith=criteria["requested_by"]
  564. )
  565. return queryset