admin.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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.utils.translation import ugettext_lazy as _
  5. from django.utils.translation import ungettext
  6. from misago.acl.models import Role
  7. from misago.conf import settings
  8. from misago.core import threadstore
  9. from misago.core.forms import IsoDateTimeField, YesNoSwitch
  10. from misago.core.validators import validate_sluggable
  11. from ..models import (
  12. AUTO_SUBSCRIBE_CHOICES, BANS_CHOICES, PRIVATE_THREAD_INVITES_LIMITS_CHOICES,
  13. Ban, Rank
  14. )
  15. from ..validators import validate_email, validate_username
  16. """
  17. Users
  18. """
  19. class UserBaseForm(forms.ModelForm):
  20. username = forms.CharField(label=_("Username"))
  21. title = forms.CharField(label=_("Custom title"), required=False)
  22. email = forms.EmailField(label=_("E-mail address"))
  23. class Meta:
  24. model = get_user_model()
  25. fields = ['username', 'email', 'title']
  26. def clean_username(self):
  27. data = self.cleaned_data['username']
  28. validate_username(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"),
  51. widget=forms.PasswordInput
  52. )
  53. class Meta:
  54. model = get_user_model()
  55. fields = ['username', 'email', 'title']
  56. class EditUserForm(UserBaseForm):
  57. IS_STAFF_LABEL = _("Is administrator")
  58. IS_STAFF_HELP_TEXT = _(
  59. "Designates whether the user can log into admin sites. "
  60. "If Django admin site is enabled, this user will need "
  61. "additional permissions assigned within it to admin "
  62. "Django modules."
  63. )
  64. IS_SUPERUSER_LABEL = _("Is superuser")
  65. IS_SUPERUSER_HELP_TEXT = _(
  66. "Only administrators can access admin sites. "
  67. "In addition to admin site access, superadmins "
  68. "can also change other members admin levels."
  69. )
  70. IS_ACTIVE_LABEL = _('Is active')
  71. IS_ACTIVE_HELP_TEXT = _(
  72. "Designates whether this user should be treated as active. "
  73. "Turning this off is non-destructible way to remove user accounts."
  74. )
  75. IS_ACTIVE_STAFF_MESSAGE_LABEL=_("Staff message")
  76. IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT=_(
  77. "Optional message for forum team members explaining "
  78. "why user's account has been disabled."
  79. )
  80. new_password = forms.CharField(
  81. label=_("Change password to"),
  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=PRIVATE_THREAD_INVITES_LIMITS_CHOICES
  144. )
  145. subscribe_to_started_threads = forms.TypedChoiceField(
  146. label=_("Started threads"),
  147. coerce=int,
  148. choices=AUTO_SUBSCRIBE_CHOICES
  149. )
  150. subscribe_to_replied_threads = forms.TypedChoiceField(
  151. label=_("Replid threads"),
  152. coerce=int,
  153. choices=AUTO_SUBSCRIBE_CHOICES
  154. )
  155. class Meta:
  156. model = get_user_model()
  157. fields = [
  158. 'username',
  159. 'email',
  160. 'title',
  161. 'is_avatar_locked',
  162. 'avatar_lock_user_message',
  163. 'avatar_lock_staff_message',
  164. 'signature',
  165. 'is_signature_locked',
  166. 'is_hiding_presence',
  167. 'limits_private_thread_invites_to',
  168. 'signature_lock_user_message',
  169. 'signature_lock_staff_message',
  170. 'subscribe_to_started_threads',
  171. 'subscribe_to_replied_threads',
  172. ]
  173. def clean_signature(self):
  174. data = self.cleaned_data['signature']
  175. length_limit = settings.signature_length_max
  176. if len(data) > length_limit:
  177. raise forms.ValidationError(ungettext(
  178. "Signature can't be longer than %(limit)s character.",
  179. "Signature can't be longer than %(limit)s characters.",
  180. length_limit
  181. ) % {'limit': length_limit})
  182. return data
  183. def UserFormFactory(FormType, instance):
  184. extra_fields = {}
  185. extra_fields['rank'] = forms.ModelChoiceField(
  186. label=_("Rank"),
  187. help_text=_(
  188. "Ranks are used to group and distinguish users. They are "
  189. "also used to add permissions to groups of users."
  190. ),
  191. queryset=Rank.objects.order_by('name'),
  192. initial=instance.rank
  193. )
  194. roles = Role.objects.order_by('name')
  195. extra_fields['roles'] = forms.ModelMultipleChoiceField(
  196. label=_("Roles"),
  197. help_text=_(
  198. 'Individual roles of this user. All users must have "member" role.'
  199. ),
  200. queryset=roles,
  201. initial=instance.roles.all() if instance.pk else None,
  202. widget=forms.CheckboxSelectMultiple
  203. )
  204. return type('UserFormFinal', (FormType,), extra_fields)
  205. def StaffFlagUserFormFactory(FormType, instance):
  206. staff_fields = {
  207. 'is_staff': YesNoSwitch(
  208. label=EditUserForm.IS_STAFF_LABEL,
  209. help_text=EditUserForm.IS_STAFF_HELP_TEXT,
  210. initial=instance.is_staff
  211. ),
  212. 'is_superuser': YesNoSwitch(
  213. label=EditUserForm.IS_SUPERUSER_LABEL,
  214. help_text=EditUserForm.IS_SUPERUSER_HELP_TEXT,
  215. initial=instance.is_superuser
  216. ),
  217. }
  218. return type('StaffUserForm', (FormType,), staff_fields)
  219. def UserIsActiveFormFactory(FormType, instance):
  220. is_active_fields = {
  221. 'is_active': YesNoSwitch(
  222. label=EditUserForm.IS_ACTIVE_LABEL,
  223. help_text=EditUserForm.IS_ACTIVE_HELP_TEXT,
  224. initial=instance.is_active
  225. ),
  226. 'is_active_staff_message': forms.CharField(
  227. label=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_LABEL,
  228. help_text=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT,
  229. initial=instance.is_active_staff_message,
  230. widget=forms.Textarea(attrs={'rows': 3}),
  231. required=False
  232. ),
  233. }
  234. return type('UserIsActiveForm', (FormType,), is_active_fields)
  235. def EditUserFormFactory(FormType, instance,
  236. add_is_active_fields=False, add_admin_fields=False):
  237. FormType = UserFormFactory(FormType, instance)
  238. if add_is_active_fields:
  239. FormType = UserIsActiveFormFactory(FormType, instance)
  240. if add_admin_fields:
  241. FormType = StaffFlagUserFormFactory(FormType, instance)
  242. return FormType
  243. class SearchUsersFormBase(forms.Form):
  244. username = forms.CharField(label=_("Username starts with"), required=False)
  245. email = forms.CharField(label=_("E-mail starts with"), required=False)
  246. inactive = YesNoSwitch(label=_("Inactive only"))
  247. disabled = YesNoSwitch(label=_("Disabled only"))
  248. is_staff = YesNoSwitch(label=_("Admins only"))
  249. def filter_queryset(self, criteria, queryset):
  250. if criteria.get('username'):
  251. queryset = queryset.filter(
  252. slug__startswith=criteria.get('username').lower())
  253. if criteria.get('email'):
  254. queryset = queryset.filter(
  255. email__istartswith=criteria.get('email'))
  256. if criteria.get('rank'):
  257. queryset = queryset.filter(rank_id=criteria.get('rank'))
  258. if criteria.get('role'):
  259. queryset = queryset.filter(roles__id=criteria.get('role'))
  260. if criteria.get('inactive'):
  261. queryset = queryset.filter(requires_activation__gt=0)
  262. if criteria.get('disabled'):
  263. queryset = queryset.filter(is_active=False)
  264. if criteria.get('is_staff'):
  265. queryset = queryset.filter(is_staff=True)
  266. return queryset
  267. def SearchUsersForm(*args, **kwargs):
  268. """
  269. Factory that uses cache for ranks and roles,
  270. and makes those ranks and roles typed choice fields that play nice
  271. with passing values via GET
  272. """
  273. ranks_choices = threadstore.get('misago_admin_ranks_choices', 'nada')
  274. if ranks_choices == 'nada':
  275. ranks_choices = [('', _("All ranks"))]
  276. for rank in Rank.objects.order_by('name').iterator():
  277. ranks_choices.append((rank.pk, rank.name))
  278. threadstore.set('misago_admin_ranks_choices', ranks_choices)
  279. roles_choices = threadstore.get('misago_admin_roles_choices', 'nada')
  280. if roles_choices == 'nada':
  281. roles_choices = [('', _("All roles"))]
  282. for role in Role.objects.order_by('name').iterator():
  283. roles_choices.append((role.pk, role.name))
  284. threadstore.set('misago_admin_roles_choices', roles_choices)
  285. extra_fields = {
  286. 'rank': forms.TypedChoiceField(
  287. label=_("Has rank"),
  288. coerce=int,
  289. required=False,
  290. choices=ranks_choices
  291. ),
  292. 'role': forms.TypedChoiceField(
  293. label=_("Has role"),
  294. coerce=int,
  295. required=False,
  296. choices=roles_choices
  297. )
  298. }
  299. FinalForm = type(
  300. 'SearchUsersFormFinal', (SearchUsersFormBase,), extra_fields)
  301. return FinalForm(*args, **kwargs)
  302. """
  303. Ranks
  304. """
  305. class RankForm(forms.ModelForm):
  306. name = forms.CharField(
  307. label=_("Name"),
  308. validators=[validate_sluggable()],
  309. help_text=_(
  310. 'Short and descriptive name of all users with this rank. '
  311. '"The Team" or "Game Masters" are good examples.'
  312. )
  313. )
  314. title = forms.CharField(
  315. label=_("User title"),
  316. required=False,
  317. help_text=_(
  318. 'Optional, singular version of rank name displayed by user names. '
  319. 'For example "GM" or "Dev".'
  320. )
  321. )
  322. description = forms.CharField(
  323. label=_("Description"),
  324. max_length=2048,
  325. required=False,
  326. widget=forms.Textarea(attrs={'rows': 3}),
  327. help_text=_(
  328. "Optional description explaining function or status of "
  329. "members distincted with this rank."
  330. )
  331. )
  332. roles = forms.ModelMultipleChoiceField(
  333. label=_("User roles"),
  334. widget=forms.CheckboxSelectMultiple,
  335. queryset=Role.objects.order_by('name'),
  336. required=False,
  337. help_text=_("Rank can give additional roles to users with it.")
  338. )
  339. css_class = forms.CharField(
  340. label=_("CSS class"),
  341. required=False,
  342. help_text=_(
  343. "Optional css class added to content belonging to this rank owner."
  344. )
  345. )
  346. is_tab = forms.BooleanField(
  347. label=_("Give rank dedicated tab on users list"),
  348. required=False,
  349. help_text=_(
  350. "Selecting this option will make users with this rank "
  351. "easily discoverable by others trough dedicated page on "
  352. "forum users list."
  353. )
  354. )
  355. class Meta:
  356. model = Rank
  357. fields = [
  358. 'name',
  359. 'description',
  360. 'css_class',
  361. 'title',
  362. 'roles',
  363. 'is_tab',
  364. ]
  365. def clean_name(self):
  366. data = self.cleaned_data['name']
  367. self.instance.set_name(data)
  368. unique_qs = Rank.objects.filter(slug=self.instance.slug)
  369. if self.instance.pk:
  370. unique_qs = unique_qs.exclude(pk=self.instance.pk)
  371. if unique_qs.exists():
  372. raise forms.ValidationError(
  373. _("This name collides with other rank."))
  374. return data
  375. """
  376. Bans
  377. """
  378. class BanUsersForm(forms.Form):
  379. ban_type = forms.MultipleChoiceField(
  380. label=_("Values to ban"),
  381. widget=forms.CheckboxSelectMultiple,
  382. choices=(
  383. ('usernames', _('Usernames')),
  384. ('emails', _('E-mails')),
  385. ('domains', _('E-mail domains')),
  386. ('ip', _('IP addresses')),
  387. ('ip_first', _('First segment of IP addresses')),
  388. ('ip_two', _('First two segments of IP addresses'))
  389. )
  390. )
  391. user_message = forms.CharField(
  392. label=_("User message"),
  393. required=False,
  394. max_length=1000,
  395. help_text=_("Optional message displayed to users instead of default one."),
  396. widget=forms.Textarea(attrs={'rows': 3}),
  397. error_messages={
  398. 'max_length': _("Message can't be longer than 1000 characters.")
  399. }
  400. )
  401. staff_message = forms.CharField(
  402. label=_("Team message"),
  403. required=False,
  404. max_length=1000,
  405. help_text=_("Optional ban message for moderators and administrators."),
  406. widget=forms.Textarea(attrs={'rows': 3}),
  407. error_messages={
  408. 'max_length': _("Message can't be longer than 1000 characters.")
  409. }
  410. )
  411. expires_on = IsoDateTimeField(
  412. label=_("Expires on"),
  413. required=False,
  414. help_text=_("Leave this field empty for set bans to never expire.")
  415. )
  416. class BanForm(forms.ModelForm):
  417. check_type = forms.TypedChoiceField(
  418. label=_("Check type"),
  419. coerce=int,
  420. choices=BANS_CHOICES
  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 "
  432. "than 250 characters.")
  433. }
  434. )
  435. user_message = forms.CharField(
  436. label=_("User message"),
  437. required=False,
  438. max_length=1000,
  439. help_text=_("Optional message displayed to user instead of default one."),
  440. widget=forms.Textarea(attrs={'rows': 3}),
  441. error_messages={
  442. 'max_length': _("Message can't be longer than 1000 characters.")
  443. }
  444. )
  445. staff_message = forms.CharField(
  446. label=_("Team message"),
  447. required=False,
  448. max_length=1000,
  449. help_text=_("Optional ban message for moderators and administrators."),
  450. widget=forms.Textarea(attrs={'rows': 3}),
  451. error_messages={
  452. 'max_length': _("Message can't be longer than 1000 characters.")
  453. }
  454. )
  455. expires_on = IsoDateTimeField(
  456. label=_("Expires on"),
  457. required=False,
  458. help_text=_("Leave this field empty for this ban to never expire.")
  459. )
  460. class Meta:
  461. model = Ban
  462. fields = [
  463. 'check_type',
  464. 'banned_value',
  465. 'user_message',
  466. 'staff_message',
  467. 'expires_on',
  468. ]
  469. def clean_banned_value(self):
  470. data = self.cleaned_data['banned_value']
  471. while '**' in data:
  472. data = data.replace('**', '*')
  473. if data == '*':
  474. raise forms.ValidationError(_("Banned value is too vague."))
  475. return data
  476. SARCH_BANS_CHOICES = (
  477. ('', _('All bans')),
  478. ('names', _('Usernames')),
  479. ('emails', _('E-mails')),
  480. ('ips', _('IPs')),
  481. )
  482. class SearchBansForm(forms.Form):
  483. check_type = forms.ChoiceField(
  484. label=_("Type"),
  485. required=False,
  486. choices=SARCH_BANS_CHOICES
  487. )
  488. value = forms.CharField(
  489. label=_("Banned value begins with"),
  490. required=False
  491. )
  492. state = forms.ChoiceField(
  493. label=_("State"),
  494. required=False,
  495. choices=(
  496. ('', _('Any')),
  497. ('used', _('Active')),
  498. ('unused', _('Expired')),
  499. )
  500. )
  501. def filter_queryset(self, search_criteria, queryset):
  502. criteria = search_criteria
  503. if criteria.get('check_type') == 'names':
  504. queryset = queryset.filter(check_type=0)
  505. if criteria.get('check_type') == 'emails':
  506. queryset = queryset.filter(check_type=1)
  507. if criteria.get('check_type') == 'ips':
  508. queryset = queryset.filter(check_type=2)
  509. if criteria.get('value'):
  510. queryset = queryset.filter(
  511. banned_value__startswith=criteria.get('value').lower())
  512. if criteria.get('state') == 'used':
  513. queryset = queryset.filter(is_checked=True)
  514. if criteria.get('state') == 'unused':
  515. queryset = queryset.filter(is_checked=False)
  516. return queryset