admin.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 misago.users.models import Ban, Rank
  12. from misago.users.profilefields import profilefields
  13. from misago.users.validators import validate_email, validate_username
  14. UserModel = get_user_model()
  15. class UserBaseForm(forms.ModelForm):
  16. username = forms.CharField(label=_("Username"))
  17. title = forms.CharField(label=_("Custom title"), required=False)
  18. email = forms.EmailField(label=_("E-mail address"))
  19. class Meta:
  20. model = UserModel
  21. fields = ['username', 'email', 'title']
  22. def clean_username(self):
  23. data = self.cleaned_data['username']
  24. validate_username(data, exclude=self.instance)
  25. return data
  26. def clean_email(self):
  27. data = self.cleaned_data['email']
  28. validate_email(data, exclude=self.instance)
  29. return data
  30. def clean_new_password(self):
  31. data = self.cleaned_data['new_password']
  32. if data:
  33. validate_password(data, user=self.instance)
  34. return data
  35. def clean_roles(self):
  36. data = self.cleaned_data['roles']
  37. for role in data:
  38. if role.special_role == 'authenticated':
  39. break
  40. else:
  41. message = _('All registered members must have "Member" role.')
  42. raise forms.ValidationError(message)
  43. return data
  44. class NewUserForm(UserBaseForm):
  45. new_password = forms.CharField(
  46. label=_("Password"),
  47. strip=False,
  48. widget=forms.PasswordInput,
  49. )
  50. class Meta:
  51. model = UserModel
  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. strip=False,
  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=_("Optional message to user explaining why his/hers signature is locked."),
  124. widget=forms.Textarea(attrs={'rows': 3}),
  125. required=False
  126. )
  127. signature_lock_staff_message = forms.CharField(
  128. label=_("Staff message"),
  129. help_text=_("Optional message to team members explaining why user signature is locked."),
  130. widget=forms.Textarea(attrs={'rows': 3}),
  131. required=False
  132. )
  133. is_hiding_presence = YesNoSwitch(label=_("Hides presence"))
  134. limits_private_thread_invites_to = forms.TypedChoiceField(
  135. label=_("Who can add user to private threads"),
  136. coerce=int,
  137. choices=UserModel.LIMIT_INVITES_TO_CHOICES
  138. )
  139. subscribe_to_started_threads = forms.TypedChoiceField(
  140. label=_("Started threads"), coerce=int, choices=UserModel.SUBSCRIBE_CHOICES
  141. )
  142. subscribe_to_replied_threads = forms.TypedChoiceField(
  143. label=_("Replid threads"), coerce=int, choices=UserModel.SUBSCRIBE_CHOICES
  144. )
  145. class Meta:
  146. model = UserModel
  147. fields = [
  148. 'username',
  149. 'email',
  150. 'title',
  151. 'is_avatar_locked',
  152. 'avatar_lock_user_message',
  153. 'avatar_lock_staff_message',
  154. 'signature',
  155. 'is_signature_locked',
  156. 'is_hiding_presence',
  157. 'limits_private_thread_invites_to',
  158. 'signature_lock_user_message',
  159. 'signature_lock_staff_message',
  160. 'subscribe_to_started_threads',
  161. 'subscribe_to_replied_threads',
  162. ]
  163. def __init__(self, *args, **kwargs):
  164. self.request = kwargs.pop('request')
  165. super(EditUserForm, self).__init__(*args, **kwargs)
  166. profilefields.add_fields_to_admin_form(self.request, self.instance, self)
  167. def get_profile_fields_groups(self):
  168. profile_fields_groups = []
  169. for group in self._profile_fields_groups:
  170. fields_group = {
  171. 'name': group['name'],
  172. 'fields': [],
  173. }
  174. for fieldname in group['fields']:
  175. fields_group['fields'].append(self[fieldname])
  176. profile_fields_groups.append(fields_group)
  177. return profile_fields_groups
  178. def clean_signature(self):
  179. data = self.cleaned_data['signature']
  180. length_limit = settings.signature_length_max
  181. if len(data) > length_limit:
  182. raise forms.ValidationError(
  183. ungettext(
  184. "Signature can't be longer than %(limit)s character.",
  185. "Signature can't be longer than %(limit)s characters.",
  186. length_limit,
  187. ) % {'limit': length_limit}
  188. )
  189. return data
  190. def clean(self):
  191. data = super(EditUserForm, self).clean()
  192. return profilefields.clean_form(self.request, self.instance, self, data)
  193. def UserFormFactory(FormType, instance):
  194. extra_fields = {}
  195. extra_fields['rank'] = forms.ModelChoiceField(
  196. label=_("Rank"),
  197. help_text=_(
  198. "Ranks are used to group and distinguish users. They are "
  199. "also used to add permissions to groups of users."
  200. ),
  201. queryset=Rank.objects.order_by('name'),
  202. initial=instance.rank
  203. )
  204. roles = Role.objects.order_by('name')
  205. extra_fields['roles'] = forms.ModelMultipleChoiceField(
  206. label=_("Roles"),
  207. help_text=_('Individual roles of this user. All users must have "member" role.'),
  208. queryset=roles,
  209. initial=instance.roles.all() if instance.pk else None,
  210. widget=forms.CheckboxSelectMultiple
  211. )
  212. return type('UserFormFinal', (FormType, ), extra_fields)
  213. def StaffFlagUserFormFactory(FormType, instance):
  214. staff_fields = {
  215. 'is_staff': YesNoSwitch(
  216. label=EditUserForm.IS_STAFF_LABEL,
  217. help_text=EditUserForm.IS_STAFF_HELP_TEXT,
  218. initial=instance.is_staff
  219. ),
  220. 'is_superuser': YesNoSwitch(
  221. label=EditUserForm.IS_SUPERUSER_LABEL,
  222. help_text=EditUserForm.IS_SUPERUSER_HELP_TEXT,
  223. initial=instance.is_superuser
  224. ),
  225. }
  226. return type('StaffUserForm', (FormType, ), staff_fields)
  227. def UserIsActiveFormFactory(FormType, instance):
  228. is_active_fields = {
  229. 'is_active': YesNoSwitch(
  230. label=EditUserForm.IS_ACTIVE_LABEL,
  231. help_text=EditUserForm.IS_ACTIVE_HELP_TEXT,
  232. initial=instance.is_active
  233. ),
  234. 'is_active_staff_message': forms.CharField(
  235. label=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_LABEL,
  236. help_text=EditUserForm.IS_ACTIVE_STAFF_MESSAGE_HELP_TEXT,
  237. initial=instance.is_active_staff_message,
  238. widget=forms.Textarea(attrs={'rows': 3}),
  239. required=False
  240. ),
  241. }
  242. return type('UserIsActiveForm', (FormType, ), is_active_fields)
  243. def EditUserFormFactory(FormType, instance, add_is_active_fields=False, add_admin_fields=False):
  244. FormType = UserFormFactory(FormType, instance)
  245. if add_is_active_fields:
  246. FormType = UserIsActiveFormFactory(FormType, instance)
  247. if add_admin_fields:
  248. FormType = StaffFlagUserFormFactory(FormType, instance)
  249. return FormType
  250. class SearchUsersFormBase(forms.Form):
  251. username = forms.CharField(label=_("Username starts with"), required=False)
  252. email = forms.CharField(label=_("E-mail starts with"), required=False)
  253. profilefields = forms.CharField(label=_("Profile fields contain"), required=False)
  254. inactive = YesNoSwitch(label=_("Inactive only"))
  255. disabled = YesNoSwitch(label=_("Disabled only"))
  256. is_staff = YesNoSwitch(label=_("Admins only"))
  257. def filter_queryset(self, criteria, queryset):
  258. if criteria.get('username'):
  259. queryset = queryset.filter(slug__startswith=criteria.get('username').lower())
  260. if criteria.get('email'):
  261. queryset = queryset.filter(email__istartswith=criteria.get('email'))
  262. if criteria.get('rank'):
  263. queryset = queryset.filter(rank_id=criteria.get('rank'))
  264. if criteria.get('role'):
  265. queryset = queryset.filter(roles__id=criteria.get('role'))
  266. if criteria.get('inactive'):
  267. queryset = queryset.filter(requires_activation__gt=0)
  268. if criteria.get('disabled'):
  269. queryset = queryset.filter(is_active=False)
  270. if criteria.get('is_staff'):
  271. queryset = queryset.filter(is_staff=True)
  272. if criteria.get('profilefields', '').strip():
  273. queryset = profilefields.search_users(
  274. criteria.get('profilefields').strip(), queryset)
  275. return queryset
  276. def SearchUsersForm(*args, **kwargs):
  277. """
  278. Factory that uses cache for ranks and roles,
  279. and makes those ranks and roles typed choice fields that play nice
  280. with passing values via GET
  281. """
  282. ranks_choices = threadstore.get('misago_admin_ranks_choices', 'nada')
  283. if ranks_choices == 'nada':
  284. ranks_choices = [('', _("All ranks"))]
  285. for rank in Rank.objects.order_by('name').iterator():
  286. ranks_choices.append((rank.pk, rank.name))
  287. threadstore.set('misago_admin_ranks_choices', ranks_choices)
  288. roles_choices = threadstore.get('misago_admin_roles_choices', 'nada')
  289. if roles_choices == 'nada':
  290. roles_choices = [('', _("All roles"))]
  291. for role in Role.objects.order_by('name').iterator():
  292. roles_choices.append((role.pk, role.name))
  293. threadstore.set('misago_admin_roles_choices', roles_choices)
  294. extra_fields = {
  295. 'rank': forms.TypedChoiceField(
  296. label=_("Has rank"),
  297. coerce=int,
  298. required=False,
  299. choices=ranks_choices,
  300. ),
  301. 'role': forms.TypedChoiceField(
  302. label=_("Has role"),
  303. coerce=int,
  304. required=False,
  305. choices=roles_choices,
  306. )
  307. }
  308. FinalForm = type('SearchUsersFormFinal', (SearchUsersFormBase, ), extra_fields)
  309. return FinalForm(*args, **kwargs)
  310. class RankForm(forms.ModelForm):
  311. name = forms.CharField(
  312. label=_("Name"),
  313. validators=[validate_sluggable()],
  314. help_text=_(
  315. 'Short and descriptive name of all users with this rank. '
  316. '"The Team" or "Game Masters" are good examples.'
  317. )
  318. )
  319. title = forms.CharField(
  320. label=_("User title"),
  321. required=False,
  322. help_text=_(
  323. 'Optional, singular version of rank name displayed by user names. '
  324. 'For example "GM" or "Dev".'
  325. )
  326. )
  327. description = forms.CharField(
  328. label=_("Description"),
  329. max_length=2048,
  330. required=False,
  331. widget=forms.Textarea(attrs={'rows': 3}),
  332. help_text=_(
  333. "Optional description explaining function or status of "
  334. "members distincted with this rank."
  335. )
  336. )
  337. roles = forms.ModelMultipleChoiceField(
  338. label=_("User roles"),
  339. widget=forms.CheckboxSelectMultiple,
  340. queryset=Role.objects.order_by('name'),
  341. required=False,
  342. help_text=_("Rank can give additional roles to users with it.")
  343. )
  344. css_class = forms.CharField(
  345. label=_("CSS class"),
  346. required=False,
  347. help_text=_("Optional css class added to content belonging to this rank owner.")
  348. )
  349. is_tab = forms.BooleanField(
  350. label=_("Give rank dedicated tab on users list"),
  351. required=False,
  352. help_text=_(
  353. "Selecting this option will make users with this rank easily discoverable "
  354. "by others through dedicated page on forum users list."
  355. )
  356. )
  357. class Meta:
  358. model = Rank
  359. fields = [
  360. 'name',
  361. 'description',
  362. 'css_class',
  363. 'title',
  364. 'roles',
  365. 'is_tab',
  366. ]
  367. def clean_name(self):
  368. data = self.cleaned_data['name']
  369. self.instance.set_name(data)
  370. unique_qs = Rank.objects.filter(slug=self.instance.slug)
  371. if self.instance.pk:
  372. unique_qs = unique_qs.exclude(pk=self.instance.pk)
  373. if unique_qs.exists():
  374. raise forms.ValidationError(_("This name collides with other rank."))
  375. return data
  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. registration_only = YesNoSwitch(
  421. label=_("Restrict this ban to registrations"),
  422. help_text=_(
  423. "Changing this to yes will make this ban check be only performed on registration "
  424. "step. This is good if you want to block certain registrations like ones from "
  425. "recently comprimised e-mail providers, without harming existing users."
  426. ),
  427. )
  428. banned_value = forms.CharField(
  429. label=_("Banned value"),
  430. max_length=250,
  431. help_text=_(
  432. 'This value is case-insensitive and accepts asterisk (*) '
  433. 'for rought matches. For example, making IP ban for value '
  434. '"83.*" will ban all IP addresses beginning with "83.".'
  435. ),
  436. error_messages={
  437. 'max_length': _("Banned value can't be longer than 250 characters."),
  438. }
  439. )
  440. user_message = forms.CharField(
  441. label=_("User message"),
  442. required=False,
  443. max_length=1000,
  444. help_text=_("Optional message displayed to user instead of default one."),
  445. widget=forms.Textarea(attrs={'rows': 3}),
  446. error_messages={
  447. 'max_length': _("Message can't be longer than 1000 characters."),
  448. }
  449. )
  450. staff_message = forms.CharField(
  451. label=_("Team message"),
  452. required=False,
  453. max_length=1000,
  454. help_text=_("Optional ban message for moderators and administrators."),
  455. widget=forms.Textarea(attrs={'rows': 3}),
  456. error_messages={
  457. 'max_length': _("Message can't be longer than 1000 characters."),
  458. }
  459. )
  460. expires_on = IsoDateTimeField(
  461. label=_("Expires on"),
  462. required=False,
  463. help_text=_("Leave this field empty for this ban to never expire.")
  464. )
  465. class Meta:
  466. model = Ban
  467. fields = [
  468. 'check_type',
  469. 'registration_only',
  470. 'banned_value',
  471. 'user_message',
  472. 'staff_message',
  473. 'expires_on',
  474. ]
  475. def clean_banned_value(self):
  476. data = self.cleaned_data['banned_value']
  477. while '**' in data:
  478. data = data.replace('**', '*')
  479. if data == '*':
  480. raise forms.ValidationError(_("Banned value is too vague."))
  481. return data
  482. class SearchBansForm(forms.Form):
  483. check_type = forms.ChoiceField(
  484. label=_("Type"),
  485. required=False,
  486. choices=[
  487. ('', _('All bans')),
  488. ('names', _('Usernames')),
  489. ('emails', _('E-mails')),
  490. ('ips', _('IPs')),
  491. ],
  492. )
  493. value = forms.CharField(label=_("Banned value begins with"), required=False)
  494. registration_only = forms.ChoiceField(
  495. label=_("Registration only"),
  496. required=False,
  497. choices=[
  498. ('', _('Any')),
  499. ('only', _('Yes')),
  500. ('exclude', _('No')),
  501. ]
  502. )
  503. state = forms.ChoiceField(
  504. label=_("State"),
  505. required=False,
  506. choices=[
  507. ('', _('Any')),
  508. ('used', _('Active')),
  509. ('unused', _('Expired')),
  510. ]
  511. )
  512. def filter_queryset(self, search_criteria, queryset):
  513. criteria = search_criteria
  514. if criteria.get('check_type') == 'names':
  515. queryset = queryset.filter(check_type=0)
  516. if criteria.get('check_type') == 'emails':
  517. queryset = queryset.filter(check_type=1)
  518. if criteria.get('check_type') == 'ips':
  519. queryset = queryset.filter(check_type=2)
  520. if criteria.get('value'):
  521. queryset = queryset.filter(banned_value__startswith=criteria.get('value').lower())
  522. if criteria.get('state') == 'used':
  523. queryset = queryset.filter(is_checked=True)
  524. if criteria.get('state') == 'unused':
  525. queryset = queryset.filter(is_checked=False)
  526. if criteria.get('registration_only') == 'only':
  527. queryset = queryset.filter(registration_only=True)
  528. if criteria.get('registration_only') == 'exclude':
  529. queryset = queryset.filter(registration_only=False)
  530. return queryset