admin.py 17 KB

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