コード例 #1
0
class DefaultUserLoaderUnitTests(unittest.TestCase):

    def setUp(self):
        self.rbac = RBAC()

    def test_default_user_loader(self):
        self.assertEqual(self.rbac._user_loader(), login_user)
コード例 #2
0
ファイル: test_rbac.py プロジェクト: shonenada/flask-rbac
class DefaultUserLoaderUnitTests(unittest.TestCase):

    def setUp(self):
        self.rbac = RBAC()

    def test_default_user_loader(self):
        self.assertEqual(self.rbac._user_loader(), login_user)
コード例 #3
0
    def setUp(self):
        self.rbac = RBAC()

        @self.rbac.as_role_model
        class RoleModel(RoleMixin):
            pass

        @self.rbac.as_user_model
        class UserModel(UserMixin):
            pass

        self.rm = RoleModel
        self.um = UserModel
コード例 #4
0
def makeapp(with_factory, use_white, before_decorator, after_decorator):
    global current_user
    app = Flask(__name__)
    app.debug = True

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @app.route('/')
    @after_decorator
    @rbac.allow(roles=['everyone'], methods=['GET'])
    @before_decorator
    def index():
        return Response('index')

    @app.route('/a')
    @after_decorator
    @rbac.allow(roles=['special'], methods=['GET'])
    @before_decorator
    def a():
        return Response('Hello')

    @app.route('/b', methods=['GET', 'POST'])
    @after_decorator
    @rbac.allow(roles=['logged_role'], methods=['GET'])
    @rbac.allow(roles=['staff_role', 'special'], methods=['POST'])
    @before_decorator
    def b():
        return Response('Hello from /b')

    @app.route('/c')
    @after_decorator
    @rbac.allow(roles=['everyone'], methods=['GET'])
    @rbac.deny(roles=['logged_role'], methods=['GET'], with_children=False)
    @rbac.allow(roles=['staff_role'], methods=['GET'])
    @before_decorator
    def c():
        return Response('Hello from /c')

    @app.route('/d')
    @after_decorator
    @rbac.deny(roles=['everyone'], methods=['GET'])
    @before_decorator
    def d():
        return Response('Hello from /d')

    @app.route('/e')
    @after_decorator
    @rbac.deny(roles=['everyone'], methods=['GET'], with_children=True)
    @before_decorator
    def e():
        return Response('Hello from /e')

    @app.route('/f', methods=['POST'])
    @after_decorator
    @rbac.deny(roles=['logged_role'], methods=['POST'])
    @before_decorator
    def f():
        return Response('Hello from /f')

    @app.route('/g', methods=['GET'])
    @after_decorator
    @rbac.exempt
    @before_decorator
    def g():
        return Response('Hello from /g')

    @app.route('/h', methods=['GET'])
    @after_decorator
    @rbac.allow(['anonymous'], methods=['GET'], with_children=False)
    @before_decorator
    def h():
        return Response('Hello from /h')

    @app.route('/i', methods=['GET'])
    @after_decorator
    @rbac.allow(['nonexistent'], methods=['GET'], with_children=False)
    @before_decorator
    def i():
        return Response('Hello from /i')

    @app.route('/j', methods=['GET'])
    @after_decorator
    @rbac.deny(['nonexistent'], methods=['GET'], with_children=False)
    @before_decorator
    def j():
        return Response('Hello from /j')

    return app
コード例 #5
0
ファイル: test_rbac.py プロジェクト: shonenada/flask-rbac
def makeapp(with_factory, use_white, before_decorator, after_decorator):
    global current_user
    app = Flask(__name__)
    app.debug = True

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @app.route('/')
    @after_decorator
    @rbac.allow(roles=['everyone'], methods=['GET'])
    @before_decorator
    def index():
        return Response('index')

    @app.route('/a')
    @after_decorator
    @rbac.allow(roles=['special'], methods=['GET'])
    @before_decorator
    def a():
        return Response('Hello')

    @app.route('/b', methods=['GET', 'POST'])
    @after_decorator
    @rbac.allow(roles=['logged_role'], methods=['GET'])
    @rbac.allow(roles=['staff_role', 'special'], methods=['POST'])
    @before_decorator
    def b():
        return Response('Hello from /b')

    @app.route('/c')
    @after_decorator
    @rbac.allow(roles=['everyone'], methods=['GET'])
    @rbac.deny(roles=['logged_role'], methods=['GET'], with_children=False)
    @rbac.allow(roles=['staff_role'], methods=['GET'])
    @before_decorator
    def c():
        return Response('Hello from /c')

    @app.route('/d')
    @after_decorator
    @rbac.deny(roles=['everyone'], methods=['GET'])
    @before_decorator
    def d():
        return Response('Hello from /d')

    @app.route('/e')
    @after_decorator
    @rbac.deny(roles=['everyone'], methods=['GET'], with_children=True)
    @before_decorator
    def e():
        return Response('Hello from /e')

    @app.route('/f', methods=['POST'])
    @after_decorator
    @rbac.deny(roles=['logged_role'], methods=['POST'])
    @before_decorator
    def f():
        return Response('Hello from /f')
    
    @app.route('/g', methods=['GET'])
    @after_decorator
    @rbac.exempt
    @before_decorator
    def g():
        return Response('Hello from /g')

    @app.route('/h', methods=['GET'])
    @after_decorator
    @rbac.allow(['anonymous'], methods=['GET'], with_children=False)
    @before_decorator
    def h():
        return Response('Hello from /h')

    return app
コード例 #6
0
ファイル: test_rbac.py プロジェクト: shonenada/flask-rbac
 def setUp(self):
     self.rbac = RBAC()
コード例 #7
0
def createapp(with_factory=False, use_white=True):
    global current_user
    app = Flask(__name__)

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @app.route('/')
    @rbac.allow(roles=['everyone'], methods=['GET'])
    def index():
        return Response('index')

    @app.route('/a')
    @rbac.allow(roles=['special'], methods=['GET'])
    def a():
        return Response('Hello')

    @app.route('/b', methods=['GET', 'POST'])
    @rbac.allow(roles=['logged_role'], methods=['GET'])
    @rbac.allow(roles=['staff_role', 'special'], methods=['POST'])
    def b():
        return Response('Hello from /b')

    @app.route('/c')
    @rbac.allow(roles=['everyone'], methods=['GET'])
    @rbac.deny(roles=['logged_role'], methods=['GET'], with_children=False)
    @rbac.allow(roles=['staff_role'], methods=['GET'])
    def c():
        return Response('Hello from /c')

    @app.route('/d')
    @rbac.deny(roles=['everyone'], methods=['GET'])
    def d():
        return Response('Hello from /d')

    @app.route('/e')
    @rbac.deny(roles=['everyone'], methods=['GET'], with_children=True)
    def e():
        return Response('Hello from /e')

    @app.route('/f', methods=['POST'])
    @rbac.deny(roles=['logged_role'], methods=['POST'])
    def f():
        return Response('Hello from /f')

    @app.route('/g', methods=['GET'])
    @rbac.exempt
    def g():
        return Response('Hello from /g')

    @app.route('/h', methods=['GET'])
    @rbac.allow(['anonymous'], methods=['GET'], with_children=False)
    def h():
        return Response('Hello from /h')

    app.run(port=9999, debug=True)
    return app
コード例 #8
0
def start_app(with_factory=False, use_white=True):
    global current_user
    app = Flask(__name__)

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    @app.route('/login/<string:name>', methods=['GET', 'POST'])
    @rbac.allow(['Q'], methods=['GET', 'POST'])
    def login(name):
        try:
            for i in user_dict.keys():
                if i == name:
                    global current_user
                    current_user = user_dict[i]
                    return 'signed-in'

            else:
                return 'Not defined'

        except Exception as ex:
            print(ex)

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    def has_permissions(*permission):
        def deco(f):
            @wraps(f)
            def wrap(*args, **kwargs):
                if not current_user:
                    return 'not current user'

                print(permission)
                for i in current_user.user_permission:
                    for j in permission:
                        if i == j:
                            return f(*args, **kwargs)

                else:
                    return 'Not Authorized'

            return wrap

        return deco

    @app.route('/create')
    @rbac.allow(roles=['P', 'Q'], methods=['GET'])
    @has_permissions('read', 'access')
    def create_user():
        return Response('Teacher Portal: \n{}'.format(current_user))

    app.run(port=9988, debug=True)
    return app
コード例 #9
0
from flask import Flask, Response, g, current_app
from flask_restx import Api, fields, Resource
from flask_rbac import RBAC, UserMixin, RoleMixin
from functools import wraps

app = Flask(__name__)
app.config['RBAC_USE_WHITE'] = True

rbac = RBAC(app)
api = Api(app,
          version='1.0',
          title='Rbac',
          description='RBAC POC',
          security=rbac.allow(roles=['Q', 'P'], methods=['PUT']))

ns = api.namespace('rbac', description="role based access control")
data = api.model('rbac_info', {'user_id': fields.String('user_id')})


class Role(RoleMixin):
    def __init__(self, name, user_permission):
        self.user_permission = user_permission
        super(Role, self).__init__(name)

    def __repr__(self):
        return 'Role: {} Permission: {}'.format(self.name,
                                                self.user_permission)

    def get_permission(self):
        return self.user_permission
コード例 #10
0
from flask_rbac import RBAC
# from flask_principal import Principal
from flask_bootstrap import Bootstrap
# from flask_restful import Api
from flask_restless import APIManager
from flask_rbac import RBAC

bcrypt = Bcrypt()
csrf_protect = CSRFProtect()
login_manager = LoginManager()
db = SQLAlchemy()
migrate = Migrate()
cache = Cache()
debug_toolbar = DebugToolbarExtension()
# redis_store = FlaskRedis()

rbac = RBAC()
# principal = Principal()
bootstrap = Bootstrap()
# api = Api(decorators=[csrf_protect.exempt])
apiManager = APIManager(flask_sqlalchemy_db=db,
                        decorators=[csrf_protect.exempt])

login_manager.session_protection = 'basic'

#自动注册
login_manager.login_view = 'auth.login'
login_manager.login_message = "请登录后访问该页面."
login_manager.refresh_view = 'auth.login'
コード例 #11
0
def start_app(with_factory=False, use_white=True):
    global current_user
    app = Flask(__name__)

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    def has_permissions(*permission):
        def deco(f):
            @wraps(f)
            def wrap(*args, **kwargs):
                if not current_user:
                    return 'not current user'

                for role in current_user.roles:
                    for roles_perms in role.get_permission():
                        for value in permission:
                            if value == roles_perms:
                                return f(*args, **kwargs)

                else:
                    return 'Not Authorized'

            return wrap

        return deco

    @app.url_value_preprocessor
    def br(endpoint, values):
        for id in user_dict.keys():
            if id == values['user_id']:
                global current_user
                current_user = user_dict[id]
                break
        else:
            raise Exception('User not registered')

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @app.route('/create/<string:user_id>')
    @rbac.allow(roles=['Employee', 'Manager'], methods=['GET'])
    @has_permissions('read', 'write')
    def create_user(user_id):
        return Response('Company Portal: \nUserName:{} {}'.format(
            user_id, current_user))

    app.run(port=9888, debug=True)
    return app
コード例 #12
0
from flask import Flask, Response
from flask_rbac import RBAC, RoleMixin, UserMixin

app = Flask(__name__)
app.config['RBAC_USE_WHITE'] = True

rbac = RBAC(app)


@rbac.as_role_model
class Role(RoleMixin):
    def __repr__(self):
        return '<Role %s>' % self.name


@rbac.as_user_model
class User(UserMixin):
    def __repr__(self):
        return '<User %s>' % self.roles


everyone = Role('everyone')
admin = Role('admin')
staff_role = Role('staff_role')
other_role = Role('other_role')
special = Role('special')

admin.add_parent(everyone)
staff_role.add_parents(everyone, admin)

anonymous = User(roles=[everyone])
コード例 #13
0
def start_app(with_factory=False, use_white=True):
    global current_user
    app = Flask(__name__)

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    @app.route('/login/<string:name>', methods=['GET', 'POST'])
    @rbac.allow(['start'], methods=['GET', 'POST'])
    def login(name):
        try:
            for i in user_dict.keys():
                if i == name:
                    global current_user
                    current_user = user_dict[i]
                    return 'signed-in'

            else:
                return 'Not defined'

        except Exception as ex:
            print(ex)

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @app.route('/teacher')
    @rbac.allow(roles=['teacher'], methods=['GET', 'POST'])
    def teachers_portal():
        return Response('Teacher Portal: \n{}'.format(current_user))

    @app.route('/student')
    @rbac.allow(roles=['student'], methods=['GET', 'POST'])
    def student_portal():
        return Response('Student Portal:\n{}'.format(current_user.name))

    @app.route('/accounts', methods=['GET', 'POST'])
    @rbac.allow(roles=['accounts'], methods=['GET'])
    def accounts_portal():
        return Response('Accounts Department Portal:\n{}'.format(
            current_user.name))

    @app.route('/acc', methods=['GET', 'POST'])
    @rbac.allow(roles=['accounts'], methods=['GET'], with_children=False)
    @rbac.deny(roles=['hr'], methods=['POST'])
    def accounts_user_portal():
        return Response('Accounts Department Personal Portal:\n{}'.format(
            current_user.name))

    @app.route('/hr')
    @rbac.allow(roles=['hr'], methods=['GET', 'PUT'])
    @rbac.deny(roles=['teacher', 'student'],
               methods=['GET'],
               with_children=False)
    def hr_portal():
        return Response('HR Portal:\n{}'.format(current_user.name))

    @app.route('/maintain')
    @rbac.allow(roles=['maintenance'], methods=['GET', 'PUT', 'POST'])
    def maintenance_portal():
        return Response('Maintenance Portal:\n{}'.format(current_user.name))

    @app.route('/dean', methods=['POST'])
    @rbac.allow(roles=['dean'], methods=['GET', 'POST', 'PUT', 'DELETE'])
    @rbac.deny(roles=['teacher', 'accounts', 'hr'],
               methods=['POST', 'DELETE', 'PUT'])
    def dean_portal():
        return Response('Dean Portal:\n{}'.format(current_user.name))

    @app.route('/common', methods=['GET'])
    @rbac.exempt
    def commom_portal():
        return Response('Common Portal:\n{}'.format(current_user.name))

    @app.route('/IT', methods=['GET'])
    @rbac.allow(['IT', 'dean'],
                methods=['GET', 'ACCESS_H'],
                with_children=False)
    def it_portal():
        print(rbac.has_permission('ACCESS_H', 'it_portal'))
        return Response('IT Portal:\n{}'.format(current_user.name))

    @app.route('/exam', methods=['GET'])
    @rbac.allow(['teacher'], methods=['ACCESS_H'], with_children=False)
    def exam():
        return Response('EXAM Portal:\n{}'.format(current_user.name))

    app.run(port=9999, debug=True)
    return app
コード例 #14
0
ファイル: app.py プロジェクト: aurigadl/apiflask
import jwt
from flask import Flask, request, jsonify, abort, session, Response
from werkzeug.security import generate_password_hash, check_password_hash

import asklibs.sessionPickle as newSession
from flask_sqlalchemy import SQLAlchemy
from flask_rbac import RBAC, RoleMixin, UserMixin

# Configuration
current_path = os.path.dirname(__file__)
client_path = os.path.abspath(os.path.join(current_path, '..', '..', 'client'))

app = Flask(__name__)
app.config.from_object('config')
rbac = RBAC(app)
db = SQLAlchemy(app)


def init_db():
    """Initializes the database."""
    if os.path.exists('app.db'):
        os.remove('app.db')
    db.create_all()
    new_role_basic = Role('candidate', 'They may present test')
    new_role_admon = Role('admon', 'They may to do anything')
    new_user_admon = User(email='admonUser', password='******', display_name='User admin system', active=True)
    new_user_admon.add_role(new_role_admon)
    db.session.add(new_role_basic)
    db.session.add(new_role_admon)
    db.session.add(new_user_admon)
コード例 #15
0
ファイル: __init__.py プロジェクト: manuelr417/RumboEx
engine = create_engine(pg_config['url'], echo=True)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
#Session = sessionmaker(bind=engine) COMMENTED THIS ON MARCH 24 !!!!!!!!!!!!!!!!!!!!!!
#Session.configure(bind=engine)
#session = Session()

# If this imports are done before a circle dependency is created and the app will not run.
from RumboEx.model.role import Role
from RumboEx.model.user import User

# NPI
# jwt = JWTManager(app)

# Starting RBAC
rbac = RBAC()
rbac.init_app(app)
rbac.set_user_loader(lambda: current_user)
rbac.set_user_model(User)
rbac.set_role_model(Role)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/login'


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

コード例 #16
0
 def setUp(self):
     self.rbac = RBAC()
コード例 #17
0
def createapp(with_factory=False, use_white=True):
    global current_user
    app = Flask(__name__)

    if use_white:
        app.config['RBAC_USE_WHITE'] = True
    else:
        app.config['RBAC_USE_WHITE'] = False

    if with_factory:
        rbac = RBAC()
        rbac.init_app(app)
    else:
        rbac = RBAC(app)

    @app.route('/signin/<string:name>', methods=['GET', 'POST'])
    @rbac.allow(['start'], methods=['GET', 'POST'])
    def signin(name):
        try:
            for i in user_dict.keys():
                if i == name:
                    global current_user
                    current_user = user_dict[i]
                    return 'signed-in'

                else:
                    return 'Not defined'

        except Exception as ex:
            print(ex)

    rbac.set_user_loader(lambda: current_user)
    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @app.route('/')
    @rbac.allow(roles=['everyone'], methods=['GET'])
    def index():
        return Response('index {}'.format(current_user.name))

    @app.route('/a')
    @rbac.allow(roles=['special'], methods=['GET'])
    def a():
        return Response('Hello from {} in /a'.format(current_user.name))

    @app.route('/b', methods=['GET', 'POST'])
    @rbac.allow(roles=['admin'], methods=['GET'])
    @rbac.allow(roles=['staff_role', 'special'], methods=['POST'])
    def b():
        return Response('Hello from {} in /b'.format(current_user.name))

    @app.route('/c')
    @rbac.allow(roles=['everyone'], methods=['GET'])
    @rbac.deny(roles=['admin'], methods=['GET'], with_children=False)
    @rbac.allow(roles=['staff_role'], methods=['GET'])
    def c():
        return Response('Hello from {} in /c'.format(current_user.name))

    @app.route('/d')
    @rbac.deny(roles=['everyone'], methods=['GET'])
    def d():
        return Response('Hello from {} in /d'.format(current_user.name))

    @app.route('/e')
    @rbac.deny(roles=['everyone'], methods=['GET'], with_children=True)
    def e():
        return Response('Hello from {} in /e'.format(current_user.name))

    @app.route('/f', methods=['POST'])
    @rbac.deny(roles=['admin'], methods=['POST'])
    def f():
        return Response('Hello from {} in /f'.format(current_user.name))

    @app.route('/g', methods=['GET'])
    @rbac.exempt
    def g():
        return Response('Hello from {} in /g'.format(current_user.name))

    @app.route('/h', methods=['GET'])
    @rbac.allow(['everyone'], methods=['GET'], with_children=False)
    def h():
        return Response('Hello from {} in /h'.format(current_user.name))

    app.run(port=9999, debug=True)
    return app