forms.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.management.forms
  4. ~~~~~~~~~~~~~~~~~~~~~~~~
  5. It provides the forms that are needed for the management views.
  6. :copyright: (c) 2014 by the FlaskBB Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from flask_wtf import Form
  10. from wtforms import (StringField, TextAreaField, PasswordField, IntegerField,
  11. BooleanField, SelectField, SubmitField)
  12. from wtforms.validators import (DataRequired, Optional, Email, regexp, Length,
  13. URL, ValidationError)
  14. from wtforms.ext.sqlalchemy.fields import (QuerySelectField,
  15. QuerySelectMultipleField)
  16. from flask_babelex import lazy_gettext as _
  17. from flaskbb.utils.fields import BirthdayField
  18. from flaskbb.utils.widgets import SelectBirthdayWidget
  19. from flaskbb.extensions import db
  20. from flaskbb.forum.models import Forum, Category
  21. from flaskbb.user.models import User, Group
  22. USERNAME_RE = r'^[\w.+-]+$'
  23. is_username = regexp(USERNAME_RE,
  24. message=_("You can only use letters, numbers or dashes."))
  25. def selectable_forums():
  26. return Forum.query.order_by(Forum.position)
  27. def selectable_categories():
  28. return Category.query.order_by(Category.position)
  29. def select_primary_group():
  30. return Group.query.filter(Group.guest != True).order_by(Group.id)
  31. class UserForm(Form):
  32. username = StringField(_("Username"), validators=[
  33. DataRequired(message=_("A Username is required.")),
  34. is_username])
  35. email = StringField(_("E-Mail Address"), validators=[
  36. DataRequired(message=_("A E-Mail Address is required.")),
  37. Email(message=_("Invalid E-Mail Address."))])
  38. password = PasswordField("Password", validators=[
  39. Optional()])
  40. birthday = BirthdayField(_("Birthday"), format="%d %m %Y",
  41. widget=SelectBirthdayWidget(),
  42. validators=[Optional()])
  43. gender = SelectField(_("Gender"), default="None", choices=[
  44. ("None", ""),
  45. ("Male", _("Male")),
  46. ("Female", _("Female"))])
  47. location = StringField(_("Location"), validators=[
  48. Optional()])
  49. website = StringField(_("Website"), validators=[
  50. Optional(), URL()])
  51. avatar = StringField(_("Avatar"), validators=[
  52. Optional(), URL()])
  53. signature = TextAreaField(_("Forum Signature"), validators=[
  54. Optional(), Length(min=0, max=250)])
  55. notes = TextAreaField(_("Notes"), validators=[
  56. Optional(), Length(min=0, max=5000)])
  57. primary_group = QuerySelectField(
  58. _("Primary Group"),
  59. query_factory=select_primary_group,
  60. get_label="name")
  61. secondary_groups = QuerySelectMultipleField(
  62. _("Secondary Groups"),
  63. # TODO: Template rendering errors "NoneType is not callable"
  64. # without this, figure out why.
  65. query_factory=select_primary_group,
  66. get_label="name")
  67. submit = SubmitField(_("Save"))
  68. def validate_username(self, field):
  69. if hasattr(self, "user"):
  70. user = User.query.filter(
  71. db.and_(
  72. User.username.like(field.data),
  73. db.not_(User.id == self.user.id)
  74. )
  75. ).first()
  76. else:
  77. user = User.query.filter(User.username.like(field.data)).first()
  78. if user:
  79. raise ValidationError(_("This Username is already taken."))
  80. def validate_email(self, field):
  81. if hasattr(self, "user"):
  82. user = User.query.filter(
  83. db.and_(
  84. User.email.like(field.data),
  85. db.not_(User.id == self.user.id)
  86. )
  87. ).first()
  88. else:
  89. user = User.query.filter(User.email.like(field.data)).first()
  90. if user:
  91. raise ValidationError(_("This E-Mail Address is already taken."))
  92. def save(self):
  93. user = User(**self.data)
  94. return user.save()
  95. class AddUserForm(UserForm):
  96. pass
  97. class EditUserForm(UserForm):
  98. def __init__(self, user, *args, **kwargs):
  99. self.user = user
  100. kwargs['obj'] = self.user
  101. UserForm.__init__(self, *args, **kwargs)
  102. class GroupForm(Form):
  103. name = StringField(_("Group Name"), validators=[
  104. DataRequired(message=_("A Group name is required."))])
  105. description = TextAreaField(_("Description"), validators=[
  106. Optional()])
  107. admin = BooleanField(
  108. _("Is Admin Group?"),
  109. description=_("With this option the group has access to "
  110. "the admin panel.")
  111. )
  112. super_mod = BooleanField(
  113. _("Is Super Moderator Group?"),
  114. description=_("Check this if the users in this group are allowed to "
  115. "moderate every forum.")
  116. )
  117. mod = BooleanField(
  118. _("Is Moderator Group?"),
  119. description=_("Check this if the users in this group are allowed to "
  120. "moderate specified forums.")
  121. )
  122. banned = BooleanField(
  123. _("Is Banned Group?"),
  124. description=_("Only one Banned group is allowed.")
  125. )
  126. guest = BooleanField(
  127. _("Is Guest Group?"),
  128. description=_("Only one Guest group is allowed.")
  129. )
  130. editpost = BooleanField(
  131. _("Can edit posts"),
  132. description=_("Check this if the users in this group can edit posts.")
  133. )
  134. deletepost = BooleanField(
  135. _("Can delete posts"),
  136. description=_("Check this is the users in this group can delete posts.")
  137. )
  138. deletetopic = BooleanField(
  139. _("Can delete topics"),
  140. description=_("Check this is the users in this group can delete "
  141. "topics.")
  142. )
  143. posttopic = BooleanField(
  144. _("Can create topics"),
  145. description=_("Check this is the users in this group can create "
  146. "topics.")
  147. )
  148. postreply = BooleanField(
  149. _("Can post replies"),
  150. description=_("Check this is the users in this group can post replies.")
  151. )
  152. mod_edituser = BooleanField(
  153. _("Moderators can edit user profiles"),
  154. description=_("Allow moderators to edit a another users profile "
  155. "including password and email changes.")
  156. )
  157. mod_banuser = BooleanField(
  158. _("Moderators can ban users"),
  159. description=_("Allow moderators to ban other users.")
  160. )
  161. submit = SubmitField(_("Save"))
  162. def validate_name(self, field):
  163. if hasattr(self, "group"):
  164. group = Group.query.filter(
  165. db.and_(
  166. Group.name.like(field.data),
  167. db.not_(Group.id == self.group.id)
  168. )
  169. ).first()
  170. else:
  171. group = Group.query.filter(Group.name.like(field.data)).first()
  172. if group:
  173. raise ValidationError(_("This Group name is already taken."))
  174. def validate_banned(self, field):
  175. if hasattr(self, "group"):
  176. group = Group.query.filter(
  177. db.and_(
  178. Group.banned,
  179. db.not_(Group.id == self.group.id)
  180. )
  181. ).count()
  182. else:
  183. group = Group.query.filter_by(banned=True).count()
  184. if field.data and group > 0:
  185. raise ValidationError(_("There is already a Banned group."))
  186. def validate_guest(self, field):
  187. if hasattr(self, "group"):
  188. group = Group.query.filter(
  189. db.and_(
  190. Group.guest,
  191. db.not_(Group.id == self.group.id)
  192. )
  193. ).count()
  194. else:
  195. group = Group.query.filter_by(guest=True).count()
  196. if field.data and group > 0:
  197. raise ValidationError(_("There is already a Guest group."))
  198. def save(self):
  199. group = Group(**self.data)
  200. return group.save()
  201. class EditGroupForm(GroupForm):
  202. def __init__(self, group, *args, **kwargs):
  203. self.group = group
  204. kwargs['obj'] = self.group
  205. GroupForm.__init__(self, *args, **kwargs)
  206. class AddGroupForm(GroupForm):
  207. pass
  208. class ForumForm(Form):
  209. title = StringField(
  210. _("Forum Title"),
  211. validators=[DataRequired(message=_("A Forum Title is required."))]
  212. )
  213. description = TextAreaField(
  214. _("Description"),
  215. validators=[Optional()],
  216. description=_("You can format your description with BBCode.")
  217. )
  218. position = IntegerField(
  219. _("Position"),
  220. default=1,
  221. validators=[DataRequired(message=_("The Forum Position is required."))]
  222. )
  223. category = QuerySelectField(
  224. _("Category"),
  225. query_factory=selectable_categories,
  226. allow_blank=False,
  227. get_label="title",
  228. description=_("The category that contains this forum.")
  229. )
  230. external = StringField(
  231. _("External Link"),
  232. validators=[Optional(), URL()],
  233. description=_("A link to a website i.e. 'http://flaskbb.org'.")
  234. )
  235. moderators = StringField(
  236. _("Moderators"),
  237. description=_("Comma seperated usernames. Leave it blank if you do not "
  238. "want to set any moderators.")
  239. )
  240. show_moderators = BooleanField(
  241. _("Show Moderators"),
  242. description=_("Do you want show the moderators on the index page?")
  243. )
  244. locked = BooleanField(
  245. _("Locked?"),
  246. description=_("Disable new posts and topics in this forum.")
  247. )
  248. submit = SubmitField(_("Save"))
  249. def validate_external(self, field):
  250. if hasattr(self, "forum"):
  251. if self.forum.topics:
  252. raise ValidationError(_("You cannot convert a forum that "
  253. "contain topics in a external link."))
  254. def validate_show_moderators(self, field):
  255. if field.data and not self.moderators.data:
  256. raise ValidationError(_("You also need to specify some "
  257. "moderators."))
  258. def validate_moderators(self, field):
  259. approved_moderators = list()
  260. if field.data:
  261. # convert the CSV string in a list
  262. moderators = field.data.split(",")
  263. # remove leading and ending spaces
  264. moderators = [mod.strip() for mod in moderators]
  265. for moderator in moderators:
  266. # Check if the usernames exist
  267. user = User.query.filter_by(username=moderator).first()
  268. # Check if the user has the permissions to moderate a forum
  269. if user:
  270. if not (user.get_permissions()["mod"] or
  271. user.get_permissions()["admin"] or
  272. user.get_permissions()["super_mod"]):
  273. raise ValidationError(
  274. _("%(user)s is not in a moderators group.",
  275. user=user.username)
  276. )
  277. else:
  278. approved_moderators.append(user)
  279. else:
  280. raise ValidationError(_("User %(moderator)s not found.",
  281. moderator=moderator))
  282. field.data = approved_moderators
  283. else:
  284. field.data = approved_moderators
  285. def save(self):
  286. forum = Forum(title=self.title.data,
  287. description=self.description.data,
  288. position=self.position.data,
  289. external=self.external.data,
  290. show_moderators=self.show_moderators.data,
  291. locked=self.locked.data)
  292. if self.moderators.data:
  293. # is already validated
  294. forum.moderators = self.moderators.data
  295. forum.category_id = self.category.data.id
  296. return forum.save()
  297. class EditForumForm(ForumForm):
  298. def __init__(self, forum, *args, **kwargs):
  299. self.forum = forum
  300. kwargs['obj'] = self.forum
  301. ForumForm.__init__(self, *args, **kwargs)
  302. class AddForumForm(ForumForm):
  303. pass
  304. class CategoryForm(Form):
  305. title = StringField(_("Category Title"), validators=[
  306. DataRequired(message=_("A Category Title is required."))])
  307. description = TextAreaField(
  308. _("Description"),
  309. validators=[Optional()],
  310. description=_("You can format your description with BBCode.")
  311. )
  312. position = IntegerField(
  313. _("Position"),
  314. default=1,
  315. validators=[DataRequired(message=_("The Category Position is "
  316. "required."))]
  317. )
  318. submit = SubmitField(_("Save"))
  319. def save(self):
  320. data = self.data
  321. # remove the button
  322. data.pop('submit', None)
  323. category = Category(**data)
  324. return category.save()