admin.py 19 KB

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