decorators.py 14 KB

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