admin.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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, criteria, queryset):
  198. if criteria.get('username'):
  199. queryset = queryset.filter(
  200. slug__startswith=criteria.get('username').lower())
  201. if criteria.get('email'):
  202. queryset = queryset.filter(
  203. email__istartswith=criteria.get('email'))
  204. if criteria.get('rank'):
  205. queryset = queryset.filter(rank_id=criteria.get('rank'))
  206. if criteria.get('role'):
  207. queryset = queryset.filter(roles__id=criteria.get('role'))
  208. if criteria.get('inactive'):
  209. queryset = queryset.filter(requires_activation__gt=0)
  210. if criteria.get('is_staff'):
  211. queryset = queryset.filter(is_staff=True)
  212. return queryset
  213. def SearchUsersForm(*args, **kwargs):
  214. """
  215. Factory that uses cache for ranks and roles,
  216. and makes those ranks and roles typed choice fields that play nice
  217. with passing values via GET
  218. """
  219. ranks_choices = threadstore.get('misago_admin_ranks_choices', 'nada')
  220. if ranks_choices == 'nada':
  221. ranks_choices = [('', _("All ranks"))]
  222. for rank in Rank.objects.order_by('name').iterator():
  223. ranks_choices.append((rank.pk, rank.name))
  224. threadstore.set('misago_admin_ranks_choices', ranks_choices)
  225. roles_choices = threadstore.get('misago_admin_roles_choices', 'nada')
  226. if roles_choices == 'nada':
  227. roles_choices = [('', _("All roles"))]
  228. for role in Role.objects.order_by('name').iterator():
  229. roles_choices.append((role.pk, role.name))
  230. threadstore.set('misago_admin_roles_choices', roles_choices)
  231. extra_fields = {
  232. 'rank': forms.TypedChoiceField(
  233. label=_("Has rank"),
  234. coerce=int,
  235. required=False,
  236. choices=ranks_choices
  237. ),
  238. 'role': forms.TypedChoiceField(
  239. label=_("Has role"),
  240. coerce=int,
  241. required=False,
  242. choices=roles_choices
  243. )
  244. }
  245. FinalForm = type(
  246. 'SearchUsersFormFinal', (SearchUsersFormBase,), extra_fields)
  247. return FinalForm(*args, **kwargs)
  248. """
  249. Ranks
  250. """
  251. class RankForm(forms.ModelForm):
  252. name = forms.CharField(
  253. label=_("Name"),
  254. validators=[validate_sluggable()],
  255. help_text=_('Short and descriptive name of all users with this rank. '
  256. '"The Team" or "Game Masters" are good examples.')
  257. )
  258. title = forms.CharField(
  259. label=_("User title"),
  260. required=False,
  261. help_text=_('Optional, singular version of rank name displayed by '
  262. 'user names. For example "GM" or "Dev".')
  263. )
  264. description = forms.CharField(
  265. label=_("Description"),
  266. max_length=2048,
  267. required=False,
  268. widget=forms.Textarea(attrs={'rows': 3}),
  269. help_text=_("Optional description explaining function or status of "
  270. "members distincted with this rank.")
  271. )
  272. roles = forms.ModelMultipleChoiceField(
  273. label=_("User roles"),
  274. widget=forms.CheckboxSelectMultiple,
  275. queryset=Role.objects.order_by('name'),
  276. required=False,
  277. help_text=_('Rank can give additional roles to users with it.')
  278. )
  279. css_class = forms.CharField(
  280. label=_("CSS class"),
  281. required=False,
  282. help_text=_("Optional css class added to content belonging to this "
  283. "rank owner.")
  284. )
  285. is_tab = forms.BooleanField(
  286. label=_("Give rank dedicated tab on users list"),
  287. required=False,
  288. help_text=_("Selecting this option will make users with this rank "
  289. "easily discoverable by others trough dedicated page on "
  290. "forum users list.")
  291. )
  292. class Meta:
  293. model = Rank
  294. fields = [
  295. 'name',
  296. 'description',
  297. 'css_class',
  298. 'title',
  299. 'roles',
  300. 'is_tab',
  301. ]
  302. def clean_name(self):
  303. data = self.cleaned_data['name']
  304. self.instance.set_name(data)
  305. unique_qs = Rank.objects.filter(slug=self.instance.slug)
  306. if self.instance.pk:
  307. unique_qs = unique_qs.exclude(pk=self.instance.pk)
  308. if unique_qs.exists():
  309. raise forms.ValidationError(
  310. _("This name collides with other rank."))
  311. return data
  312. """
  313. Bans
  314. """
  315. class BanUsersForm(forms.Form):
  316. ban_type = forms.MultipleChoiceField(
  317. label=_("Values to ban"),
  318. widget=forms.CheckboxSelectMultiple,
  319. choices=(
  320. ('usernames', _('Usernames')),
  321. ('emails', _('E-mails')),
  322. ('domains', _('E-mail domains')),
  323. ('ip', _('IP addresses')),
  324. ('ip_first', _('First segment of IP addresses')),
  325. ('ip_two', _('First two segments of IP addresses'))
  326. )
  327. )
  328. user_message = forms.CharField(
  329. label=_("User message"),
  330. required=False,
  331. max_length=1000,
  332. help_text=_("Optional message displayed to users "
  333. "instead of default one."),
  334. widget=forms.Textarea(attrs={'rows': 3}),
  335. error_messages={
  336. 'max_length': _("Message can't be longer than 1000 characters.")
  337. }
  338. )
  339. staff_message = forms.CharField(
  340. label=_("Team message"),
  341. required=False,
  342. max_length=1000,
  343. help_text=_("Optional ban message for moderators and administrators."),
  344. widget=forms.Textarea(attrs={'rows': 3}),
  345. error_messages={
  346. 'max_length': _("Message can't be longer than 1000 characters.")
  347. }
  348. )
  349. expires_on = forms.IsoDateTimeField(
  350. label=_("Expires on"),
  351. required=False,
  352. help_text=_('Leave this field empty for set bans to never expire.')
  353. )
  354. class BanForm(forms.ModelForm):
  355. check_type = forms.TypedChoiceField(
  356. label=_("Check type"),
  357. coerce=int,
  358. choices=BANS_CHOICES
  359. )
  360. banned_value = forms.CharField(
  361. label=_("Banned value"),
  362. max_length=250,
  363. help_text=_('This value is case-insensitive and accepts asterisk (*) '
  364. 'for rought matches. For example, making IP ban for value '
  365. '"83.*" will ban all IP addresses beginning with "83.".'),
  366. error_messages={
  367. 'max_length': _("Banned value can't be longer "
  368. "than 250 characters.")
  369. }
  370. )
  371. user_message = forms.CharField(
  372. label=_("User message"),
  373. required=False,
  374. max_length=1000,
  375. help_text=_("Optional message displayed to user "
  376. "instead of default one."),
  377. widget=forms.Textarea(attrs={'rows': 3}),
  378. error_messages={
  379. 'max_length': _("Message can't be longer than 1000 characters.")
  380. }
  381. )
  382. staff_message = forms.CharField(
  383. label=_("Team message"),
  384. required=False,
  385. max_length=1000,
  386. help_text=_("Optional ban message for moderators and administrators."),
  387. widget=forms.Textarea(attrs={'rows': 3}),
  388. error_messages={
  389. 'max_length': _("Message can't be longer than 1000 characters.")
  390. }
  391. )
  392. expires_on = forms.IsoDateTimeField(
  393. label=_("Expires on"),
  394. required=False,
  395. help_text=_('Leave this field empty for this ban to never expire.')
  396. )
  397. class Meta:
  398. model = Ban
  399. fields = [
  400. 'check_type',
  401. 'banned_value',
  402. 'user_message',
  403. 'staff_message',
  404. 'expires_on',
  405. ]
  406. def clean_banned_value(self):
  407. data = self.cleaned_data['banned_value']
  408. while '**' in data:
  409. data = data.replace('**', '*')
  410. if data == '*':
  411. raise forms.ValidationError(_("Banned value is too vague."))
  412. return data
  413. SARCH_BANS_CHOICES = (
  414. ('', _('All bans')),
  415. ('names', _('Usernames')),
  416. ('emails', _('E-mails')),
  417. ('ips', _('IPs')),
  418. )
  419. class SearchBansForm(forms.Form):
  420. check_type = forms.ChoiceField(
  421. label=_("Type"),
  422. required=False,
  423. choices=SARCH_BANS_CHOICES
  424. )
  425. value = forms.CharField(
  426. label=_("Banned value begins with"),
  427. required=False
  428. )
  429. state = forms.ChoiceField(
  430. label=_("State"),
  431. required=False,
  432. choices=(
  433. ('', _('Any')),
  434. ('used', _('Active')),
  435. ('unused', _('Expired')),
  436. )
  437. )
  438. def filter_queryset(self, search_criteria, queryset):
  439. criteria = search_criteria
  440. if criteria.get('check_type') == 'names':
  441. queryset = queryset.filter(check_type=0)
  442. if criteria.get('check_type') == 'emails':
  443. queryset = queryset.filter(check_type=1)
  444. if criteria.get('check_type') == 'ips':
  445. queryset = queryset.filter(check_type=2)
  446. if criteria.get('value'):
  447. queryset = queryset.filter(
  448. banned_value__startswith=criteria.get('value').lower())
  449. if criteria.get('state') == 'used':
  450. queryset = queryset.filter(is_checked=True)
  451. if criteria.get('state') == 'unused':
  452. queryset = queryset.filter(is_checked=False)
  453. return queryset
  454. """
  455. Warning levels
  456. """
  457. class WarningLevelForm(forms.ModelForm):
  458. name = forms.CharField(label=_("Level name"), max_length=255)
  459. length_in_minutes = forms.IntegerField(
  460. label=_("Length in minutes"),
  461. min_value=0,
  462. help_text=_("Enter number of minutes since this warning level was "
  463. "imposed on member until it's reduced, or 0 to make "
  464. "this warning level permanent.")
  465. )
  466. restricts_posting_replies = forms.TypedChoiceField(
  467. label=_("Posting replies"),
  468. coerce=int,
  469. choices=RESTRICTIONS_CHOICES
  470. )
  471. restricts_posting_threads = forms.TypedChoiceField(
  472. label=_("Posting threads"),
  473. coerce=int,
  474. choices=RESTRICTIONS_CHOICES
  475. )
  476. class Meta:
  477. model = WarningLevel
  478. fields = [
  479. 'name',
  480. 'length_in_minutes',
  481. 'restricts_posting_replies',
  482. 'restricts_posting_threads',
  483. ]