base.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/env python
  2. # -*- coding=UTF-8 -*-
  3. # **************************************************************************
  4. # Copyright © 2016 jianglin
  5. # File Name: base.py
  6. # Author: jianglin
  7. # Email: xiyang0807@gmail.com
  8. # Created: 2016-07-16 15:25:16 (CST)
  9. # Last Update:星期一 2016-7-25 15:7:1 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from flask_principal import RoleNeed, UserNeed, identity_loaded
  14. from flask_login import current_user
  15. from flask import request, abort
  16. from maple import app
  17. from functools import wraps
  18. from .permission import EditTopicNeed, GetCollect, PostCollect
  19. class RestBase(object):
  20. decorators = ()
  21. def __call__(self, func):
  22. f = self.method(func)
  23. if self.decorators:
  24. for dec in reversed(self.decorators):
  25. f = dec(f)
  26. return f
  27. def method(self, func):
  28. @wraps(func)
  29. def decorator(*args, **kwargs):
  30. meth = getattr(self, request.method.lower(), None)
  31. if request.method == 'HEAD':
  32. meth = getattr(self, 'get', None)
  33. if meth is not None:
  34. check = meth(*args, **kwargs)
  35. if check:
  36. return self.callback()
  37. return func(*args, **kwargs)
  38. return decorator
  39. def callback(self):
  40. abort(403)
  41. @identity_loaded.connect_via(app)
  42. def on_identity_loaded(sender, identity):
  43. '''基础权限'''
  44. identity.user = current_user
  45. if hasattr(current_user, 'id'):
  46. identity.provides.add(UserNeed(current_user.id))
  47. if hasattr(current_user, 'roles'):
  48. for role in current_user.roles:
  49. identity.provides.add(RoleNeed(role.name))
  50. if hasattr(current_user, 'is_superuser'):
  51. if current_user.is_superuser:
  52. identity.provides.add(RoleNeed('super'))
  53. if hasattr(current_user, 'topics'):
  54. for topic in current_user.topics:
  55. identity.provides.add(EditTopicNeed(topic.id))
  56. if hasattr(current_user, 'collects'):
  57. for collect in current_user.collects:
  58. identity.provides.add(GetCollect(collect.id))
  59. identity.provides.add(PostCollect(collect.id))
  60. # if hasattr(current_user, 'likes'):
  61. # for like in current_user.likes:
  62. # identity.provides.add(GetLike(like.id))