admin.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. from django.contrib.auth import get_user_model
  2. from django.utils.translation import ugettext_lazy as _
  3. from misago.core import forms, threadstore
  4. from misago.core.validators import validate_sluggable
  5. from misago.acl.models import Role
  6. from misago.users.models import (BANS_CHOICES, RESTRICTIONS_CHOICES,
  7. Ban, Rank, WarningLevel)
  8. from misago.users.validators import (validate_username, validate_email,
  9. validate_password)
  10. """
  11. Users
  12. """
  13. class UserBaseForm(forms.ModelForm):
  14. username = forms.CharField(
  15. label=_("Username"))
  16. title = forms.CharField(
  17. label=_("Custom title"), required=False)
  18. email = forms.EmailField(
  19. label=_("E-mail address"))
  20. class Meta:
  21. model = get_user_model()
  22. fields = ['username', 'email', 'title']
  23. def clean_username(self):
  24. data = self.cleaned_data['username']
  25. validate_username(data, exclude=self.instance)
  26. return data
  27. def clean_email(self):
  28. data = self.cleaned_data['email']
  29. validate_email(data, exclude=self.instance)
  30. return data
  31. def clean_new_password(self):
  32. data = self.cleaned_data['new_password']
  33. if data:
  34. validate_password(data)
  35. return data
  36. def clean_roles(self):
  37. data = self.cleaned_data['roles']
  38. for role in data:
  39. if role.special_role == 'authenticated':
  40. break
  41. else:
  42. message = _('All registered members must have "Member" role.')
  43. raise forms.ValidationError(message)
  44. return data
  45. class NewUserForm(UserBaseForm):
  46. new_password = forms.CharField(
  47. label=_("Password"), widget=forms.PasswordInput)
  48. class Meta:
  49. model = get_user_model()
  50. fields = ['username', 'email', 'title']
  51. class EditUserForm(UserBaseForm):
  52. new_password = forms.CharField(
  53. label=_("Change password to"),
  54. widget=forms.PasswordInput,
  55. required=False)
  56. class Meta:
  57. model = get_user_model()
  58. fields = ['username', 'email', 'title']
  59. def UserFormFactory(FormType, instance):
  60. extra_fields = {}
  61. extra_fields['rank'] = forms.ModelChoiceField(
  62. label=_("Rank"),
  63. help_text=_("Ranks are used to group and distinguish users. "
  64. "They are also used to add permissions to groups of "
  65. "users."),
  66. queryset=Rank.objects.order_by('name'),
  67. initial=instance.rank)
  68. roles = Role.objects.order_by('name')
  69. extra_fields['roles'] = forms.ModelMultipleChoiceField(
  70. label=_("Roles"),
  71. help_text=_('Individual roles of this user. '
  72. 'All users must have "member" role.'),
  73. queryset=roles,
  74. initial=instance.roles.all() if instance.pk else None,
  75. widget=forms.CheckboxSelectMultiple)
  76. return type('UserFormFinal', (FormType,), extra_fields)
  77. def StaffFlagUserFormFactory(FormType, instance, add_staff_field):
  78. FormType = UserFormFactory(FormType, instance)
  79. if add_staff_field:
  80. staff_levels = (
  81. (0, _("No access")),
  82. (1, _("Administrator")),
  83. (2, _("Superadmin")),
  84. )
  85. staff_fields = {
  86. 'staff_level': forms.TypedChoiceField(
  87. label=_("Admin level"),
  88. help_text=_('Only administrators can access admin sites. '
  89. 'In addition to admin site access, superadmins '
  90. 'can also change other members admin levels.'),
  91. coerce=int,
  92. choices=staff_levels,
  93. initial=instance.staff_level),
  94. }
  95. return type('StaffUserForm', (FormType,), staff_fields)
  96. else:
  97. return FormType
  98. class SearchUsersFormBase(forms.Form):
  99. username = forms.CharField(label=_("Username starts with"), required=False)
  100. email = forms.CharField(label=_("E-mail starts with"), required=False)
  101. inactive = forms.YesNoSwitch(label=_("Inactive only"))
  102. is_staff = forms.YesNoSwitch(label=_("Admins only"))
  103. def filter_queryset(self, search_criteria, queryset):
  104. criteria = search_criteria
  105. if criteria.get('username'):
  106. queryset = queryset.filter(
  107. username_slug__startswith=criteria.get('username').lower())
  108. if criteria.get('email'):
  109. queryset = queryset.filter(
  110. email__istartswith=criteria.get('email'))
  111. if criteria.get('rank'):
  112. queryset = queryset.filter(
  113. rank_id=criteria.get('rank'))
  114. if criteria.get('role'):
  115. queryset = queryset.filter(
  116. roles__id=criteria.get('role'))
  117. if criteria.get('inactive'):
  118. queryset = queryset.filter(requires_activation__gt=0)
  119. if criteria.get('is_staff'):
  120. queryset = queryset.filter(is_staff=True)
  121. return queryset
  122. def SearchUsersForm(*args, **kwargs):
  123. """
  124. Factory that uses cache for ranks and roles,
  125. and makes those ranks and roles typed choice fields that play nice
  126. with passing values via GET
  127. """
  128. ranks_choices = threadstore.get('misago_admin_ranks_choices', 'nada')
  129. if ranks_choices == 'nada':
  130. ranks_choices = [('', _("All ranks"))]
  131. for rank in Rank.objects.order_by('name').iterator():
  132. ranks_choices.append((rank.pk, rank.name))
  133. threadstore.set('misago_admin_ranks_choices', ranks_choices)
  134. roles_choices = threadstore.get('misago_admin_roles_choices', 'nada')
  135. if roles_choices == 'nada':
  136. roles_choices = [('', _("All roles"))]
  137. for role in Role.objects.order_by('name').iterator():
  138. roles_choices.append((role.pk, role.name))
  139. threadstore.set('misago_admin_roles_choices', roles_choices)
  140. extra_fields = {
  141. 'rank': forms.TypedChoiceField(label=_("Has rank"),
  142. coerce=int,
  143. required=False,
  144. choices=ranks_choices),
  145. 'role': forms.TypedChoiceField(label=_("Has role"),
  146. coerce=int,
  147. required=False,
  148. choices=roles_choices)
  149. }
  150. FinalForm = type('SearchUsersFormFinal',
  151. (SearchUsersFormBase,),
  152. extra_fields)
  153. return FinalForm(*args, **kwargs)
  154. """
  155. Ranks
  156. """
  157. class RankForm(forms.ModelForm):
  158. name = forms.CharField(
  159. label=_("Name"),
  160. validators=[validate_sluggable()],
  161. help_text=_('Short and descriptive name of all users with this rank. '
  162. '"The Team" or "Game Masters" are good examples.'))
  163. title = forms.CharField(
  164. label=_("User title"), required=False,
  165. help_text=_('Optional, singular version of rank name displayed by '
  166. 'user names. For example "GM" or "Dev".'))
  167. description = forms.CharField(
  168. label=_("Description"), max_length=2048, required=False,
  169. widget=forms.Textarea(attrs={'rows': 3}),
  170. help_text=_("Optional description explaining function or status of "
  171. "members distincted with this rank."))
  172. roles = forms.ModelMultipleChoiceField(
  173. label=_("User roles"), queryset=Role.objects.order_by('name'),
  174. required=False, widget=forms.CheckboxSelectMultiple,
  175. help_text=_('Rank can give additional roles to users with it.'))
  176. css_class = forms.CharField(
  177. label=_("CSS class"), required=False,
  178. help_text=_("Optional css class added to content belonging to this "
  179. "rank owner."))
  180. is_tab = forms.BooleanField(
  181. label=_("Give rank dedicated tab on users list"), required=False,
  182. help_text=_("Selecting this option will make users with this rank "
  183. "easily discoverable by others trough dedicated page on "
  184. "forum users list."))
  185. is_on_index = forms.BooleanField(
  186. label=_("Show users online on forum index"), required=False,
  187. help_text=_("Selecting this option will make forum inform other "
  188. "users of their availability by displaying them on forum "
  189. "index page."))
  190. class Meta:
  191. model = Rank
  192. fields = [
  193. 'name',
  194. 'description',
  195. 'css_class',
  196. 'title',
  197. 'roles',
  198. 'is_tab',
  199. 'is_on_index',
  200. ]
  201. def clean(self):
  202. data = super(RankForm, self).clean()
  203. self.instance.set_name(data.get('name'))
  204. return data
  205. """
  206. Bans
  207. """
  208. class BanForm(forms.ModelForm):
  209. test = forms.TypedChoiceField(
  210. label=_("Ban type"),
  211. coerce=int,
  212. choices=BANS_CHOICES)
  213. banned_value = forms.CharField(
  214. label=_("Banned value"), max_length=250,
  215. help_text=_('This value is case-insensitive and accepts asterisk (*) '
  216. 'for rought matches. For example, making IP ban for value '
  217. '"83.*" will ban all IP addresses beginning with "83.".'),
  218. error_messages={
  219. 'max_length': _("Banned value can't be longer than 250 characters.")
  220. })
  221. user_message = forms.CharField(
  222. label=_("User message"), required=False, max_length=1000,
  223. help_text=_("Optional message displayed instead of default one."),
  224. widget=forms.Textarea(attrs={'rows': 3}),
  225. error_messages={
  226. 'max_length': _("Message can't be longer than 1000 characters.")
  227. })
  228. staff_message = forms.CharField(
  229. label=_("Team message"), required=False, max_length=1000,
  230. help_text=_("Optional ban message for moderators and administrators."),
  231. widget=forms.Textarea(attrs={'rows': 3}),
  232. error_messages={
  233. 'max_length': _("Message can't be longer than 1000 characters.")
  234. })
  235. valid_until = forms.DateField(
  236. label=_("Expiration date"),
  237. required=False, input_formats=['%m-%d-%Y'],
  238. widget=forms.DateInput(
  239. format='%m-%d-%Y', attrs={'data-date-format': 'MM-DD-YYYY'}),
  240. help_text=_('Leave this field empty for this ban to never expire.'))
  241. class Meta:
  242. model = Ban
  243. fields = [
  244. 'test',
  245. 'banned_value',
  246. 'user_message',
  247. 'staff_message',
  248. 'valid_until',
  249. ]
  250. def clean_banned_value(self):
  251. data = self.cleaned_data['banned_value']
  252. while '**' in data:
  253. data = data.replace('**', '*')
  254. if data == '*':
  255. raise forms.ValidationError(_("Banned value is too vague."))
  256. return data
  257. SARCH_BANS_CHOICES = (
  258. ('', _('All bans')),
  259. ('names', _('Usernames')),
  260. ('emails', _('E-mails')),
  261. ('ips', _('IPs')),
  262. )
  263. class SearchBansForm(forms.Form):
  264. test = forms.ChoiceField(
  265. label=_("Type"), required=False,
  266. choices=SARCH_BANS_CHOICES)
  267. value = forms.CharField(
  268. label=_("Banned value begins with"),
  269. required=False)
  270. state = forms.ChoiceField(
  271. label=_("State"), required=False,
  272. choices=(
  273. ('', _('All states')),
  274. ('valid', _('Valid bans')),
  275. ('expired', _('Expired bans')),
  276. ))
  277. def filter_queryset(self, search_criteria, queryset):
  278. criteria = search_criteria
  279. if criteria.get('test') == 'names':
  280. queryset = queryset.filter(test=0)
  281. if criteria.get('test') == 'emails':
  282. queryset = queryset.filter(test=1)
  283. if criteria.get('test') == 'ips':
  284. queryset = queryset.filter(test=2)
  285. if criteria.get('value'):
  286. queryset = queryset.filter(
  287. banned_value__startswith=criteria.get('value').lower())
  288. if criteria.get('state') == 'valid':
  289. queryset = queryset.filter(is_valid=True)
  290. if criteria.get('state') == 'expired':
  291. queryset = queryset.filter(is_valid=False)
  292. return queryset
  293. """
  294. Warning levels
  295. """
  296. class WarningLevelForm(forms.ModelForm):
  297. name = forms.CharField(label=_("Level name"), max_length=255)
  298. description = forms.CharField(
  299. label=_("Description"), required=False, max_length=1000,
  300. help_text=_("Optional message description displayed to users with "
  301. "this warning level."),
  302. widget=forms.Textarea(attrs={'rows': 3}),
  303. error_messages={
  304. 'max_length': _("Description can't be longer "
  305. "than 1000 characters.")
  306. })
  307. length_in_minutes = forms.IntegerField(
  308. label=_("Length in minutes"), min_value=0,
  309. help_text=_("Enter number of minutes since this warning level was "
  310. "imposed on member until it's reduced, or 0 to make "
  311. "this warning level permanent."))
  312. restricts_posting_replies = forms.TypedChoiceField(
  313. label=_("Posting replies"),
  314. coerce=int, choices=RESTRICTIONS_CHOICES)
  315. restricts_posting_threads = forms.TypedChoiceField(
  316. label=_("Posting threads"),
  317. coerce=int, choices=RESTRICTIONS_CHOICES)
  318. class Meta:
  319. model = WarningLevel
  320. fields = [
  321. 'name',
  322. 'description',
  323. 'length_in_minutes',
  324. 'restricts_posting_replies',
  325. 'restricts_posting_threads',
  326. ]