spec.py 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. # TODO(anr): When pluggy 1.0 is released, mark this spec deprecated
  137. @spec
  138. def flaskbb_event_user_registered(username):
  139. """Hook for handling events after a user is registered
  140. .. warning::
  141. This hook is deprecated in favor of
  142. :func:`~flaskbb.plugins.spec.flaskbb_registration_post_processor`
  143. :param username: The username of the newly registered user.
  144. """
  145. @spec
  146. def flaskbb_gather_registration_validators():
  147. """
  148. Hook for gathering user registration validators, implementers must return
  149. a callable that accepts a
  150. :class:`~flaskbb.core.auth.registration.UserRegistrationInfo` and raises
  151. a :class:`~flaskbb.core.exceptions.ValidationError` if the registration
  152. is invalid or :class:`~flaskbb.core.exceptions.StopValidation` if
  153. validation of the registration should end immediatey.
  154. Example::
  155. def cannot_be_named_fred(user_info):
  156. if user_info.username.lower() == 'fred':
  157. raise ValidationError(('username', 'Cannot name user fred'))
  158. @impl
  159. def flaskbb_gather_registration_validators():
  160. return [cannot_be_named_fred]
  161. .. note::
  162. This is implemented as a hook that returns callables since the
  163. callables are designed to raise exceptions that are aggregated to
  164. form the failure message for the registration response.
  165. See Also: :class:`~flaskbb.core.auth.registration.UserValidator`
  166. """
  167. @spec
  168. def flaskbb_registration_failure_handler(user_info, failures):
  169. """
  170. Hook for dealing with user registration failures, receives the info
  171. that user attempted to register with as well as the errors that failed
  172. the registration.
  173. Example::
  174. from .utils import fuzz_username
  175. def has_already_registered(failures):
  176. return any(
  177. attr = "username" and "already registered" in msg
  178. for (attr, msg) in failures
  179. )
  180. def suggest_alternate_usernames(user_info, failures):
  181. if has_already_registered(failures):
  182. suggestions = fuzz_username(user_info.username)
  183. failures.append(("username", "Try: {}".format(suggestions)))
  184. @impl
  185. def flaskbb_registration_failure_handler(user_info, failures):
  186. suggest_alternate_usernames(user_info, failures)
  187. See Also: :class:`~flaskbb.core.auth.registration.RegistrationFailureHandler`
  188. """ # noqa
  189. @spec
  190. def flaskbb_registration_post_processor(user):
  191. """
  192. Hook for handling actions after a user has successfully registered. This
  193. spec receives the user object after it has been successfully persisted
  194. to the database.
  195. Example::
  196. def greet_user(user):
  197. flash(_("Thanks for registering {}".format(user.username)))
  198. @impl
  199. def flaskbb_registration_post_processor(user):
  200. greet_user(user)
  201. See Also: :class:`~flaskbb.core.auth.registration.RegistrationPostProcessor`
  202. """ # noqa
  203. @spec(firstresult=True)
  204. def flaskbb_authenticate(identifier, secret):
  205. """Hook for authenticating users in FlaskBB.
  206. This hook should return either an instance of
  207. :class:`flaskbb.user.models.User` or None.
  208. If a hook decides that all attempts for authentication
  209. should end, it may raise a
  210. :class:`flaskbb.core.exceptions.StopAuthentication`
  211. and include a reason why authentication was stopped.
  212. Only the first User result will used and the default FlaskBB
  213. authentication is tried last to give others an attempt to
  214. authenticate the user instead.
  215. See also:
  216. :class:`AuthenticationProvider<flaskbb.core.auth.AuthenticationProvider>`
  217. Example of alternative auth::
  218. def ldap_auth(identifier, secret):
  219. "basic ldap example with imaginary ldap library"
  220. user_dn = "uid={},ou=flaskbb,dc=flaskbb,dc=org"
  221. try:
  222. ldap.bind(user_dn, secret)
  223. return User.query.join(
  224. UserLDAP
  225. ).filter(
  226. UserLDAP.dn==user_dn
  227. ).with_entities(User).one()
  228. except:
  229. return None
  230. @impl
  231. def flaskbb_authenticate(identifier, secret):
  232. return ldap_auth(identifier, secret)
  233. Example of ending authentication::
  234. def prevent_login_with_too_many_failed_attempts(identifier):
  235. user = User.query.filter(
  236. db.or_(
  237. User.username == identifier,
  238. User.email == identifier
  239. )
  240. ).first()
  241. if user is not None:
  242. if has_too_many_failed_logins(user):
  243. raise StopAuthentication(_(
  244. "Your account is temporarily locked due to too many"
  245. " login attempts"
  246. ))
  247. @impl(tryfirst=True)
  248. def flaskbb_authenticate(user, identifier):
  249. prevent_login_with_too_many_failed_attempts(identifier)
  250. """
  251. @spec
  252. def flaskbb_post_authenticate(user):
  253. """Hook for handling actions that occur after a user is
  254. authenticated but before setting them as the current user.
  255. This could be used to handle MFA. However, these calls will
  256. be blocking and should be taken into account.
  257. Responses from this hook are not considered at all. If a hook
  258. should need to prevent the user from logging in, it should
  259. register itself as tryfirst and raise a
  260. :class:`flaskbb.core.exceptions.StopAuthentication`
  261. and include why the login was prevented.
  262. See also:
  263. :class:`PostAuthenticationHandler<flaskbb.core.auth.PostAuthenticationHandler>`
  264. Example::
  265. def post_auth(user):
  266. today = utcnow()
  267. if is_anniversary(today, user.date_joined):
  268. flash(_("Happy registerversary!"))
  269. @impl
  270. def flaskbb_post_authenticate(user):
  271. post_auth(user)
  272. """
  273. @spec
  274. def flaskbb_authentication_failed(identifier):
  275. """Hook for handling authentication failure events.
  276. This hook will only be called when no authentication
  277. providers successfully return a user or a
  278. :class:`flaskbb.core.exceptions.StopAuthentication`
  279. is raised during the login process.
  280. See also:
  281. :class:`AuthenticationFailureHandler<flaskbb.core.auth.AuthenticationFailureHandler>`
  282. Example::
  283. def mark_failed_logins(identifier):
  284. user = User.query.filter(
  285. db.or_(
  286. User.username == identifier,
  287. User.email == identifier
  288. )
  289. ).first()
  290. if user is not None:
  291. if user.login_attempts is None:
  292. user.login_attempts = 1
  293. else:
  294. user.login_attempts += 1
  295. user.last_failed_login = utcnow()
  296. """
  297. @spec(firstresult=True)
  298. def flaskbb_reauth_attempt(user, secret):
  299. """Hook for handling reauth in FlaskBB
  300. These hooks receive the currently authenticated user
  301. and the entered secret. Only the first response from
  302. this hook is considered -- similar to the authenticate
  303. hooks. A successful attempt should return True, otherwise
  304. None for an unsuccessful or untried reauth from an
  305. implementation. Reauth will be considered a failure if
  306. no implementation return True.
  307. If a hook decides that a reauthenticate attempt should
  308. cease, it may raise StopAuthentication.
  309. See also:
  310. :class:`ReauthenticateProvider<flaskbb.core.auth.ReauthenticateProvider>`
  311. Example of checking secret or passing to the next implementer::
  312. @impl
  313. def flaskbb_reauth_attempt(user, secret):
  314. if check_password(user.password, secret):
  315. return True
  316. Example of forcefully ending reauth::
  317. @impl
  318. def flaskbb_reauth_attempt(user, secret):
  319. if user.login_attempts > 5:
  320. raise StopAuthentication(
  321. _("Too many failed authentication attempts")
  322. )
  323. """
  324. @spec
  325. def flaskbb_post_reauth(user):
  326. """Hook called after successfully reauthenticating.
  327. These hooks are called a user has passed the flaskbb_reauth_attempt
  328. hooks but before their reauth is confirmed so a post reauth implementer
  329. may still force a reauth to fail by raising StopAuthentication.
  330. Results from these hooks are not considered.
  331. See also:
  332. :class:`PostReauthenticateHandler<flaskbb.core.auth.PostAuthenticationHandler>`
  333. """
  334. @spec
  335. def flaskbb_reauth_failed(user):
  336. """Hook called if a reauth fails.
  337. These hooks will only be called if no implementation
  338. for flaskbb_reauth_attempt returns a True result or if
  339. an implementation raises StopAuthentication.
  340. If an implementation raises ForceLogout it should register
  341. itself as trylast to give other reauth failed handlers an
  342. opprotunity to run first.
  343. See also:
  344. :class:`ReauthenticateFailureHandler<flaskbb.core.auth.ReauthenticateFailureHandler>`
  345. """
  346. # Form hooks
  347. @spec
  348. def flaskbb_form_new_post(form):
  349. """Hook for modifying the :class:`~flaskbb.forum.forms.ReplyForm`.
  350. For example::
  351. @impl
  352. def flaskbb_form_new_post(form):
  353. form.example = TextField("Example Field", validators=[
  354. DataRequired(message="This field is required"),
  355. Length(min=3, max=50)])
  356. :param form: The :class:`~flaskbb.forum.forms.ReplyForm` class.
  357. """
  358. @spec
  359. def flaskbb_form_post_save(form):
  360. """Hook for modifying the :class:`~flaskbb.forum.forms.ReplyForm`.
  361. This hook is called while populating the post object with
  362. the data from the form. The post object will be saved after the hook
  363. call.
  364. :param form: The form object.
  365. :param post: The post object.
  366. """
  367. @spec
  368. def flaskbb_form_new_topic(form):
  369. """Hook for modifying the :class:`~flaskbb.forum.forms.NewTopicForm`
  370. :param form: The :class:`~flaskbb.forum.forms.NewTopicForm` class.
  371. """
  372. @spec
  373. def flaskbb_form_topic_save(form, topic):
  374. """Hook for modifying the :class:`~flaskbb.forum.forms.NewTopicForm`.
  375. This hook is called while populating the topic object with
  376. the data from the form. The topic object will be saved after the hook
  377. call.
  378. :param form: The form object.
  379. :param topic: The topic object.
  380. """
  381. @spec
  382. def flaskbb_form_registration(form):
  383. """
  384. Hook for modifying the :class:`~flaskbb.auth.forms.RegisterForm`.
  385. :param form: The form class
  386. """
  387. @spec
  388. def flaskbb_gather_password_validators(app):
  389. """
  390. Hook for gathering :class:`~flaskbb.core.changesets.ChangeSetValidator`
  391. instances specialized for handling :class:`~flaskbb.core.user.update.PasswordUpdate`
  392. This hook should return an iterable::
  393. class NotLongEnough(ChangeSetValidator):
  394. def __init__(self, min_length):
  395. self._min_length = min_length
  396. def validate(self, model, changeset):
  397. if len(changeset.new_password) < self._min_length:
  398. raise ValidationError(
  399. "new_password",
  400. "Password must be at least {} characters ".format(
  401. self._min_length
  402. )
  403. )
  404. @impl
  405. def flaskbb_gather_password_validators(app):
  406. return [NotLongEnough(app.config['MIN_PASSWORD_LENGTH'])]
  407. :param app: The current application
  408. """
  409. @spec
  410. def flaskbb_gather_email_validators(app):
  411. """
  412. Hook for gathering :class:`~flaskbb.core.changesets.ChangeSetValidator`
  413. instances specialized for :class:`~flaskbb.core.user.update.EmailUpdate`.
  414. This hook should return an iterable::
  415. class BlackListedEmailProviders(ChangeSetValidator):
  416. def __init__(self, black_list):
  417. self._black_list = black_list
  418. def validate(self, model, changeset):
  419. provider = changeset.new_email.split('@')[1]
  420. if provider in self._black_list:
  421. raise ValidationError(
  422. "new_email",
  423. "{} is a black listed email provider".format(provider)
  424. )
  425. @impl
  426. def flaskbb_gather_email_validators(app):
  427. return [BlackListedEmailProviders(app.config["EMAIL_PROVIDER_BLACK_LIST"])]
  428. :param app: The current application
  429. """
  430. @spec
  431. def flaskbb_gather_details_update_validators(app):
  432. """
  433. Hook for gathering :class:`~flaskbb.core.changesets.ChangeSetValidator`
  434. instances specialized for :class:`~flaskbb.core.user.update.UserDetailsChange`.
  435. This hook should return an iterable::
  436. class DontAllowImageSignatures(ChangeSetValidator):
  437. def __init__(self, renderer):
  438. self._renderer = renderer
  439. def validate(self, model, changeset):
  440. rendered = self._renderer.render(changeset.signature)
  441. if '<img' in rendered:
  442. raise ValidationError("signature", "No images allowed in signature")
  443. @impl
  444. def flaskbb_gather_details_update_validators(app):
  445. renderer = app.pluggy.hook.flaskbb_load_nonpost_markdown_class()
  446. return [DontAllowImageSignatures(renderer())]
  447. :param app: The current application
  448. """
  449. @spec
  450. def flaskbb_details_updated(user, details_update):
  451. """
  452. Hook for responding to a user updating their details. This hook is called
  453. after the details update has been persisted.
  454. See also :class:`~flaskbb.core.changesets.ChangeSetPostProcessor`
  455. :param user: The user whose details have been updated.
  456. :param details_update: The details change set applied to the user.
  457. """
  458. @spec
  459. def flaskbb_password_updated(user):
  460. """
  461. Hook for responding to a user updating their password. This hook is called
  462. after the password change has been persisted::
  463. @impl
  464. def flaskbb_password_updated(app, user):
  465. send_email(
  466. "Password changed",
  467. [user.email],
  468. text_body=...,
  469. html_body=...
  470. )
  471. See also :class:`~flaskbb.core.changesets.ChangeSetPostProcessor`
  472. :param user: The user that updated their password.
  473. """
  474. @spec
  475. def flaskbb_email_updated(user, email_update):
  476. """
  477. Hook for responding to a user updating their email. This hook is called after
  478. the email change has been persisted::
  479. @impl
  480. def flaskbb_email_updated(app):
  481. send_email(
  482. "Email changed",
  483. [email_change.old_email],
  484. text_body=...,
  485. html_body=...
  486. )
  487. See also :class:`~flaskbb.core.changesets.ChangeSetPostProcessor`.
  488. :param user: The user whose email was updated.
  489. :param email_update: The change set applied to the user.
  490. """
  491. @spec
  492. def flaskbb_settings_updated(user, settings_update):
  493. """
  494. Hook for responding to a user updating their settings. This hook is called after
  495. the settings change has been persisted.
  496. See also :class:`~flaskbb.core.changesets.ChangeSetPostProcessor`
  497. :param user: The user whose settings have been updated.
  498. :param settings: The settings change set applied to the user.
  499. """
  500. # Template Hooks
  501. @spec
  502. def flaskbb_tpl_navigation_before():
  503. """Hook for registering additional navigation items.
  504. in :file:`templates/layout.html`.
  505. """
  506. @spec
  507. def flaskbb_tpl_navigation_after():
  508. """Hook for registering additional navigation items.
  509. in :file:`templates/layout.html`.
  510. """
  511. @spec
  512. def flaskbb_tpl_user_nav_loggedin_before():
  513. """Hook for registering additional user navigational items
  514. which are only shown when a user is logged in.
  515. in :file:`templates/layout.html`.
  516. """
  517. @spec
  518. def flaskbb_tpl_user_nav_loggedin_after():
  519. """Hook for registering additional user navigational items
  520. which are only shown when a user is logged in.
  521. in :file:`templates/layout.html`.
  522. """
  523. @spec
  524. def flaskbb_tpl_form_registration_before(form):
  525. """This hook is emitted in the Registration form **before** the first
  526. input field but after the hidden CSRF token field.
  527. in :file:`templates/auth/register.html`.
  528. :param form: The form object.
  529. """
  530. @spec
  531. def flaskbb_tpl_form_registration_after(form):
  532. """This hook is emitted in the Registration form **after** the last
  533. input field but before the submit field.
  534. in :file:`templates/auth/register.html`.
  535. :param form: The form object.
  536. """
  537. @spec
  538. def flaskbb_tpl_form_user_details_before(form):
  539. """This hook is emitted in the Change User Details form **before** an
  540. input field is rendered.
  541. in :file:`templates/user/change_user_details.html`.
  542. :param form: The form object.
  543. """
  544. @spec
  545. def flaskbb_tpl_form_user_details_after(form):
  546. """This hook is emitted in the Change User Details form **after** the last
  547. input field has been rendered but before the submit field.
  548. in :file:`templates/user/change_user_details.html`.
  549. :param form: The form object.
  550. """
  551. @spec
  552. def flaskbb_tpl_profile_settings_menu(user):
  553. """This hook is emitted on the user settings page in order to populate the
  554. side bar menu. Implementations of this hook should return a list of tuples
  555. that are view name and display text. The display text will be provided to
  556. the translation service so it is unnecessary to supply translated text.
  557. A plugin can declare a new block by setting the view to None. If this is
  558. done, consider marking the hook implementation with `trylast=True` to
  559. avoid capturing plugins that do not create new blocks.
  560. For example::
  561. @impl(trylast=True)
  562. def flaskbb_tpl_profile_settings_menu():
  563. return [
  564. (None, 'Account Settings'),
  565. ('user.settings', 'General Settings'),
  566. ('user.change_user_details', 'Change User Details'),
  567. ('user.change_email', 'Change E-Mail Address'),
  568. ('user.change_password', 'Change Password')
  569. ]
  570. Hookwrappers for this spec should not be registered as FlaskBB
  571. supplies its own hookwrapper to flatten all the lists into a single list.
  572. in :file:`templates/user/settings_layout.html`
  573. .. versionchanged:: 2.1.0
  574. The user param. Typically this will be the current user but might not
  575. always be the current user.
  576. :param user: The user the settings menu is being rendered for.
  577. """
  578. @spec
  579. def flaskbb_tpl_profile_sidebar_links(user):
  580. """
  581. This hook is emitted on the user profile page in order to populate the
  582. sidebar menu. Implementations of this hook should return an iterable of
  583. :class:`~flaskbb.display.navigation.NavigationItem` instances::
  584. @impl
  585. def flaskbb_tpl_profile_sidebar_links(user):
  586. return [
  587. NavigationLink(
  588. endpoint="user.profile",
  589. name=_("Overview"),
  590. icon="fa fa-home",
  591. urlforkwargs={"username": user.username},
  592. ),
  593. NavigationLink(
  594. endpoint="user.view_all_topics",
  595. name=_("Topics"),
  596. icon="fa fa-comments",
  597. urlforkwargs={"username": user.username},
  598. ),
  599. NavigationLink(
  600. endpoint="user.view_all_posts",
  601. name=_("Posts"),
  602. icon="fa fa-comment",
  603. urlforkwargs={"username": user.username},
  604. ),
  605. ]
  606. .. warning::
  607. Hookwrappers for this spec should not be registered as FlaskBB registers
  608. its own hook wrapper to flatten all the results into a single list.
  609. .. versionadded:: 2.1
  610. :param user: The user the profile page belongs to.
  611. """
  612. @spec
  613. def flaskbb_tpl_admin_settings_menu(user):
  614. """This hook is emitted in the admin panel and used to add additional
  615. navigation links to the admin menu.
  616. Implementations of this hook should return a list of tuples
  617. that are view name, display text and optionally an icon.
  618. The display text will be provided to the translation service so it
  619. is unnecessary to supply translated text.
  620. For example::
  621. @impl(trylast=True)
  622. def flaskbb_tpl_admin_settings_menu():
  623. # only add this item if the user is an admin
  624. if Permission(IsAdmin, identity=current_user):
  625. return [
  626. ("myplugin.foobar", "Foobar", "fa fa-foobar")
  627. ]
  628. Hookwrappers for this spec should not be registered as FlaskBB
  629. supplies its own hookwrapper to flatten all the lists into a single list.
  630. in :file:`templates/management/management_layout.html`
  631. :param user: The current user object.
  632. """
  633. @spec
  634. def flaskbb_tpl_profile_sidebar_stats(user):
  635. """This hook is emitted on the users profile page below the standard
  636. information. For example, it can be used to add additional items
  637. such as a link to the profile.
  638. in :file:`templates/user/profile_layout.html`
  639. :param user: The user object for whom the profile is currently visited.
  640. """
  641. @spec
  642. def flaskbb_tpl_post_author_info_before(user, post):
  643. """This hook is emitted before the information about the
  644. author of a post is displayed (but after the username).
  645. in :file:`templates/forum/topic.html`
  646. :param user: The user object of the post's author.
  647. :param post: The post object.
  648. """
  649. @spec
  650. def flaskbb_tpl_post_author_info_after(user, post):
  651. """This hook is emitted after the information about the
  652. author of a post is displayed (but after the username).
  653. in :file:`templates/forum/topic.html`
  654. :param user: The user object of the post's author.
  655. :param post: The post object.
  656. """
  657. @spec
  658. def flaskbb_tpl_post_content_before(post):
  659. """Hook to do some stuff before the post content is rendered.
  660. in :file:`templates/forum/topic.html`
  661. :param post: The current post object.
  662. """
  663. @spec
  664. def flaskbb_tpl_post_content_after(post):
  665. """Hook to do some stuff after the post content is rendered.
  666. in :file:`templates/forum/topic.html`
  667. :param post: The current post object.
  668. """
  669. @spec
  670. def flaskbb_tpl_post_menu_before(post):
  671. """Hook for inserting a new item at the beginning of the post menu.
  672. in :file:`templates/forum/topic.html`
  673. :param post: The current post object.
  674. """
  675. @spec
  676. def flaskbb_tpl_post_menu_after(post):
  677. """Hook for inserting a new item at the end of the post menu.
  678. in :file:`templates/forum/topic.html`
  679. :param post: The current post object.
  680. """
  681. @spec
  682. def flaskbb_tpl_topic_controls(topic):
  683. """Hook for inserting additional topic moderation controls.
  684. in :file:`templates/forum/topic_controls.html`
  685. :param topic: The current topic object.
  686. """
  687. @spec
  688. def flaskbb_tpl_form_new_post_before(form):
  689. """Hook for inserting a new form field before the first field is
  690. rendered.
  691. For example::
  692. @impl
  693. def flaskbb_tpl_form_new_post_after(form):
  694. return render_template_string(
  695. \"""
  696. <div class="form-group">
  697. <div class="col-md-12 col-sm-12 col-xs-12">
  698. <label>{{ form.example.label.text }}</label>
  699. {{ form.example(class="form-control",
  700. placeholder=form.example.label.text) }}
  701. {%- for error in form.example.errors -%}
  702. <span class="help-block">{{error}}</span>
  703. {%- endfor -%}
  704. </div>
  705. </div>
  706. \"""
  707. in :file:`templates/forum/new_post.html`
  708. :param form: The form object.
  709. """
  710. @spec
  711. def flaskbb_tpl_form_new_post_after(form):
  712. """Hook for inserting a new form field after the last field is
  713. rendered (but before the submit field).
  714. in :file:`templates/forum/new_post.html`
  715. :param form: The form object.
  716. """
  717. @spec
  718. def flaskbb_tpl_form_new_topic_before(form):
  719. """Hook for inserting a new form field before the first field is
  720. rendered (but before the CSRF token).
  721. in :file:`templates/forum/new_topic.html`
  722. :param form: The form object.
  723. """
  724. @spec
  725. def flaskbb_tpl_form_new_topic_after(form):
  726. """Hook for inserting a new form field after the last field is
  727. rendered (but before the submit button).
  728. in :file:`templates/forum/new_topic.html`
  729. :param form: The form object.
  730. """