admin.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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, Ban, Rank
  7. from misago.users.validators import (validate_username, validate_email,
  8. validate_password)
  9. """
  10. Users forms
  11. """
  12. class UserBaseForm(forms.ModelForm):
  13. username = forms.CharField(
  14. label=_("Username"))
  15. title = forms.CharField(
  16. label=_("Custom title"),
  17. 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)
  26. return data
  27. def clean_email(self):
  28. data = self.cleaned_data['email']
  29. validate_email(data)
  30. return data
  31. def clean_new_password(self):
  32. data = self.cleaned_data['new_password']
  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. class Meta:
  49. model = get_user_model()
  50. fields = ['username', 'email', 'title']
  51. class EditUserForm(forms.ModelForm):
  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. ranks = Rank.objects.order_by('name')
  62. if ranks.exists():
  63. extra_fields['rank'] = forms.ModelChoiceField(
  64. label=_("Rank"),
  65. help_text=_("Ranks are used to group and distinguish users. "
  66. "They are also used to add permissions to groups of "
  67. "users."),
  68. queryset=ranks,
  69. initial=instance.rank,
  70. required=False,
  71. empty_label=_("No rank"))
  72. roles = Role.objects.order_by('name')
  73. extra_fields['roles'] = forms.ModelMultipleChoiceField(
  74. label=_("Roles"),
  75. help_text=_("Individual roles of this user."),
  76. queryset=roles,
  77. initial=instance.roles.all() if instance.pk else None,
  78. widget=forms.CheckboxSelectMultiple)
  79. return type('UserFormFinal', (FormType,), extra_fields)
  80. import warnings
  81. warnings.warn("Admin search inactive users not implemented yet.",
  82. FutureWarning)
  83. def StaffFlagUserFormFactory(FormType, instance, add_staff_field):
  84. FormType = UserFormFactory(FormType, instance)
  85. if add_staff_field:
  86. staff_levels = (
  87. (0, _("No access")),
  88. (1, _("Administrator")),
  89. (2, _("Superadmin")),
  90. )
  91. staff_fields = {
  92. 'staff_level': forms.TypedChoiceField(
  93. label=_("Admin level"),
  94. help_text=_('Only administrators can access admin sites. '
  95. 'In addition to admin site access, superadmins '
  96. 'can also change other members admin levels.'),
  97. coerce=int,
  98. choices=staff_levels,
  99. initial=instance.staff_level),
  100. }
  101. return type('StaffUserForm', (FormType,), staff_fields)
  102. else:
  103. return FormType
  104. class SearchUsersFormBase(forms.Form):
  105. username = forms.CharField(label=_("Username starts with"), required=False)
  106. email = forms.CharField(label=_("E-mail starts with"), required=False)
  107. #rank = forms.TypedChoiceField(label=_("Rank"),
  108. # coerce=int,
  109. # required=False,
  110. # choices=ranks_list)
  111. #role = forms.TypedChoiceField(label=_("Role"),
  112. # coerce=int,
  113. # required=False,
  114. # choices=roles_list)
  115. inactive = forms.YesNoSwitch(label=_("Inactive only"))
  116. is_staff = forms.YesNoSwitch(label=_("Is administrator"))
  117. def filter_queryset(self, search_criteria, queryset):
  118. criteria = search_criteria
  119. if criteria.get('username'):
  120. queryset = queryset.filter(
  121. username_slug__startswith=criteria.get('username').lower())
  122. if criteria.get('email'):
  123. queryset = queryset.filter(
  124. email__istartswith=criteria.get('email'))
  125. if criteria.get('rank'):
  126. queryset = queryset.filter(
  127. rank_id=criteria.get('rank'))
  128. if criteria.get('role'):
  129. queryset = queryset.filter(
  130. roles__id=criteria.get('role'))
  131. if criteria.get('inactive'):
  132. pass
  133. if criteria.get('is_staff'):
  134. queryset = criteria.filter(is_staff=True)
  135. return queryset
  136. def SearchUsersForm(*args, **kwargs):
  137. """
  138. Factory that uses cache for ranks and roles,
  139. and makes those ranks and roles typed choice fields that play nice
  140. with passing values via GET
  141. """
  142. ranks_choices = threadstore.get('misago_admin_ranks_choices', 'nada')
  143. if ranks_choices == 'nada':
  144. ranks_choices = [('', _("All ranks"))]
  145. for rank in Rank.objects.order_by('name').iterator():
  146. ranks_choices.append((rank.pk, rank.name))
  147. threadstore.set('misago_admin_ranks_choices', ranks_choices)
  148. roles_choices = threadstore.get('misago_admin_roles_choices', 'nada')
  149. if roles_choices == 'nada':
  150. roles_choices = [('', _("All roles"))]
  151. for role in Role.objects.order_by('name').iterator():
  152. roles_choices.append((role.pk, role.name))
  153. threadstore.set('misago_admin_roles_choices', roles_choices)
  154. extra_fields = {
  155. 'rank': forms.TypedChoiceField(label=_("Has rank"),
  156. coerce=int,
  157. required=False,
  158. choices=ranks_choices),
  159. 'role': forms.TypedChoiceField(label=_("Has role"),
  160. coerce=int,
  161. required=False,
  162. choices=roles_choices)
  163. }
  164. FinalForm = type('SearchUsersFormFinal',
  165. (SearchUsersFormBase,),
  166. extra_fields)
  167. return FinalForm(*args, **kwargs)
  168. """
  169. Ranks form
  170. """
  171. class RankForm(forms.ModelForm):
  172. name = forms.CharField(
  173. label=_("Name"),
  174. validators=[validate_sluggable()],
  175. help_text=_('Short and descriptive name of all users with this rank. '
  176. '"The Team" or "Game Masters" are good examples.'))
  177. title = forms.CharField(
  178. label=_("User title"), required=False,
  179. help_text=_('Optional, singular version of rank name displayed by '
  180. 'user names. For example "GM" or "Dev".'))
  181. description = forms.CharField(
  182. label=_("Description"), max_length=2048, required=False,
  183. widget=forms.Textarea(attrs={'rows': 3}),
  184. help_text=_("Optional description explaining function or status of "
  185. "members distincted with this rank."))
  186. roles = forms.ModelMultipleChoiceField(
  187. label=_("User roles"), queryset=Role.objects.order_by('name'),
  188. required=False, widget=forms.CheckboxSelectMultiple,
  189. help_text=_('Rank can give users with it additional roles.'))
  190. css_class = forms.CharField(
  191. label=_("CSS class"), required=False,
  192. help_text=_("Optional css class added to content belonging to this "
  193. "rank owner."))
  194. is_tab = forms.BooleanField(
  195. label=_("Give rank dedicated tab on users list"), required=False,
  196. help_text=_("Selecting this option will make users with this rank "
  197. "easily discoverable by others trough dedicated page on "
  198. "forum users list."))
  199. is_on_index = forms.BooleanField(
  200. label=_("Show users online on forum index"), required=False,
  201. help_text=_("Selecting this option will make forum inform other "
  202. "users of their availability by displaying them on forum "
  203. "index page."))
  204. class Meta:
  205. model = Rank
  206. fields = [
  207. 'name',
  208. 'description',
  209. 'css_class',
  210. 'title',
  211. 'roles',
  212. 'is_tab',
  213. 'is_on_index',
  214. ]
  215. def clean(self):
  216. data = super(RankForm, self).clean()
  217. self.instance.set_name(data.get('name'))
  218. return data
  219. """
  220. Bans Form
  221. """
  222. class BanForm(forms.ModelForm):
  223. test = forms.TypedChoiceField(
  224. label=_("Ban type"),
  225. coerce=int,
  226. choices=BANS_CHOICES)
  227. banned_value = forms.CharField(
  228. label=_("Banned value"), max_length=250,
  229. help_text=_('This value is case-insensitive and accepts asterisk (*) '
  230. 'for rought matches. For example, making IP ban for value '
  231. '"83.*" will ban all IP addresses beginning with "83.".'),
  232. error_messages={
  233. 'max_length': _("Banned value can't be longer than 250 characters.")
  234. })
  235. user_message = forms.CharField(
  236. label=_("Optional message for user"), required=False, max_length=1000,
  237. widget=forms.Textarea(attrs={'rows': 3}),
  238. error_messages={
  239. 'max_length': _("Message can't be longer than 1000 characters.")
  240. })
  241. staff_message = forms.CharField(
  242. label=_("Optional message for team"), required=False, max_length=1000,
  243. widget=forms.Textarea(attrs={'rows': 3}),
  244. error_messages={
  245. 'max_length': _("Message can't be longer than 1000 characters.")
  246. })
  247. valid_until = forms.DateField(
  248. label=_("Optional expiration date for this ban"),
  249. required=False, input_formats=['%m-%d-%Y'],
  250. widget=forms.DateInput(
  251. format='%m-%d-%Y', attrs={'data-date-format': 'MM-DD-YYYY'}),
  252. help_text=_('Leave this field empty for this ban to never expire.'))
  253. class Meta:
  254. model = Ban
  255. fields = [
  256. 'test',
  257. 'banned_value',
  258. 'user_message',
  259. 'staff_message',
  260. 'valid_until',
  261. ]
  262. class SearchBansForm(object):
  263. pass