decorators.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # GNU MediaGoblin -- federated, autonomous media hosting
  2. # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. from functools import wraps
  17. from werkzeug.exceptions import Forbidden, NotFound
  18. from oauthlib.oauth1 import ResourceEndpoint
  19. from six.moves.urllib.parse import urljoin
  20. from mediagoblin import mg_globals as mgg
  21. from mediagoblin import messages
  22. from mediagoblin.db.models import MediaEntry, LocalUser, TextComment, \
  23. AccessToken, Comment
  24. from mediagoblin.tools.response import (
  25. redirect, render_404,
  26. render_user_banned, json_response)
  27. from mediagoblin.tools.translate import pass_to_ugettext as _
  28. from mediagoblin.oauth.tools.request import decode_authorization_header
  29. from mediagoblin.oauth.oauth import GMGRequestValidator
  30. def user_not_banned(controller):
  31. """
  32. Requires that the user has not been banned. Otherwise redirects to the page
  33. explaining why they have been banned
  34. """
  35. @wraps(controller)
  36. def wrapper(request, *args, **kwargs):
  37. if request.user:
  38. if request.user.is_banned():
  39. return render_user_banned(request)
  40. return controller(request, *args, **kwargs)
  41. return wrapper
  42. def require_active_login(controller):
  43. """
  44. Require an active login from the user. If the user is banned, redirects to
  45. the "You are Banned" page.
  46. """
  47. @wraps(controller)
  48. @user_not_banned
  49. def new_controller_func(request, *args, **kwargs):
  50. if request.user and \
  51. not request.user.has_privilege(u'active'):
  52. return redirect(
  53. request, 'mediagoblin.user_pages.user_home',
  54. user=request.user.username)
  55. elif not request.user or not request.user.has_privilege(u'active'):
  56. next_url = urljoin(
  57. request.urlgen('mediagoblin.auth.login',
  58. qualified=True),
  59. request.url)
  60. return redirect(request, 'mediagoblin.auth.login',
  61. next=next_url)
  62. return controller(request, *args, **kwargs)
  63. return new_controller_func
  64. def user_has_privilege(privilege_name, allow_admin=True):
  65. """
  66. Requires that a user have a particular privilege in order to access a page.
  67. In order to require that a user have multiple privileges, use this
  68. decorator twice on the same view. This decorator also makes sure that the
  69. user is not banned, or else it redirects them to the "You are Banned" page.
  70. :param privilege_name A unicode object that is that represents
  71. the privilege object. This object is
  72. the name of the privilege, as assigned
  73. in the Privilege.privilege_name column
  74. :param allow_admin If this is true then if the user is an admin
  75. it will allow the user even if the user doesn't
  76. have the privilage given in privilage_name.
  77. """
  78. def user_has_privilege_decorator(controller):
  79. @wraps(controller)
  80. @require_active_login
  81. def wrapper(request, *args, **kwargs):
  82. if not request.user.has_privilege(privilege_name, allow_admin):
  83. raise Forbidden()
  84. return controller(request, *args, **kwargs)
  85. return wrapper
  86. return user_has_privilege_decorator
  87. def active_user_from_url(controller):
  88. """Retrieve LocalUser() from <user> URL pattern and pass in as url_user=...
  89. Returns a 404 if no such active user has been found"""
  90. @wraps(controller)
  91. def wrapper(request, *args, **kwargs):
  92. user = LocalUser.query.filter_by(username=request.matchdict['user']).first()
  93. if user is None:
  94. return render_404(request)
  95. return controller(request, *args, url_user=user, **kwargs)
  96. return wrapper
  97. def user_may_delete_media(controller):
  98. """
  99. Require user ownership of the MediaEntry to delete.
  100. """
  101. @wraps(controller)
  102. def wrapper(request, *args, **kwargs):
  103. uploader_id = kwargs['media'].actor
  104. if not (request.user.has_privilege(u'admin') or
  105. request.user.id == uploader_id):
  106. raise Forbidden()
  107. return controller(request, *args, **kwargs)
  108. return wrapper
  109. def user_may_alter_collection(controller):
  110. """
  111. Require user ownership of the Collection to modify.
  112. """
  113. @wraps(controller)
  114. def wrapper(request, *args, **kwargs):
  115. creator_id = request.db.LocalUser.query.filter_by(
  116. username=request.matchdict['user']).first().id
  117. if not (request.user.has_privilege(u'admin') or
  118. request.user.id == creator_id):
  119. raise Forbidden()
  120. return controller(request, *args, **kwargs)
  121. return wrapper
  122. def uses_pagination(controller):
  123. """
  124. Check request GET 'page' key for wrong values
  125. """
  126. @wraps(controller)
  127. def wrapper(request, *args, **kwargs):
  128. try:
  129. page = int(request.GET.get('page', 1))
  130. if page < 0:
  131. return render_404(request)
  132. except ValueError:
  133. return render_404(request)
  134. return controller(request, page=page, *args, **kwargs)
  135. return wrapper
  136. def get_user_media_entry(controller):
  137. """
  138. Pass in a MediaEntry based off of a url component
  139. """
  140. @wraps(controller)
  141. def wrapper(request, *args, **kwargs):
  142. user = LocalUser.query.filter_by(username=request.matchdict['user']).first()
  143. if not user:
  144. raise NotFound()
  145. media = None
  146. # might not be a slug, might be an id, but whatever
  147. media_slug = request.matchdict['media']
  148. # if it starts with id: it actually isn't a slug, it's an id.
  149. if media_slug.startswith(u'id:'):
  150. try:
  151. media = MediaEntry.query.filter_by(
  152. id=int(media_slug[3:]),
  153. state=u'processed',
  154. actor=user.id).first()
  155. except ValueError:
  156. raise NotFound()
  157. else:
  158. # no magical id: stuff? It's a slug!
  159. media = MediaEntry.query.filter_by(
  160. slug=media_slug,
  161. state=u'processed',
  162. actor=user.id).first()
  163. if not media:
  164. # Didn't find anything? Okay, 404.
  165. raise NotFound()
  166. return controller(request, media=media, *args, **kwargs)
  167. return wrapper
  168. def get_user_collection(controller):
  169. """
  170. Pass in a Collection based off of a url component
  171. """
  172. @wraps(controller)
  173. def wrapper(request, *args, **kwargs):
  174. user = request.db.LocalUser.query.filter_by(
  175. username=request.matchdict['user']).first()
  176. if not user:
  177. return render_404(request)
  178. collection = request.db.Collection.query.filter_by(
  179. slug=request.matchdict['collection'],
  180. actor=user.id).first()
  181. # Still no collection? Okay, 404.
  182. if not collection:
  183. return render_404(request)
  184. return controller(request, collection=collection, *args, **kwargs)
  185. return wrapper
  186. def get_user_collection_item(controller):
  187. """
  188. Pass in a CollectionItem based off of a url component
  189. """
  190. @wraps(controller)
  191. def wrapper(request, *args, **kwargs):
  192. user = request.db.LocalUser.query.filter_by(
  193. username=request.matchdict['user']).first()
  194. if not user:
  195. return render_404(request)
  196. collection_item = request.db.CollectionItem.query.filter_by(
  197. id=request.matchdict['collection_item']).first()
  198. # Still no collection item? Okay, 404.
  199. if not collection_item:
  200. return render_404(request)
  201. return controller(request, collection_item=collection_item, *args, **kwargs)
  202. return wrapper
  203. def get_media_entry_by_id(controller):
  204. """
  205. Pass in a MediaEntry based off of a url component
  206. """
  207. @wraps(controller)
  208. def wrapper(request, *args, **kwargs):
  209. media = MediaEntry.query.filter_by(
  210. id=request.matchdict['media_id'],
  211. state=u'processed').first()
  212. # Still no media? Okay, 404.
  213. if not media:
  214. return render_404(request)
  215. given_username = request.matchdict.get('user')
  216. if given_username and (given_username != media.get_actor.username):
  217. return render_404(request)
  218. return controller(request, media=media, *args, **kwargs)
  219. return wrapper
  220. def get_workbench(func):
  221. """Decorator, passing in a workbench as kwarg which is cleaned up afterwards"""
  222. @wraps(func)
  223. def new_func(*args, **kwargs):
  224. with mgg.workbench_manager.create() as workbench:
  225. return func(*args, workbench=workbench, **kwargs)
  226. return new_func
  227. def allow_registration(controller):
  228. """ Decorator for if registration is enabled"""
  229. @wraps(controller)
  230. def wrapper(request, *args, **kwargs):
  231. if not mgg.app_config["allow_registration"]:
  232. messages.add_message(
  233. request,
  234. messages.WARNING,
  235. _('Sorry, registration is disabled on this instance.'))
  236. return redirect(request, "index")
  237. return controller(request, *args, **kwargs)
  238. return wrapper
  239. def allow_reporting(controller):
  240. """ Decorator for if reporting is enabled"""
  241. @wraps(controller)
  242. def wrapper(request, *args, **kwargs):
  243. if not mgg.app_config["allow_reporting"]:
  244. messages.add_message(
  245. request,
  246. messages.WARNING,
  247. _('Sorry, reporting is disabled on this instance.'))
  248. return redirect(request, 'index')
  249. return controller(request, *args, **kwargs)
  250. return wrapper
  251. def get_optional_media_comment_by_id(controller):
  252. """
  253. Pass in a Comment based off of a url component. Because of this decor-
  254. -ator's use in filing Reports, it has two valid outcomes.
  255. :returns The view function being wrapped with kwarg `comment` set to
  256. the Comment who's id is in the URL. If there is a
  257. comment id in the URL and if it is valid.
  258. :returns The view function being wrapped with kwarg `comment` set to
  259. None. If there is no comment id in the URL.
  260. :returns A 404 Error page, if there is a comment if in the URL and it
  261. is invalid.
  262. """
  263. @wraps(controller)
  264. def wrapper(request, *args, **kwargs):
  265. if 'comment' in request.matchdict:
  266. comment = Comment.query.filter_by(
  267. id=request.matchdict['comment']
  268. ).first()
  269. if comment is None:
  270. return render_404(request)
  271. return controller(request, comment=comment, *args, **kwargs)
  272. else:
  273. return controller(request, comment=None, *args, **kwargs)
  274. return wrapper
  275. def auth_enabled(controller):
  276. """Decorator for if an auth plugin is enabled"""
  277. @wraps(controller)
  278. def wrapper(request, *args, **kwargs):
  279. if not mgg.app.auth:
  280. messages.add_message(
  281. request,
  282. messages.WARNING,
  283. _('Sorry, authentication is disabled on this instance.'))
  284. return redirect(request, 'index')
  285. return controller(request, *args, **kwargs)
  286. return wrapper
  287. def require_admin_or_moderator_login(controller):
  288. """
  289. Require a login from an administrator or a moderator.
  290. """
  291. @wraps(controller)
  292. def new_controller_func(request, *args, **kwargs):
  293. if request.user and \
  294. not (request.user.has_privilege(u'admin')
  295. or request.user.has_privilege(u'moderator')):
  296. raise Forbidden()
  297. elif not request.user:
  298. next_url = urljoin(
  299. request.urlgen('mediagoblin.auth.login',
  300. qualified=True),
  301. request.url)
  302. return redirect(request, 'mediagoblin.auth.login',
  303. next=next_url)
  304. return controller(request, *args, **kwargs)
  305. return new_controller_func
  306. def oauth_required(controller):
  307. """ Used to wrap API endpoints where oauth is required """
  308. @wraps(controller)
  309. def wrapper(request, *args, **kwargs):
  310. data = request.headers
  311. authorization = decode_authorization_header(data)
  312. if authorization == dict():
  313. error = "Missing required parameter."
  314. return json_response({"error": error}, status=400)
  315. request_validator = GMGRequestValidator()
  316. resource_endpoint = ResourceEndpoint(request_validator)
  317. valid, r = resource_endpoint.validate_protected_resource_request(
  318. uri=request.url,
  319. http_method=request.method,
  320. body=request.data,
  321. headers=dict(request.headers),
  322. )
  323. if not valid:
  324. error = "Invalid oauth prarameter."
  325. return json_response({"error": error}, status=400)
  326. # Fill user if not already
  327. token = authorization[u"oauth_token"]
  328. request.access_token = AccessToken.query.filter_by(token=token).first()
  329. if request.access_token is not None and request.user is None:
  330. user_id = request.access_token.actor
  331. request.user = LocalUser.query.filter_by(id=user_id).first()
  332. return controller(request, *args, **kwargs)
  333. return wrapper