Exemple #1
0
 def detach_volume(self, provider, **kwargs):
     try:
         conn = self.connect(provider)
         return None
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
def api_invalid_response(req):
    """
    This is a default handler for OAuth2Provider, which raises abort exception
    with error message in JSON format.
    """
    # pylint: disable=unused-argument
    api.abort(code=http_exceptions.Unauthorized.code)
    def delete(self, args, team_id):
        """
        Remove a member from a team.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                user_id = args['user_id']
                team_member = TeamMember.query.filter_by(team=team, user_id=user_id).one()
                if team_member is None:
                    abort(
                        code=http_exceptions.NotFound.code,
                        message="User with id %d does not exist" % user_id
                    )
                db.session.delete(team_member)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(
                code=http_exceptions.Conflict.code,
                message="Could not update team details."
            )

        return team
Exemple #4
0
    def get_server(self, provider, name_or_id):
        try:
            conn = self.connect(provider)
            container = conn.containers.get(name_or_id)
            server = types.SimpleNamespace()
            server.id = container.attrs['Id']
            server.created = container.attrs['Created']
            server.status = container.attrs['State']['Status']
            if container.attrs['State']['Running'] == True:
                server.power_state = 1
            elif container.attrs['State']['Paused'] == True:
                server.power_state = 3
            elif container.attrs['State']['Restarting'] == True:
                server.power_state = 4
            elif container.attrs['State']['OOMKilled'] == True:
                server.power_state = 6
            elif container.attrs['State']['Dead'] == True:
                server.power_state = 7
            else:
                server.power_state = 0

            return server
        except Exception as e:
            log.info("Exception: %s", e)
            abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #5
0
def api_invalid_response(req):
    """
    This is a default handler for OAuth2Provider, which raises abort exception
    with error message in JSON format.
    """
    # pylint: disable=unused-argument
    api.abort(code=http_exceptions.Unauthorized.code)
    def patch(self, args, user_id):
        """
        Patch user details by ID.
        """
        user = User.query.get_or_404(user_id)

        with permissions.OwnerRolePermission(obj=user):
            with permissions.WriteAccessPermission():
                state = {'current_password': None}

                for operation in args['body']:
                    if not self._process_patch_operation(operation, user=user, state=state):
                        log.info("User patching has ignored unknown operation %s", operation)

                # pylint: disable=no-member
                try:
                    db.session.merge(user)
                    db.session.commit()
                except sqlalchemy.exc.IntegrityError:
                    db.session.rollback()
                    # TODO: handle errors better
                    abort(
                        code=http_exceptions.Conflict.code,
                        message="Could not update user details."
                    )
        return user
def fuzzy_search_pageIndex(keyword, pageIndex):

    # Http请求头设置
    timespan = str(int(time.time()))
    token = appkey + timespan + seckey
    hl = hashlib.md5()
    hl.update(token.encode(encoding=encode))
    token = hl.hexdigest().upper()
    log.debug('MD5加密后为 :' + token)

    # 设置请求Url-请自行设置Url
    reqInterNme = 'http://api.qichacha.com/ECIV4/Search'
    paramStr = 'keyword=' + keyword + '&pageIndex=' + str(pageIndex)
    url = reqInterNme + '?key=' + appkey + '&' + paramStr
    headers = {'Token': token, 'Timespan': timespan}
    response = requests.get(url, headers=headers)

    # 结果返回处理
    log.debug(response.status_code)
    raw_str = response.content.decode()
    log.debug(raw_str)

    result = json.loads(raw_str)

    if result['Status'] != '200':
        api.abort(
            500,
            "Qichacha doesn't return results correctly. The error code is {}".format(
                result['Status']
            ),
        )
    log.debug(result['Result'])
    return result['Result'], result['Paging']['TotalRecords']
Exemple #8
0
 def list_servers(self, provider, **kwargs):
     try:
         conn = self.connect(provider)
         return conn.containers.list()
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #9
0
def api_invalid_response(req):
    """
    This is a default handler for OAuth2Provider, which raises abort exception
    with error message in JSON format.
    """
    # pylint: disable=unused-argument
    api.abort(code=HTTPStatus.UNAUTHORIZED.value)
    def post(self, args, team_id):
        """
        Add a new member to a team.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                user_id = args.pop('user_id')
                user = User.query.get(user_id)
                if user is None:
                    abort(
                        code=http_exceptions.NotFound.code,
                        message="User with id %d does not exist" % user_id
                    )
                team_member = TeamMember(team=team, user=user, **args)
                db.session.add(team_member)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(
                code=http_exceptions.Conflict.code,
                message="Could not update team details."
            )

        return None
    def post(self, args):
        """
        Create a new user.
        """
        # Check reCAPTCHA if necessary
        recaptcha_key = args.pop('recaptcha_key', None)
        captcha_is_valid = False
        if not recaptcha_key:
            no_captcha_permission = permissions.AdminRolePermission()
            if no_captcha_permission.check():
                captcha_is_valid = True
        elif recaptcha_key == 'secret_key':
            captcha_is_valid = True

        if not captcha_is_valid:
            abort(code=http_exceptions.Forbidden.code, message="CAPTCHA key is incorrect.")

        new_user = User(**args)

        # pylint: disable=no-member
        db.session.add(new_user)
        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(code=http_exceptions.Conflict.code, message="Could not create a new user.")

        return new_user
Exemple #12
0
    def get(self, target, path):
        params = {}
        params.update(request.args)
        params.update(request.form)

        request_func = current_app.edm.get_passthrough
        passthrough_kwargs = {'params': params}

        response = _request_passthrough(target, path, request_func,
                                        passthrough_kwargs)

        # private means cannot be read other than admin
        ####@edm_configuration.login_required(oauth_scopes=['configuration:write'])  TODO somehow need to *allow* private if has auth!!!
        data = response.json()
        if (response.ok and 'response' in data
                and 'private' in data['response']
                and data['response']['private']):
            abort(code=HTTPStatus.FORBIDDEN, message='unavailable')

        if path == '__bundle_setup':
            data = response.json()
            data['response']['configuration'][
                'site.adminUserInitialized'] = User.admin_user_initialized()
            return data

        return response
    def patch(self, args, user):
        """
        Patch user details by ID.
        """
        state = {'current_password': None}

        try:
            for operation in args:
                try:
                    if not self._process_patch_operation(operation, user=user, state=state):
                        log.info("User patching has ignored unknown operation %s", operation)
                except ValueError as exception:
                    abort(code=http_exceptions.Conflict.code, message=str(exception))

            try:
                db.session.merge(user)
                db.session.commit()
            except sqlalchemy.exc.IntegrityError:
                db.session.rollback()
                # TODO: handle errors better
                abort(
                    code=http_exceptions.Conflict.code,
                    message="Could not update user details."
                )
        finally:
            db.session.rollback()
        return user
    def put(self):
        """Update restaurant data"""

        data = request.get_json()
        print("update restaurant: ", data)

        if not data:
            abort(400, "Missing restaurant data")

        user = g.user

        try:

            if data["name"] != "":
                user.name = data["name"]
            if data["phone_number"] != "":
                user.phone_number = data["phone_number"]
            if data["address"] != "":
                user.address = data["address"]

        except KeyError:
            abort(400, "Missing restaurant data")

        db.session.commit()

        return make_response(f"Restaurant {user.name} successfully updated info", 200)
    def patch(self, args, team_id):
        """
        Patch team details by ID.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                for operation in args['body']:
                    if not self._process_patch_operation(operation, team=team):
                        log.info(
                            "Team patching has ignored unknown operation %s",
                            operation)
                db.session.merge(team)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(code=http_exceptions.Conflict.code,
                  message="Could not update team details.")

        return team
    def delete(self, args, team_id):
        """
        Remove a member from a team.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                user_id = args['user_id']
                team_member = TeamMember.query.filter_by(
                    team=team, user_id=user_id).one()
                if team_member is None:
                    abort(code=http_exceptions.NotFound.code,
                          message="User with id %d does not exist" % user_id)
                db.session.delete(team_member)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(code=http_exceptions.Conflict.code,
                  message="Could not update team details.")

        return team
    def post(self, args, team_id):
        """
        Add a new member to a team.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                user_id = args.pop('user_id')
                user = User.query.get(user_id)
                if user is None:
                    abort(code=http_exceptions.NotFound.code,
                          message="User with id %d does not exist" % user_id)
                team_member = TeamMember(team=team, user=user, **args)
                db.session.add(team_member)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(code=http_exceptions.Conflict.code,
                  message="Could not update team details.")

        return None
Exemple #18
0
    def patch(self, args, user):
        """
        Patch user details by ID.
        """
        state = {'current_password': None}

        try:
            for operation in args:
                try:
                    if not self._process_patch_operation(
                            operation, user=user, state=state):
                        log.info(
                            "User patching has ignored unknown operation %s",
                            operation)
                except ValueError as exception:
                    abort(code=http_exceptions.Conflict.code,
                          message=str(exception))

            try:
                db.session.merge(user)
                db.session.commit()
            except sqlalchemy.exc.IntegrityError:
                db.session.rollback()
                # TODO: handle errors better
                abort(code=http_exceptions.Conflict.code,
                      message="Could not update user details.")
        finally:
            db.session.rollback()
        return user
Exemple #19
0
    def post(self, args):
        """
        Create a new user.
        """
        email = args.get('email', None)
        user = User.query.filter_by(email=email).first()

        if user is not None:
            abort(
                code=HTTPStatus.CONFLICT, message='The email address is already in use.'
            )

        if 'password' not in args:
            abort(code=HTTPStatus.BAD_REQUEST, message='Must provide a password')

        args['is_active'] = True

        context = api.commit_or_abort(
            db.session, default_error_message='Failed to create a new user.'
        )
        with context:
            new_user = User(**args)
            db.session.add(new_user)
        db.session.refresh(new_user)

        return new_user
Exemple #20
0
    def get(self, comment_id):
        comment = Comment.query.filter_by(id=comment_id).first()
        if comment:
            dump_data = comment_to_json(comment)
            return dump_data

        api.abort(404, "Comment by id {} doesn't exist".format(comment_id))
Exemple #21
0
    def post(self):
        """Create a new food request"""

        data = request.get_json()
        print("create food: ", data)

        user = g.user

        if not data:
            abort(400, "Missing necessary food request data")

        try:
            food_request = {}
            food_request["restaurant_id"] = user.id
            food_request["food_type"] = data["food_type"]
            food_request["food_quantity"] = data["quantity"]
            food_request["pickup_time"] = data["pickup_time"]

        except KeyError:
            abort(400, "Missing necessary data")

        new_food_request = FoodRequest(**food_request)

        db.session.add(new_food_request)
        db.session.commit()

        return make_response(f"New Food Request successfully created", 200)
    def patch(self, args, team_id):
        """
        Patch team details by ID.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                for operation in args['body']:
                    if not self._process_patch_operation(operation, team=team):
                        log.info("Team patching has ignored unknown operation %s", operation)
                db.session.merge(team)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(
                code=http_exceptions.Conflict.code,
                message="Could not update team details."
            )

        return team
Exemple #23
0
 def get_volume(self, provider, volume_id):
     try:
         conn = self.connect(provider)
         return conn.volumes.get(volume_id)
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #24
0
 def delete_volume_snapshot(self, provider, volume_id):
     try:
         conn = self.connect(provider)
         return None
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #25
0
 def delete_security_group_rule(self, provider, name):
     try:
         conn = self.connect(provider)
         return None
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #26
0
 def create_volume(self, provider, **kwargs):
     try:
         conn = self.connect(provider)
         return conn.volumes.create(name=kwargs['name'], driver='local')
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #27
0
 def delete_image(self, provider, name):
     try:
         conn = self.connect(provider)
         return conn.images.remove(image=name)
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #28
0
    def put(self):
        """Update driver data"""

        data = request.get_json()
        print("update driver: ", data)

        if not data:
            abort(400, "Missing driver data")

        user = g.user

        try:

            if data["first_name"] != "":
                user.first_name = data["first_name"]
            if data["phone_number"] != "":
                user.phone_number = data["phone_number"]
            if data["car_description"] != "":
                user.car_description = data["car_description"]

        except KeyError:
            abort(400, "Missing driver data")

        db.session.commit()

        return make_response(
            f"Driver {user.first_name} successfully updated info", 200)
Exemple #29
0
 def list_flavors(self, provider):
     try:
         conn = self.connect(provider)
         return None
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #30
0
 def delete_network(self, provider, name):
     try:
         conn = self.connect(provider)
         network = conn.networks.get(name)
         return network.remove()
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #31
0
 def delete_server(self, provider, name_or_id):
     try:
         conn = self.connect(provider)
         container = conn.containers.get(name_or_id)
         return container.remove(force=True)
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #32
0
    def delete(self, comment_id):
        comment = Comment.query.filter_by(id=comment_id).first()
        if comment:
            db.session.delete(comment)

            return 'deleted'
        else:
            api.abort(404, "Comment by id {} doesn't exist".format(comment_id))
Exemple #33
0
def getMerchantIdFromDB(keyword):
    merchant_query_res = MerchantQueryRaw.query.filter_by(
        keyword=keyword).first()

    if merchant_query_res:
        return merchant_query_res.get_id()

    api.abort(404, "Merchant by keyword {} doesn't exist".format(keyword))
Exemple #34
0
 def create_image_snapshot(self, provider, name, server):
     try:
         conn = self.connect(provider)
         container = conn.containers.get(server)
         return container.commit(repository=name)
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
Exemple #35
0
 def server_logs(self, provider, name_or_id, **kwargs):
     try:
         conn = self.connect(provider)
         container = conn.containers.get(name_or_id)
         return container.logs(**kwargs)
     except Exception as e:
         log.info("Exception: %s", e)
         abort(code=HTTPStatus.UNPROCESSABLE_ENTITY, message="%s" % e)
    def _process_patch_operation(self, operation, user, state):
        """
        Args:
            operation (dict) - one patch operation in RFC 6902 format
            user (User) - user instance which is needed to be patched
            state (dict) - inter-operations state storage

        Returns:
            processing_status (bool) - True if operation was handled, otherwise False.
        """
        if 'value' not in operation:
            # TODO: handle errors better
            abort(code=http_exceptions.UnprocessableEntity.code, message="value is required")

        if operation['op'] == parameters.PatchUserDetailsParameters.OP_TEST:
            # User has to provide the admin/supervisor password (if the current
            # user has an admin or a supervisor role) or the current password
            # of the user that is edited.
            if operation['path'] == '/current_password':
                current_password = operation['value']

                if current_user.password != current_password and user.password != current_password:
                    abort(code=http_exceptions.Forbidden.code, message="Wrong password")

                state['current_password'] = current_password
                return True

        elif operation['op'] == parameters.PatchUserDetailsParameters.OP_REPLACE:
            assert operation['path'][0] == '/', "Path must always begin with /"
            field_name = operation['path'][1:]
            field_value = operation['value']

            # Some fields require extra permissions to be changed.
            # Current user has to have at least a Supervisor role to change
            # 'is_active' and 'is_readonly' property
            if field_name in {'is_active', 'is_readonly'}:
                with permissions.SupervisorRolePermission(
                    obj=user,
                    password_required=True,
                    password=state['current_password']
                ):
                    # Access granted
                    pass

            # Current user has to have an Admin role to change 'is_admin' property
            elif field_name == 'is_admin':
                with permissions.AdminRolePermission(
                    password_required=True,
                    password=state['current_password']
                ):
                    # Access granted
                    pass

            setattr(user, field_name, field_value)
            return True
        return False
 def test(cls, obj, field, value, state):
     """
     Additional check for 'current_password' as User hasn't field 'current_password'
     """
     if field == 'current_password':
         if current_user.password != value and obj.password != value:
             abort(code=HTTPStatus.FORBIDDEN, message="Wrong password")
         else:
             state['current_password'] = value
             return True
     return PatchJSONParameters.test(obj, field, value, state)
 def post(self, args):
     """
     Create a new team.
     """
     team = Team(**args)
     # pylint: disable=no-member
     db.session.add(team)
     try:
         db.session.commit()
     except sqlalchemy.exc.IntegrityError:
         db.session.rollback()
         # TODO: handle errors better
         abort(code=http_exceptions.Conflict.code, message="Could not create a new team.")
     return team
 def delete(self, team):
     """
     Delete a team by ID.
     """
     db.session.delete(team)
     try:
         db.session.commit()
     except sqlalchemy.exc.IntegrityError:
         db.session.rollback()
         # TODO: handle errors better
         abort(
             code=http_exceptions.Conflict.code,
             message="Could not delete the team."
         )
     return None
def authorize(*args, **kwargs):
    # pylint: disable=unused-argument
    """
    This endpoint asks user if he grants access to his data to the requesting
    application.
    """
    # TODO: improve implementation. This implementation is broken because we
    # don't use cookies, so there is no session which client could carry on.
    # OAuth2 server should probably be deployed on a separate domain, so we
    # can implement a login page and store cookies with a session id.
    # ALTERNATIVELY, authorize page can be implemented as SPA (single page
    # application)
    if not current_user.is_authenticated:
        return api.abort(code=http_exceptions.Unauthorized.code)

    if request.method == 'GET':
        client_id = kwargs.get('client_id')
        oauth2_client = OAuth2Client.query.get_or_404(client_id=client_id)
        kwargs['client'] = oauth2_client
        kwargs['user'] = current_user
        # TODO: improve template design
        return render_template('authorize.html', **kwargs)

    confirm = request.form.get('confirm', 'no')
    return confirm == 'yes'
def client():
    """
    This endpoint creates and provides the authenticated user with
    ``client_id`` and ``client_secret``.
    """
    if not current_user.is_authenticated:
        return api.abort(code=http_exceptions.Unauthorized.code)
    # XXX: remove hard-codings
    # TODO: reconsider using gen_salt
    # TODO: develop sensible scopes
    # TODO: consider moving `db` operations into OAuth2Client class implementation
    client_instance = OAuth2Client(
        client_id=security.gen_salt(40),
        client_secret=security.gen_salt(50),
        _redirect_uris=" ".join(
            [
                "http://localhost:8000/authorized",
                "http://127.0.0.1:8000/authorized",
                "http://127.0.0.1:5000/api/v1/o2c.html",
                "http://127.0.0.2:8000/authorized",
                "http://127.0.1:8000/authorized",
                "http://127.1:8000/authorized",
            ]
        ),
        _default_scopes="users:read users:write email",
        user_id=current_user.id,
    )
    db.session.add(client_instance)
    db.session.commit()
    return jsonify(client_id=client_instance.client_id, client_secret=client_instance.client_secret)
 def post(self, args):
     """
     Create a new team.
     """
     try:
         try:
             team = Team(**args)
         except ValueError as exception:
             abort(code=http_exceptions.Conflict.code, message=str(exception))
         db.session.add(team)
         try:
             db.session.commit()
         except sqlalchemy.exc.IntegrityError:
             abort(code=http_exceptions.Conflict.code, message="Could not create a new team.")
     finally:
         db.session.rollback()
     return team
    def validate_captcha(self, data):
        """"
        Check reCAPTCHA if necessary.

        NOTE: we remove 'recaptcha_key' from data once checked because we don't need it
        in the resource
        """
        recaptcha_key = data.pop('recaptcha_key', None)
        captcha_is_valid = False
        if not recaptcha_key:
            no_captcha_permission = permissions.AdminRolePermission()
            if no_captcha_permission.check():
                captcha_is_valid = True
        elif recaptcha_key == 'secret_key':
            captcha_is_valid = True

        if not captcha_is_valid:
            abort(code=http_exceptions.Forbidden.code, message="CAPTCHA key is incorrect.")
    def delete(self, team, user_id):
        """
        Remove a member from a team.
        """
        team_member = TeamMember.query.filter_by(team=team, user_id=user_id).first_or_404()
        db.session.delete(team_member)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(
                code=http_exceptions.Conflict.code,
                message="Could not update team details."
            )

        return None
    def validate_captcha(self, data):
        """"
        Check reCAPTCHA if necessary.

        NOTE: we remove 'recaptcha_key' from data once checked because we don't need it
        in the resource
        """
        recaptcha_key = data.pop('recaptcha_key', None)
        captcha_is_valid = False
        if not recaptcha_key:
            no_captcha_permission = permissions.AdminRolePermission()
            if no_captcha_permission.check():
                captcha_is_valid = True
        # NOTE: This hardcoded CAPTCHA key is just for demo purposes.
        elif recaptcha_key == 'secret_key':
            captcha_is_valid = True

        if not captcha_is_valid:
            abort(code=HTTPStatus.FORBIDDEN, message="CAPTCHA key is incorrect.")
    def post(self, args, team):
        """
        Add a new member to a team.
        """
        with api.commit_or_abort(
                db.session,
                default_error_message="Failed to update team details."
            ):
            user_id = args.pop('user_id')
            user = User.query.get(user_id)
            if user is None:
                abort(
                    code=http_exceptions.NotFound.code,
                    message="User with id %d does not exist" % user_id
                )

            team_member = TeamMember(team=team, user=user, **args)
            db.session.add(team_member)

        return team_member
    def post(self, args, team):
        """
        Add a new member to a team.
        """
        try:
            user_id = args.pop('user_id')
            user = User.query.get(user_id)
            if user is None:
                abort(
                    code=http_exceptions.NotFound.code,
                    message="User with id %d does not exist" % user_id
                )

            try:
                team_member = TeamMember(team=team, user=user, **args)
            except ValueError as exception:
                abort(code=http_exceptions.Conflict.code, message=str(exception))

            db.session.add(team_member)

            try:
                db.session.commit()
            except sqlalchemy.exc.IntegrityError:
                abort(
                    code=http_exceptions.Conflict.code,
                    message="Could not update team details."
                )
        finally:
            db.session.rollback()
        return team_member
    def delete(self, team_id):
        """
        Delete a team by ID.
        """
        team = Team.query.get_or_404(team_id)

        # pylint: disable=no-member
        with permissions.OwnerRolePermission(obj=team):
            with permissions.WriteAccessPermission():
                db.session.delete(team)

        try:
            db.session.commit()
        except sqlalchemy.exc.IntegrityError:
            db.session.rollback()
            # TODO: handle errors better
            abort(
                code=http_exceptions.Conflict.code,
                message="Could not delete the team."
            )

        return None
    def _process_patch_operation(self, operation, team):
        """
        Args:
            operation (dict) - one patch operation in RFC 6902 format.
            team (Team) - team instance which is needed to be patched.
            state (dict) - inter-operations state storage.

        Returns:
            processing_status (bool) - True if operation was handled, otherwise False.
        """
        if 'value' not in operation:
            # TODO: handle errors better
            abort(code=http_exceptions.UnprocessableEntity.code, message="value is required")

        assert operation['path'][0] == '/', "Path must always begin with /"
        field_name = operation['path'][1:]
        field_value = operation['value']

        if operation['op'] == parameters.PatchTeamDetailsParameters.OP_REPLACE:
            setattr(team, field_name, field_value)
            return True

        return False
    def post(self, args):
        """
        Create a new user.
        """
        # Check reCAPTCHA if necessary
        recaptcha_key = args.pop('recaptcha_key', None)
        captcha_is_valid = False
        if not recaptcha_key:
            no_captcha_permission = permissions.AdminRolePermission()
            if no_captcha_permission.check():
                captcha_is_valid = True
        elif recaptcha_key == 'secret_key':
            captcha_is_valid = True

        if not captcha_is_valid:
            abort(code=http_exceptions.Forbidden.code, message="CAPTCHA key is incorrect.")
        
        new_user = User.create(**args)
        # TODO: handle errors better
        if new_user is None:
            abort(code=http_exceptions.Conflict.code, message="Could not create a new user.")
        
        return new_user
    def patch(self, args, team):
        """
        Patch team details by ID.
        """
        try:
            for operation in args:
                try:
                    if not self._process_patch_operation(operation, team=team):
                        log.info("Team patching has ignored unknown operation %s", operation)
                except ValueError as exception:
                    abort(code=http_exceptions.Conflict.code, message=str(exception))

            db.session.merge(team)

            try:
                db.session.commit()
            except sqlalchemy.exc.IntegrityError:
                abort(
                    code=http_exceptions.Conflict.code,
                    message="Could not update team details."
                )
        finally:
            db.session.rollback()
        return team
def authorize(*args, **kwargs):
    """
    This endpoint asks user if he grants access to his data to the requesting
    application.
    """
    # TODO: improve implementation
    if not current_user.is_authenticated:
        return api.abort(code=http_exceptions.Unauthorized.code)
    if request.method == "GET":
        client_id = kwargs.get("client_id")
        client = OAuth2Client.query.filter_by(client_id=client_id).first()
        kwargs["client"] = client
        kwargs["user"] = current_user
        # TODO: improve template design
        return render_template("authorize.html", **kwargs)

    confirm = request.form.get("confirm", "no")
    return confirm == "yes"
def authorize(*args, **kwargs):
    # pylint: disable=unused-argument
    """
    This endpoint asks user if he grants access to his data to the requesting
    application.
    """
    # TODO: improve implementation
    if not current_user.is_authenticated:
        return api.abort(code=http_exceptions.Unauthorized.code)
    if request.method == 'GET':
        client_id = kwargs.get('client_id')
        oauth2_client = OAuth2Client.query.filter_by(client_id=client_id).first()
        kwargs['client'] = oauth2_client
        kwargs['user'] = current_user
        # TODO: improve template design
        return render_template('authorize.html', **kwargs)

    confirm = request.form.get('confirm', 'no')
    return confirm == 'yes'
 def _invalid_response(self, req):
     # pylint: disable=method-hidden,unused-argument,no-self-use
     api.abort(code=http_exceptions.Unauthorized.code)
 def deny(self):
     return abort(code=self.DENY_ABORT_HTTP_CODE, message=self.DENY_ABORT_MESSAGE)
 def deny(self):
     """
     Abort HTTP request by raising HTTP error exception with a specified
     HTTP code.
     """
     return abort(code=self.DENY_ABORT_HTTP_CODE, message=self.DENY_ABORT_MESSAGE)
 def __init__(self, *args, **kwargs):
     super(OAuth2Provider, self).__init__(*args, **kwargs)
     # XXX: it would be great if flask-oauthlib won't override existing
     # methods, so we can implement `_invalid_response` as a method instead
     # of lambda.
     self._invalid_response = lambda req: api.abort(code=http_exceptions.Unauthorized.code)
    def _process_patch_operation(self, operation, user, state):
        """
        Args:
            operation (dict) - one patch operation in RFC 6902 format
            user (User) - user instance which is needed to be patched
            state (dict) - inter-operations state storage

        Returns:
            processing_status (bool) - True if operation was handled, otherwise False.
        """
        if 'value' not in operation:
            abort(code=http_exceptions.UnprocessableEntity.code, message="value is required")

        if operation['op'] == parameters.PatchUserDetailsParameters.OP_TEST:
            if operation['path'] == '/current_password':
                state['current_password'] = operation['value']
                if (
                    not current_user.verify_password(state['current_password'])
                    and
                    not user.verify_password(state['current_password'])
                ):
                    abort(code=http_exceptions.Forbidden.code, message="Wrong password")
                return True
        
        elif operation['op'] == parameters.PatchUserDetailsParameters.OP_REPLACE:
            assert operation['path'][0] == '/', "Path must always begin with /"
            field_name = operation['path'][1:]
            field_value = operation['value']
            
            if field_name in ('is_active', 'is_readonly', 'is_admin'):
                
                if field_name == 'is_admin':
                    with permissions.AdminRolePermission(
                            password_required=True,
                            password=state['current_password']
                    ):
                        static_role = user.SR_ADMIN
                
                elif field_name == 'is_active':
                    with permissions.SupervisorRolePermission(
                            obj=user,
                            password_required=True,
                            password=state['current_password']
                    ):
                        static_role = user.SR_ACTIVE
                
                elif field_name == 'is_readonly':
                    with permissions.SupervisorRolePermission(
                            obj=user,
                            password_required=True,
                            password=state['current_password']
                    ):
                        static_role = user.SR_READONLY
                
                if field_value:
                    user.set_static_role(static_role, commit=False)
                
                else:
                    user.unset_static_role(static_role, commit=False)
            
            elif field_name == 'password':
                user.set_password(field_value, commit=False)
            
            else:
                setattr(user, field_name, field_value)
            return True
        return False