forms.py 11 KB

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