spec.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.plugins.spec
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. This module provides the core FlaskBB plugin hook definitions
  6. :copyright: (c) 2017 by the FlaskBB Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from pluggy import HookspecMarker
  10. spec = HookspecMarker('flaskbb')
  11. # Setup Hooks
  12. @spec
  13. def flaskbb_extensions(app):
  14. """Hook for initializing any plugin loaded extensions."""
  15. @spec
  16. def flaskbb_load_translations():
  17. """Hook for registering translation folders."""
  18. @spec
  19. def flaskbb_load_migrations():
  20. """Hook for registering additional migrations."""
  21. @spec
  22. def flaskbb_load_blueprints(app):
  23. """Hook for registering blueprints.
  24. :param app: The application object.
  25. """
  26. @spec
  27. def flaskbb_request_processors(app):
  28. """Hook for registering pre/post request processors.
  29. :param app: The application object.
  30. """
  31. @spec
  32. def flaskbb_errorhandlers(app):
  33. """Hook for registering error handlers.
  34. :param app: The application object.
  35. """
  36. @spec
  37. def flaskbb_jinja_directives(app):
  38. """Hook for registering jinja filters, context processors, etc.
  39. :param app: The application object.
  40. """
  41. @spec
  42. def flaskbb_additional_setup(app, pluggy):
  43. """Hook for any additional setup a plugin wants to do after all other
  44. application setup has finished.
  45. For example, you could apply a WSGI middleware::
  46. @impl
  47. def flaskbb_additional_setup(app):
  48. app.wsgi_app = ProxyFix(app.wsgi_app)
  49. :param app: The application object.
  50. :param pluggy: The pluggy object.
  51. """
  52. @spec
  53. def flaskbb_load_post_markdown_class(app):
  54. """
  55. Hook for loading a mistune renderer child class in order to render
  56. markdown on posts and user signatures. All classes returned by this hook
  57. will be composed into a single class to render markdown for posts.
  58. Since all classes will be composed together, child classes should call
  59. super as appropriate and not add any new arguments to `__init__` since the
  60. class will be insantiated with predetermined arguments.
  61. Example::
  62. class YellingRenderer(mistune.Renderer):
  63. def paragraph(self, text):
  64. return super(YellingRenderer, self).paragraph(text.upper())
  65. @impl
  66. def flaskbb_load_post_markdown_class():
  67. return YellingRenderer
  68. :param app: The application object associated with the class if needed
  69. :type app: Flask
  70. """
  71. @spec
  72. def flaskbb_load_nonpost_markdown_class(app):
  73. """
  74. Hook for loading a mistune renderer child class in order to render
  75. markdown in locations other than posts, for example in category or
  76. forum descriptions. All classes returned by this hook will be composed into
  77. a single class to render markdown for nonpost content (e.g. forum and
  78. category descriptions).
  79. Since all classes will be composed together, child classes should call
  80. super as appropriate and not add any new arguments to `__init__` since the
  81. class will be insantiated with predetermined arguments.
  82. Example::
  83. class YellingRenderer(mistune.Renderer):
  84. def paragraph(self, text):
  85. return super(YellingRenderer, self).paragraph(text.upper())
  86. @impl
  87. def flaskbb_load_nonpost_markdown_class():
  88. return YellingRenderer
  89. :param app: The application object associated with the class if needed
  90. :type app: Flask
  91. """
  92. @spec
  93. def flaskbb_cli(cli, app):
  94. """Hook for registering CLI commands.
  95. For example::
  96. @impl
  97. def flaskbb_cli(cli):
  98. @cli.command()
  99. def testplugin():
  100. click.echo("Hello Testplugin")
  101. return testplugin
  102. :param app: The application object.
  103. :param cli: The FlaskBBGroup CLI object.
  104. """
  105. @spec
  106. def flaskbb_shell_context():
  107. """Hook for registering shell context handlers
  108. Expected to return a single callable function that returns a dictionary or
  109. iterable of key value pairs.
  110. """
  111. # Event hooks
  112. @spec
  113. def flaskbb_event_post_save_before(post):
  114. """Hook for handling a post before it has been saved.
  115. :param flaskbb.forum.models.Post post: The post which triggered the event.
  116. """
  117. @spec
  118. def flaskbb_event_post_save_after(post, is_new):
  119. """Hook for handling a post after it has been saved.
  120. :param flaskbb.forum.models.Post post: The post which triggered the event.
  121. :param bool is_new: True if the post is new, False if it is an edit.
  122. """
  123. @spec
  124. def flaskbb_event_topic_save_before(topic):
  125. """Hook for handling a topic before it has been saved.
  126. :param flaskbb.forum.models.Topic topic: The topic which triggered the
  127. event.
  128. """
  129. @spec
  130. def flaskbb_event_topic_save_after(topic, is_new):
  131. """Hook for handling a topic after it has been saved.
  132. :param flaskbb.forum.models.Topic topic: The topic which triggered the
  133. event.
  134. :param bool is_new: True if the topic is new, False if it is an edit.
  135. """
  136. @spec
  137. def flaskbb_event_user_registered(username):
  138. """Hook for handling events after a user is registered
  139. :param username: The username of the newly registered user.
  140. """
  141. @spec
  142. def flaskbb_gather_registration_validators():
  143. """
  144. Hook for gathering user registration validators, implementers must return
  145. a callable that accepts a
  146. :class:`~flaskbb.core.auth.registration.UserRegistrationInfo` and raises
  147. a :class:`~flaskbb.core.exceptions.ValidationError` if the registration
  148. is invalid or :class:`~flaskbb.core.exceptions.StopValidation` if
  149. validation of the registration should end immediatey.
  150. Example::
  151. def cannot_be_named_fred(user_info):
  152. if user_info.username.lower() == 'fred':
  153. raise ValidationError(('username', 'Cannot name user fred'))
  154. @impl
  155. def flaskbb_gather_validate_user_registration():
  156. return cannot_be_named_fred
  157. .. note::
  158. This is implemented as a hook that returns callables since the
  159. callables are designed to raise exceptions.
  160. """
  161. @spec
  162. def flaskbb_registration_failure_handler(user_info, failures):
  163. """
  164. Hook for dealing with user registration failures, receives the info
  165. that user attempted to register with as well as the errors that failed
  166. the registration.
  167. """
  168. @spec
  169. def flaskbb_registration_post_processor(user):
  170. """
  171. Hook for handling actions after a user has successfully registered.
  172. Example::
  173. def greet_user(user):
  174. flash(_("Thanks for registering {}".format(user.username)))
  175. @impl
  176. def flaskbb_registration_post_processor(user):
  177. greet_user(user)
  178. """
  179. @spec(firstresult=True)
  180. def flaskbb_authenticate(identifier, secret):
  181. """Hook for authenticating users in FlaskBB.
  182. This hook should return either an instance of
  183. :class:`flaskbb.user.models.User` or None.
  184. If a hook decides that all attempts for authentication
  185. should end, it may raise a
  186. :class:`flaskbb.core.exceptions.StopAuthentication`
  187. and include a reason why authentication was stopped.
  188. Only the first User result will used and the default FlaskBB
  189. authentication is tried last to give others an attempt to
  190. authenticate the user instead.
  191. See also:
  192. :class:`AuthenticationProvider<flaskbb.core.auth.AuthenticationProvider>`
  193. Example of alternative auth::
  194. def ldap_auth(identifier, secret):
  195. "basic ldap example with imaginary ldap library"
  196. user_dn = "uid={},ou=flaskbb,dc=flaskbb,dc=org"
  197. try:
  198. ldap.bind(user_dn, secret)
  199. return User.query.join(
  200. UserLDAP
  201. ).filter(
  202. UserLDAP.dn==user_dn
  203. ).with_entities(User).one()
  204. except:
  205. return None
  206. @impl
  207. def flaskbb_authenticate(identifier, secret):
  208. return ldap_auth(identifier, secret)
  209. Example of ending authentication::
  210. def prevent_login_with_too_many_failed_attempts(identifier):
  211. user = User.query.filter(
  212. db.or_(
  213. User.username == identifier,
  214. User.email == identifier
  215. )
  216. ).first()
  217. if user is not None:
  218. if has_too_many_failed_logins(user):
  219. raise StopAuthentication(_(
  220. "Your account is temporarily locked due to too many"
  221. " login attempts"
  222. ))
  223. @impl(tryfirst=True)
  224. def flaskbb_authenticate(user, identifier):
  225. prevent_login_with_too_many_failed_attempts(identifier)
  226. """
  227. @spec
  228. def flaskbb_post_authenticate(user):
  229. """Hook for handling actions that occur after a user is
  230. authenticated but before setting them as the current user.
  231. This could be used to handle MFA. However, these calls will
  232. be blocking and should be taken into account.
  233. Responses from this hook are not considered at all. If a hook
  234. should need to prevent the user from logging in, it should
  235. register itself as tryfirst and raise a
  236. :class:`flaskbb.core.exceptions.StopAuthentication`
  237. and include why the login was prevented.
  238. See also:
  239. :class:`PostAuthenticationHandler<flaskbb.core.auth.PostAuthenticationHandler>`
  240. Example::
  241. def post_auth(user):
  242. today = utcnow()
  243. if is_anniversary(today, user.date_joined):
  244. flash(_("Happy registerversary!"))
  245. @impl
  246. def flaskbb_post_authenticate(user):
  247. post_auth(user)
  248. """
  249. @spec
  250. def flaskbb_authentication_failed(identifier):
  251. """Hook for handling authentication failure events.
  252. This hook will only be called when no authentication
  253. providers successfully return a user or a
  254. :class:`flaskbb.core.exceptions.StopAuthentication`
  255. is raised during the login process.
  256. See also:
  257. :class:`AuthenticationFailureHandler<flaskbb.core.auth.AuthenticationFailureHandler>`
  258. Example::
  259. def mark_failed_logins(identifier):
  260. user = User.query.filter(
  261. db.or_(
  262. User.username == identifier,
  263. User.email == identifier
  264. )
  265. ).first()
  266. if user is not None:
  267. if user.login_attempts is None:
  268. user.login_attempts = 1
  269. else:
  270. user.login_attempts += 1
  271. user.last_failed_login = utcnow()
  272. """
  273. @spec(firstresult=True)
  274. def flaskbb_reauth_attempt(user, secret):
  275. """Hook for handling reauth in FlaskBB
  276. These hooks receive the currently authenticated user
  277. and the entered secret. Only the first response from
  278. this hook is considered -- similar to the authenticate
  279. hooks. A successful attempt should return True, otherwise
  280. None for an unsuccessful or untried reauth from an
  281. implementation. Reauth will be considered a failure if
  282. no implementation return True.
  283. If a hook decides that a reauthenticate attempt should
  284. cease, it may raise StopAuthentication.
  285. See also:
  286. :class:`ReauthenticateProvider<flaskbb.core.auth.ReauthenticateProvider>`
  287. Example of checking secret or passing to the next implementer::
  288. @impl
  289. def flaskbb_reauth_attempt(user, secret):
  290. if check_password(user.password, secret):
  291. return True
  292. Example of forcefully ending reauth::
  293. @impl
  294. def flaskbb_reauth_attempt(user, secret):
  295. if user.login_attempts > 5:
  296. raise StopAuthentication(
  297. _("Too many failed authentication attempts")
  298. )
  299. """
  300. @spec
  301. def flaskbb_post_reauth(user):
  302. """Hook called after successfully reauthenticating.
  303. These hooks are called a user has passed the flaskbb_reauth_attempt
  304. hooks but before their reauth is confirmed so a post reauth implementer
  305. may still force a reauth to fail by raising StopAuthentication.
  306. Results from these hooks are not considered.
  307. See also:
  308. :class:`PostReauthenticateHandler<flaskbb.core.auth.PostAuthenticationHandler>`
  309. """
  310. @spec
  311. def flaskbb_reauth_failed(user):
  312. """Hook called if a reauth fails.
  313. These hooks will only be called if no implementation
  314. for flaskbb_reauth_attempt returns a True result or if
  315. an implementation raises StopAuthentication.
  316. If an implementation raises ForceLogout it should register
  317. itself as trylast to give other reauth failed handlers an
  318. opprotunity to run first.
  319. See also:
  320. :class:`ReauthenticateFailureHandler<flaskbb.core.auth.ReauthenticateFailureHandler>`
  321. """
  322. # Form hooks
  323. @spec
  324. def flaskbb_form_new_post(form):
  325. """Hook for modifying the :class:`~flaskbb.forum.forms.ReplyForm`.
  326. For example::
  327. @impl
  328. def flaskbb_form_new_post(form):
  329. form.example = TextField("Example Field", validators=[
  330. DataRequired(message="This field is required"),
  331. Length(min=3, max=50)])
  332. :param form: The :class:`~flaskbb.forum.forms.ReplyForm` class.
  333. """
  334. @spec
  335. def flaskbb_form_new_post_save(form):
  336. """Hook for modifying the :class:`~flaskbb.forum.forms.ReplyForm`.
  337. This hook is called while populating the post object with
  338. the data from the form. The post object will be saved after the hook
  339. call.
  340. :param form: The form object.
  341. :param post: The post object.
  342. """
  343. @spec
  344. def flaskbb_form_new_topic(form):
  345. """Hook for modifying the :class:`~flaskbb.forum.forms.NewTopicForm`
  346. :param form: The :class:`~flaskbb.forum.forms.NewTopicForm` class.
  347. """
  348. @spec
  349. def flaskbb_form_new_topic_save(form, topic):
  350. """Hook for modifying the :class:`~flaskbb.forum.forms.NewTopicForm`.
  351. This hook is called while populating the topic object with
  352. the data from the form. The topic object will be saved after the hook
  353. call.
  354. :param form: The form object.
  355. :param topic: The topic object.
  356. """
  357. @spec
  358. def flaskbb_form_registration(form):
  359. """
  360. Hook for modifying the :class:`~flaskbb.auth.forms.RegisterForm`.
  361. :param form: The form class
  362. """
  363. # Template Hooks
  364. @spec
  365. def flaskbb_tpl_navigation_before():
  366. """Hook for registering additional navigation items.
  367. in :file:`templates/layout.html`.
  368. """
  369. @spec
  370. def flaskbb_tpl_navigation_after():
  371. """Hook for registering additional navigation items.
  372. in :file:`templates/layout.html`.
  373. """
  374. @spec
  375. def flaskbb_tpl_user_nav_loggedin_before():
  376. """Hook for registering additional user navigational items
  377. which are only shown when a user is logged in.
  378. in :file:`templates/layout.html`.
  379. """
  380. @spec
  381. def flaskbb_tpl_user_nav_loggedin_after():
  382. """Hook for registering additional user navigational items
  383. which are only shown when a user is logged in.
  384. in :file:`templates/layout.html`.
  385. """
  386. @spec
  387. def flaskbb_tpl_form_registration_before(form):
  388. """This hook is emitted in the Registration form **before** the first
  389. input field but after the hidden CSRF token field.
  390. in :file:`templates/auth/register.html`.
  391. :param form: The form object.
  392. """
  393. @spec
  394. def flaskbb_tpl_form_registration_after(form):
  395. """This hook is emitted in the Registration form **after** the last
  396. input field but before the submit field.
  397. in :file:`templates/auth/register.html`.
  398. :param form: The form object.
  399. """
  400. @spec
  401. def flaskbb_tpl_form_user_details_before(form):
  402. """This hook is emitted in the Change User Details form **before** an
  403. input field is rendered.
  404. in :file:`templates/user/change_user_details.html`.
  405. :param form: The form object.
  406. """
  407. @spec
  408. def flaskbb_tpl_form_user_details_after(form):
  409. """This hook is emitted in the Change User Details form **after** the last
  410. input field has been rendered but before the submit field.
  411. in :file:`templates/user/change_user_details.html`.
  412. :param form: The form object.
  413. """
  414. @spec
  415. def flaskbb_tpl_profile_settings_menu():
  416. """This hook is emitted on the user settings page in order to populate the
  417. side bar menu. Implementations of this hook should return a list of tuples
  418. that are view name and display text. The display text will be provided to
  419. the translation service so it is unnecessary to supply translated text.
  420. A plugin can declare a new block by setting the view to None. If this is
  421. done, consider marking the hook implementation with `trylast=True` to
  422. avoid capturing plugins that do not create new blocks.
  423. For example::
  424. @impl(trylast=True)
  425. def flaskbb_tpl_profile_settings_menu():
  426. return [
  427. (None, 'Account Settings'),
  428. ('user.settings', 'General Settings'),
  429. ('user.change_user_details', 'Change User Details'),
  430. ('user.change_email', 'Change E-Mail Address'),
  431. ('user.change_password', 'Change Password')
  432. ]
  433. Hookwrappers for this spec should not be registered as FlaskBB
  434. supplies its own hookwrapper to flatten all the lists into a single list.
  435. in :file:`templates/user/settings_layout.html`
  436. """
  437. @spec
  438. def flaskbb_tpl_admin_settings_menu(user):
  439. """This hook is emitted in the admin panel and used to add additional
  440. navigation links to the admin menu.
  441. Implementations of this hook should return a list of tuples
  442. that are view name, display text and optionally an icon.
  443. The display text will be provided to the translation service so it
  444. is unnecessary to supply translated text.
  445. For example::
  446. @impl(trylast=True)
  447. def flaskbb_tpl_admin_settings_menu():
  448. # only add this item if the user is an admin
  449. if Permission(IsAdmin, identity=current_user):
  450. return [
  451. ("myplugin.foobar", "Foobar", "fa fa-foobar")
  452. ]
  453. Hookwrappers for this spec should not be registered as FlaskBB
  454. supplies its own hookwrapper to flatten all the lists into a single list.
  455. in :file:`templates/management/management_layout.html`
  456. :param user: The current user object.
  457. """
  458. @spec
  459. def flaskbb_tpl_profile_sidebar_stats(user):
  460. """This hook is emitted on the users profile page below the standard
  461. information. For example, it can be used to add additional items
  462. such as a link to the profile.
  463. in :file:`templates/user/profile_layout.html`
  464. :param user: The user object for whom the profile is currently visited.
  465. """
  466. @spec
  467. def flaskbb_tpl_post_author_info_before(user, post):
  468. """This hook is emitted before the information about the
  469. author of a post is displayed (but after the username).
  470. in :file:`templates/forum/topic.html`
  471. :param user: The user object of the post's author.
  472. :param post: The post object.
  473. """
  474. @spec
  475. def flaskbb_tpl_post_author_info_after(user, post):
  476. """This hook is emitted after the information about the
  477. author of a post is displayed (but after the username).
  478. in :file:`templates/forum/topic.html`
  479. :param user: The user object of the post's author.
  480. :param post: The post object.
  481. """
  482. @spec
  483. def flaskbb_tpl_post_content_before(post):
  484. """Hook to do some stuff before the post content is rendered.
  485. in :file:`templates/forum/topic.html`
  486. :param post: The current post object.
  487. """
  488. @spec
  489. def flaskbb_tpl_post_content_after(post):
  490. """Hook to do some stuff after the post content is rendered.
  491. in :file:`templates/forum/topic.html`
  492. :param post: The current post object.
  493. """
  494. @spec
  495. def flaskbb_tpl_post_menu_before(post):
  496. """Hook for inserting a new item at the beginning of the post menu.
  497. in :file:`templates/forum/topic.html`
  498. :param post: The current post object.
  499. """
  500. @spec
  501. def flaskbb_tpl_post_menu_after(post):
  502. """Hook for inserting a new item at the end of the post menu.
  503. in :file:`templates/forum/topic.html`
  504. :param post: The current post object.
  505. """
  506. @spec
  507. def flaskbb_tpl_topic_controls(topic):
  508. """Hook for inserting additional topic moderation controls.
  509. in :file:`templates/forum/topic_controls.html`
  510. :param topic: The current topic object.
  511. """
  512. @spec
  513. def flaskbb_tpl_form_new_post_before(form):
  514. """Hook for inserting a new form field before the first field is
  515. rendered.
  516. For example::
  517. @impl
  518. def flaskbb_tpl_form_new_post_after(form):
  519. return render_template_string(
  520. \"""
  521. <div class="form-group">
  522. <div class="col-md-12 col-sm-12 col-xs-12">
  523. <label>{{ form.example.label.text }}</label>
  524. {{ form.example(class="form-control",
  525. placeholder=form.example.label.text) }}
  526. {%- for error in form.example.errors -%}
  527. <span class="help-block">{{error}}</span>
  528. {%- endfor -%}
  529. </div>
  530. </div>
  531. \"""
  532. in :file:`templates/forum/new_post.html`
  533. :param form: The form object.
  534. """
  535. @spec
  536. def flaskbb_tpl_form_new_post_after(form):
  537. """Hook for inserting a new form field after the last field is
  538. rendered (but before the submit field).
  539. in :file:`templates/forum/new_post.html`
  540. :param form: The form object.
  541. """
  542. @spec
  543. def flaskbb_tpl_form_new_topic_before(form):
  544. """Hook for inserting a new form field before the first field is
  545. rendered (but before the CSRF token).
  546. in :file:`templates/forum/new_topic.html`
  547. :param form: The form object.
  548. """
  549. @spec
  550. def flaskbb_tpl_form_new_topic_after(form):
  551. """Hook for inserting a new form field after the last field is
  552. rendered (but before the submit button).
  553. in :file:`templates/forum/new_topic.html`
  554. :param form: The form object.
  555. """