admin.py 18 KB

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