admin.py 19 KB

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