admin.py 18 KB

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