Ejemplo n.º 1
0
class RoleParentCollectionApi(BaseApiResource):
    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, role_id):
        role = req.context['role']
        parents = Role.find({
            'name': {
                '$in': role.parents,
            }
        })
        resp.media = [ p.to_dict() for p in parents ]

    @falcon.before(extract_params_object)
    @falcon.before(JsonSchema('''
    definitions:
      parent:
        type: string
        minLength: 24
        maxLength: 24
    
    anyOf:
      - type: array
        items:
          $ref: "#/definitions/parent"
      - $ref: "#/definitions/parent"
    '''))
    @falcon.before(permission_required)
    def on_post(self, req, resp, role_id):
        role = req.context['role']
        params = req.media
        if isinstance(params, str):
            params = [params]
        resp.media = []
        
        for p in params:
            if ObjectId(p) not in role.parents:
                role.parents.append(p)
        role.save()
        resp.media = [str(p) for p in role.parents]
        resp.status = falcon.HTTP_201
    
    @falcon.before(extract_params_object)
    @falcon.before(JsonSchema('''
    definitions:
      parent:
        type: string
        minLength: 24
        maxLength: 24
    
    type: array
    items:
      $ref: "#/definitions/parent"
    '''))
    @falcon.before(permission_required)
    def on_put(self, req, resp, role_id):
        role = req.context['role']
        params = req.media
        role.parents = params
        role.save()
        resp.media = [str(p) for p in role.parents]
Ejemplo n.º 2
0
class UserRoleCollectionApi(BaseApiResource):
    URL_PARAMS_SCHEMA = UrlParamsSchema('''
    type: object
    properties:
      user_id:
        type: string
        minLength: 24
        maxLength: 24
    ''')

    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, user_id):
        u = req.context['api_user']
        roles = u.get_roles()
        ret = [r.to_json_dict() for r in roles]
        for r in ret:
            r.pop('permissions_all')
        resp.media = ret

    @falcon.before(extract_params_object)
    @falcon.before(
        JsonSchema('''
    anyOf:
      - type: string
      - type: array
        items:
          type: string
    '''))
    @falcon.before(permission_required)
    def on_post(self, req, resp, user_id):
        u = req.context['api_user']
        role_names = req.media
        if isinstance(role_names, str):
            role_names = [role_names]
        u.update_one({'$addToSet': {
            'role_names': {
                '$each': role_names,
            }
        }})
        resp.media = role_names
        resp.status = falcon.HTTP_201

    @falcon.before(extract_params_object)
    @falcon.before(
        JsonSchema('''
    type: array
    items: { type: string }
    '''))
    @falcon.before(permission_required)
    def on_put(self, req, resp, user_id):
        u = req.context['api_user']
        role_names = req.media
        u.role_names = role_names
        u.save()
        resp.media = role_names
Ejemplo n.º 3
0
class RoleApi(BaseApiResource):
    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, role_name):
        role = req.context['role']
        resp.media = role.to_json_dict()

    @falcon.before(extract_params_object)
    @falcon.before(
        JsonSchema('''
    type: object
    properties:
      name: { type: string }
      description: { type: string }
    '''))
    @falcon.before(permission_required)
    def on_patch(self, req, resp, role_name):
        params = req.media
        role = req.context['role']
        for k, v in params.items():
            setattr(role, k, v)
        role.save()
        resp.media = role.to_json_dict()

    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_delete(self, req, resp, role_name):
        role = req.context['role']
        role.delete()
        resp.media = {
            'title': 'Success',
            'id': role_name,
        }
Ejemplo n.º 4
0
class UserLoginApi(BaseApiResource):
    def on_get(self, req, resp):
        session = req.context['session']
        permissions = session.permissions
        if session.user:
            username = session.user.username
        else:
            username = '******'
        resp.media = {
            'user_id': str(session.user_id),
            'username': username,
            'permissions': [p.to_json_dict() for p in permissions],
            'is_guest': session.is_guest(),
        }

    @falcon.before(
        JsonSchema('''
    type: object
    properties:
      username: { type: string }
      password: { type: string }
    required: [username, password]
    '''))
    def on_post(self, req, resp):
        params = req.media
        try:
            username_attempt = params['username']
            password_attempt = params['password']
        except KeyError:
            raise falcon.HTTPInvalidParam('HTTP param not valid')
        u = User.find_one({'username': username_attempt})
        if not u:
            raise falcon.HTTPUnauthorized('User %(username)s not exists' %
                                          params)
        if not password.verify_password(u.password, password_attempt):
            raise falcon.HTTPUnauthorized('Incorrect password')

        session = req.context['session']
        session.login(u)
        permissions = u.get_permissions()
        resp.media = {
            'title': 'Login Success',
            'user_id': str(u.id),
            'username': str(u.username),
            'permissions': [p.to_json_dict() for p in permissions],
        }

    @falcon.before(login_required)
    def on_delete(self, req, resp):
        session = req.context['session']
        session.logout()
        resp.unset_cookie('session_id')
        resp.media = {
            'title': 'Logout Success',
        }
Ejemplo n.º 5
0
class UserPermissionCollectionApi(BaseApiResource):
    URL_PARAMS_SCHEMA = UrlParamsSchema('''
    type: object
    properties:
      user_id:
        type: string
        minLength: 24
        maxLength: 24
    ''')

    @falcon.after(add_list_index)
    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, user_id):
        user = req.context['api_user']
        resp.media = [p.to_dict() for p in user.permissions]

    @falcon.after(add_list_index)
    @falcon.before(extract_params_object)
    @falcon.before(
        JsonSchema('''
    definitions:
      permission:
        type: object
        properties:
          allow: { type: boolean }
          resource: { type: string }
          actions:
            type: array
            items: { type: string }
            pattern: (GET|POST|PUT|PATCH|DELETE)
        required: [allow, resource, actions]
    
    anyOf:
      - type: array
        items:
          $ref: "#/definitions/permission"
      - $ref: "#/definitions/permission"
    '''))
    @falcon.before(permission_required)
    def on_post(self, req, resp, user_id):
        user = req.context['api_user']
        params = req.media
        if isinstance(params, dict):
            params = [params]
        permissions = []
        for p in params:
            permission = Permission(allow=p['allow'],
                                    resource=p['resource'],
                                    actions=p['actions'])
            if permission not in user.permissions:
                user.permissions.append(permission)
        user.save()
        resp.media = [p.to_dict() for p in user.permissions]
Ejemplo n.º 6
0
class RolePermissionApi(BaseApiResource):
    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, role_id, permission_id):
        role = req.context['role']
        permission = req.context['permission']
        resp.media = permission.to_dict()
    
    @falcon.before(extract_params_object)
    @falcon.before(JsonSchema('''
    type: object
    properties:
      allow: { type: boolean }
      resource: { type: string }
      actions:
        type: array
        items: { type: string }
        pattern: (GET|POST|PUT|PATCH|DELETE)
    required: [allow, resource, actions]
    '''))
    @falcon.before(permission_required)
    def on_put(self, req, resp, role_id, permission_id):
        role = req.context['role']
        params = req.media
        role.permissions[permission_id] = Permission(
            allow=params['allow'],
            resource=params['resource'],
            actions=[
                Permission.Action.num_to_name()[a] for a in params['actions']
            ]
        )
        role.save()
        permission = role.permissions[permission_id]
        resp.media = permission.to_dict()

    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_delete(self, req, resp, role_id, permission_id):
        role = req.context['role']
        role.permissions.pop(permission_id)
        role.save()
        resp.media = {
            'title': 'Success',
            'role_name': role.name,
            'permission_id': permission_id,
        }
Ejemplo n.º 7
0
class UserCollectionApi(BaseApiResource):
    @falcon.before(permission_required)
    def on_get(self, req, resp):
        all_users = User.find({})
        resp.media = [u.to_json_dict() for u in all_users]

    @falcon.before(
        JsonSchema('''
    type: object
    properties:
      username: { type: string }
      password: { type: string }
      email:
        type: string
        format: email
      phone_number: { type: string }
    required: [username, password, email, phone_number]
    '''))
    def on_post(self, req, resp):
        time.sleep(1)  # simulate server delay
        params = req.media
        try:
            username = params['username']
            pwd = params['password']
            email = params['email']
            phone = params['phone_number']
        except KeyError:
            raise falcon.HTTPBadRequest('Bad input body')

        e_password = password.encrypt_password(pwd)
        try:
            u = User(
                username=username,
                password=e_password,
                email=email,
                phone_number=phone,
            )
            u.save()
            resp.status = falcon.HTTP_201
            resp.media = {
                'id': str(u.id),
                'username': str(u.username),
            }
        except dberr.NotUniqueError as e:
            raise falcon.HTTPBadRequest('User already exists')
Ejemplo n.º 8
0
class RoleApi(BaseApiResource):
    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, role_id):
        print("----------------")
        role = Role.by_id(role_id)
        if role:
            resp.media = role.to_dict()
        else:
            raise falcon.HTTPNotFound(description="Role不存在!")

    @falcon.before(extract_params_object)
    @falcon.before(JsonSchema('''
    type: object
    properties:
      name: { type: string }
      description: { type: string }
    '''))
    @falcon.before(permission_required)
    def on_patch(self, req, resp, role_id):
        params = req.media
        role = req.context['role']
        for k, v in params.items():
            setattr(role, k, v)
        role.save()
        resp.media = role.to_dict()

    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_delete(self, req, resp, role_id):
        role = req.context['role']
        role.delete()
        resp.media = {
            'title': 'Success',
            'id': role_id,
        }
Ejemplo n.º 9
0
class RoleCollectionApi(BaseApiResource):
    @falcon.before(permission_required)
    def on_get(self, req, resp):
        roles = Role.find({})
        resp.media = [{
            'id': str(r.id),
            'name': r.name,
            'description': r.description,
        } for r in roles]

    @falcon.before(JsonSchema('''
    definitions:
      permission:
        type: object
        properties:
          allow: { type: boolean }
          resource: { type: string }
          actions:
            type: array
            items: { type: string }
            pattern: (GET|POST|PUT|PATCH|DELETE)
        required: [allow, resource, actions]
      role:
        type: object
        properties:
          name: { type: string }
          description: { type: string }
          parents:
            type: array
            items:
              type: string
              minLength: 24
              maxLength: 24
          permissions:
            type: array
            items:
              $ref: "#/definitions/permission"
        required: [name, permissions]
    
    anyOf:
      - $ref: "#/definitions/role"
      - type: array
        items:
          $ref: "#/definitions/role"
    '''))
    @falcon.before(permission_required)
    def on_post(self, req, resp):
        params = req.media
        if isinstance(params, dict):
            params = [params]
        roles = []
        for param in params:
            permissions = []
            for p in param['permissions']:
                actions = [Permission.Action.name_to_num(
                    a.upper()
                ) for a in p['actions']]
                permissions.append(Permission(
                    resource=p['resource'],
                    allow=p['allow'],
                    actions=actions,
                ))
            roles.append(Role(
                name=param['name'],
                description=param.get('description'),
                parents=param.get('parents', []),
                permissions=permissions,
            ))
        try:
            with Role.bulk() as bulk_context:
                for r in roles:
                    r.bulk_save(bulk_context)
        except dberr.NotUniqueError as e:
            raise falcon.HTTPBadRequest(
                'Role name already exists.'
            )
        ret_value = [r.to_dict() for r in roles]
        if len(ret_value) == 0:
            resp.media = ret_value[0]
        else:
            resp.media = ret_value
        resp.status = falcon.HTTP_201
Ejemplo n.º 10
0
class RolePermissionCollectionApi(BaseApiResource):
    @falcon.after(add_list_index)
    @falcon.before(extract_params_object)
    @falcon.before(permission_required)
    def on_get(self, req, resp, role_id):
        role = req.context['role']
        resp.media = [p.to_dict() for p in role.permissions]

    @falcon.after(add_list_index)
    @falcon.before(extract_params_object)
    @falcon.before(JsonSchema('''
    definitions:
      permission:
        type: object
        properties:
          allow: { type: boolean }
          resource: { type: string }
          actions:
            type: array
            items: { type: string }
            pattern: (GET|POST|PUT|PATCH|DELETE)
        required: [allow, resource, actions]
    
    anyOf:
      - type: array
        items:
          $ref: "#/definitions/permission"
      - $ref: "#/definitions/permission"
    '''))
    @falcon.before(permission_required)
    def on_post(self, req, resp, role_id):
        role = req.context['role']
        params = req.media
        if isinstance(params, dict):
            params = [params]
        resp.media = []
        permission_resources = [p.resource for p in role.permissions]
        for p in params:
            if p['resource'] not in permission_resources:
                permission = Permission(
                    allow=p['allow'],
                    resource=p['resource'],
                    actions=[
                        Permission.Action.name_to_num(a)
                            for a in p['actions']
                    ]
                )
                role.permissions.append(permission)
                permission_resources.append(p)
        role.set(permissions=role.permissions)
        resp.media = [p.to_dict() for p in role.permissions]
        resp.status = falcon.HTTP_201

    @falcon.before(extract_params_object)
    @falcon.before(JsonSchema('''
    definitions:
      permission:
        type: object
        properties:
          allow: { type: boolean }
          resource: { type: string }
          actions:
            type: array
            items: { type: string }
            pattern: (GET|POST|PUT|PATCH|DELETE)
        required: [allow, resource, actions]
    
    type: array
    items:
      $ref: "#/definitions/permission"
    '''))
    @falcon.before(permission_required)
    def on_put(self, req, resp, role_id):
        role = req.context['role']
        params = req.media
        resp.media = []
        permissions = []
        for p in params:
            permission = Permission(
                allow=p['allow'],
                resource=p['resource'],
                actions=[
                    Permission.Action.name_to_num(a)
                        for a in p['actions']
                ]
            )
            if permission in role.permissions:
                raise falcon.HTTPBadRequest(
                    'Duplicate permission %s' % p
                )
            permissions.append(permission)
        role.permissions = permissions
        role.save()
        resp.media = [ p.to_dict() for p in role.permissions ]