admin.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. from django import forms
  2. from django.contrib.auth import get_user_model
  3. from django.utils.translation import ugettext_lazy as _
  4. from django.utils.translation import ungettext
  5. from misago.acl.models import Role
  6. from misago.conf import settings
  7. from misago.core import threadstore
  8. from misago.core.forms import IsoDateTimeField, YesNoSwitch
  9. from misago.core.validators import validate_sluggable
  10. from ..models import (
  11. AUTO_SUBSCRIBE_CHOICES, BANS_CHOICES, PRIVATE_THREAD_INVITES_LIMITS_CHOICES,
  12. Ban, Rank
  13. )
  14. from ..validators import validate_email, validate_password, validate_username
  15. """
  16. Users
  17. """
  18. class UserBaseForm(forms.ModelForm):
  19. username = forms.CharField(label=_("Username"))
  20. title = forms.CharField(label=_("Custom title"), required=False)
  21. email = forms.EmailField(label=_("E-mail address"))
  22. class Meta:
  23. model = get_user_model()
  24. fields = ['username', 'email', 'title']
  25. def clean_username(self):
  26. data = self.cleaned_data['username']
  27. validate_username(data, exclude=self.instance)
  28. return data
  29. def clean_email(self):
  30. data = self.cleaned_data['email']
  31. validate_email(data, exclude=self.instance)
  32. return data
  33. def clean_new_password(self):
  34. data = self.cleaned_data['new_password']
  35. if data:
  36. validate_password(data)
  37. return data
  38. def clean_roles(self):
  39. data = self.cleaned_data['roles']
  40. for role in data:
  41. if role.special_role == 'authenticated':
  42. break
  43. else:
  44. message = _('All registered members must have "Member" role.')
  45. raise forms.ValidationError(message)
  46. return data
  47. class NewUserForm(UserBaseForm):
  48. new_password = forms.CharField(
  49. label=_("Password"),
  50. widget=forms.PasswordInput
  51. )
  52. class Meta:
  53. model = get_user_model()
  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. widget=forms.PasswordInput,
  82. required=False
  83. )
  84. is_avatar_locked = YesNoSwitch(
  85. label=_("Lock avatar"),
  86. help_text=_(
  87. "Setting this to yes will stop user from changing "
  88. "his/her avatar, and will reset his/her avatar to "
  89. "procedurally generated one."
  90. )
  91. )
  92. avatar_lock_user_message = forms.CharField(
  93. label=_("User message"),
  94. help_text=_(
  95. "Optional message for user explaining "
  96. "why he/she is banned form changing avatar."
  97. ),
  98. widget=forms.Textarea(attrs={'rows': 3}),
  99. required=False
  100. )
  101. avatar_lock_staff_message = forms.CharField(
  102. label=_("Staff message"),
  103. help_text=_(
  104. "Optional message for forum team members explaining "
  105. "why user is banned form changing avatar."
  106. ),
  107. widget=forms.Textarea(attrs={'rows': 3}),
  108. required=False
  109. )
  110. signature = forms.CharField(
  111. label=_("Signature contents"),
  112. widget=forms.Textarea(attrs={'rows': 3}),
  113. required=False
  114. )
  115. is_signature_locked = YesNoSwitch(
  116. label=_("Lock signature"),
  117. help_text=_(
  118. "Setting this to yes will stop user from "
  119. "making changes to his/her signature."
  120. )
  121. )
  122. signature_lock_user_message = forms.CharField(
  123. label=_("User message"),
  124. help_text=_(
  125. "Optional message to user explaining why his/hers signature is locked."
  126. ),
  127. widget=forms.Textarea(attrs={'rows': 3}),
  128. required=False
  129. )
  130. signature_lock_staff_message = forms.CharField(
  131. label=_("Staff message"),
  132. help_text=_(
  133. "Optional message to team members explaining why user signature is locked."
  134. ),
  135. widget=forms.Textarea(attrs={'rows': 3}),
  136. required=False
  137. )
  138. is_hiding_presence = YesNoSwitch(label=_("Hides presence"))
  139. limits_private_thread_invites_to = forms.TypedChoiceField(
  140. label=_("Who can add user to private threads"),
  141. coerce=int,
  142. choices=PRIVATE_THREAD_INVITES_LIMITS_CHOICES
  143. )
  144. subscribe_to_started_threads = forms.TypedChoiceField(
  145. label=_("Started threads"),
  146. coerce=int,
  147. choices=AUTO_SUBSCRIBE_CHOICES
  148. )
  149. subscribe_to_replied_threads = forms.TypedChoiceField(
  150. label=_("Replid threads"),
  151. coerce=int,
  152. choices=AUTO_SUBSCRIBE_CHOICES
  153. )
  154. class Meta:
  155. model = get_user_model()
  156. fields = [
  157. 'username',
  158. 'email',
  159. 'title',
  160. 'is_avatar_locked',
  161. 'avatar_lock_user_message',
  162. 'avatar_lock_staff_message',
  163. 'signature',
  164. 'is_signature_locked',
  165. 'is_hiding_presence',
  166. 'limits_private_thread_invites_to',
  167. 'signature_lock_user_message',
  168. 'signature_lock_staff_message',
  169. 'subscribe_to_started_threads',
  170. 'subscribe_to_replied_threads',
  171. ]
  172. def clean_signature(self):
  173. data = self.cleaned_data['signature']
  174. length_limit = settings.signature_length_max
  175. if len(data) > length_limit:
  176. raise forms.ValidationError(ungettext(
  177. "Signature can't be longer than %(limit)s character.",
  178. "Signature can't be longer than %(limit)s characters.",
  179. length_limit
  180. ) % {'limit': length_limit})
  181. return data
  182. def UserFormFactory(FormType, instance):
  183. extra_fields = {}
  184. extra_fields['rank'] = forms.ModelChoiceField(
  185. label=_("Rank"),
  186. help_text=_(
  187. "Ranks are used to group and distinguish users. They are "
  188. "also used to add permissions to groups of users."
  189. ),
  190. queryset=Rank.objects.order_by('name'),
  191. initial=instance.rank
  192. )
  193. roles = Role.objects.order_by('name')
  194. extra_fields['roles'] = forms.ModelMultipleChoiceField(
  195. label=_("Roles"),
  196. help_text=_(
  197. 'Individual roles of this user. All users must have "member" role.'
  198. ),
  199. queryset=roles,
  200. initial=instance.roles.all() if instance.pk else None,
  201. widget=forms.CheckboxSelectMultiple
  202. )
  203. return type('UserFormFinal', (FormType,), extra_fields)
  204. def StaffFlagUserFormFactory(FormType, instance):
  205. staff_fields = {
  206. 'is_staff': YesNoSwitch(
  207. label=EditUserForm.IS_STAFF_LABEL,
  208. help_text=EditUserForm.IS_STAFF_HELP_TEXT,
  209. initial=instance.is_staff
  210. ),
  211. 'is_superuser': YesNoSwitch(
  212. label=EditUserForm.IS_SUPERUSER_LABEL,
  213. help_text=EditUserForm.IS_SUPERUSER_HELP_TEXT,
  214. initial=instance.is_superuser
  215. ),
  216. }
  217. return type('StaffUserForm', (FormType,), staff_fields)
  218. def UserIsActiveFormFactory(FormType, instance):
  219. is_active_fields = {
  220. 'is_active': YesNoSwitch(
  221. label=EditUserForm.IS_ACTIVE_LABEL,
  222. help_text=EditUserForm.IS_ACTIVE_HELP_TEXT,
  223. initial=instance.is_active
  224. ),
  225. 'is_active_staff_message': forms.CharField(
  226. label=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_LABEL,
  227. help_text=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT,
  228. initial=instance.is_active_staff_message,
  229. widget=forms.Textarea(attrs={'rows': 3}),
  230. required=False
  231. ),
  232. }
  233. return type('UserIsActiveForm', (FormType,), is_active_fields)
  234. def EditUserFormFactory(FormType, instance,
  235. add_is_active_fields=False, add_admin_fields=False):
  236. FormType = UserFormFactory(FormType, instance)
  237. if add_is_active_fields:
  238. FormType = UserIsActiveFormFactory(FormType, instance)
  239. if add_admin_fields:
  240. FormType = StaffFlagUserFormFactory(FormType, instance)
  241. return FormType
  242. class SearchUsersFormBase(forms.Form):
  243. username = forms.CharField(label=_("Username starts with"), required=False)
  244. email = forms.CharField(label=_("E-mail starts with"), required=False)
  245. inactive = YesNoSwitch(label=_("Inactive only"))
  246. disabled = YesNoSwitch(label=_("Disabled only"))
  247. is_staff = YesNoSwitch(label=_("Admins only"))
  248. def filter_queryset(self, criteria, queryset):
  249. if criteria.get('username'):
  250. queryset = queryset.filter(
  251. slug__startswith=criteria.get('username').lower())
  252. if criteria.get('email'):
  253. queryset = queryset.filter(
  254. email__istartswith=criteria.get('email'))
  255. if criteria.get('rank'):
  256. queryset = queryset.filter(rank_id=criteria.get('rank'))
  257. if criteria.get('role'):
  258. queryset = queryset.filter(roles__id=criteria.get('role'))
  259. if criteria.get('inactive'):
  260. queryset = queryset.filter(requires_activation__gt=0)
  261. if criteria.get('disabled'):
  262. queryset = queryset.filter(is_active=False)
  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 = 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 = 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