admin.py 17 KB

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