base.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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-24 14:56:50 (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. print(check)
  36. if check:
  37. return self.callback()
  38. return func(*args, **kwargs)
  39. return decorator
  40. def callback(self):
  41. abort(403)
  42. @identity_loaded.connect_via(app)
  43. def on_identity_loaded(sender, identity):
  44. '''基础权限'''
  45. identity.user = current_user
  46. if hasattr(current_user, 'id'):
  47. identity.provides.add(UserNeed(current_user.id))
  48. if hasattr(current_user, 'roles'):
  49. for role in current_user.roles:
  50. identity.provides.add(RoleNeed(role.name))
  51. if hasattr(current_user, 'is_superuser'):
  52. if current_user.is_superuser:
  53. identity.provides.add(RoleNeed('super'))
  54. if hasattr(current_user, 'topics'):
  55. for topic in current_user.topics:
  56. identity.provides.add(EditTopicNeed(topic.id))
  57. if hasattr(current_user, 'collects'):
  58. for collect in current_user.collects:
  59. identity.provides.add(GetCollect(collect.id))
  60. identity.provides.add(PostCollect(collect.id))
  61. # if hasattr(current_user, 'likes'):
  62. # for like in current_user.likes:
  63. # identity.provides.add(GetLike(like.id))