admin.py 18 KB

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