Esempio n. 1
0
    def put(self, target_username):
        """
        PUT request for updating user data.
        This requires a Pbench auth token in the header field

        This requires a JSON data with required user registration fields that needs an update
        Example Json:
        {
            "first_name": "new_name",
            "password": "******",
            ...
        }

        Required headers include

            Content-Type:   application/json
            Accept:         application/json
            Authorization:  Bearer Pbench_auth_token (user received upon login)

        :return: JSON Payload
            Success: 200,
                    response_object = {
                        "username": <username>,
                        "first_name": <firstName>,
                        "last_name": <lastName>,
                        "registered_on": <registered_on>,
                    }
            Failure: <status_Code>,
                    response_object = {
                        "message": "failure message"
                    }
        """
        user_payload = request.get_json()
        if not user_payload:
            self.logger.warning("Invalid json object: {}", request.url)
            abort(HTTPStatus.BAD_REQUEST,
                  message="Invalid json object in request")

        result = self.get_valid_target_user(target_username, "PUT")
        if not result.target_user:
            abort(result.http_status, message=result.http_message)

        # Check if the user payload contain fields that are either protected or
        # are not present in the user db. If any key in the payload does not match
        # with the column name we will abort the update request.
        non_existent = set(user_payload.keys()).difference(
            set(User.__table__.columns.keys()))
        if non_existent:
            self.logger.warning(
                "User trying to update fields that are not present in the user database. Fields: {}",
                non_existent,
            )
            abort(
                HTTPStatus.BAD_REQUEST,
                message="Invalid fields in update request payload",
            )
        # Only admin user will be allowed to change other user's role. However,
        # Admin users will not be able to change their admin role,
        # This is done to prevent last admin user from de-admining him/herself
        protected_db_fields = User.get_protected()
        if (not self.auth.token_auth.current_user().is_admin()
                or self.auth.token_auth.current_user() == result.target_user):
            protected_db_fields.append("role")

        protected = set(user_payload.keys()).intersection(
            set(protected_db_fields))
        for field in protected:
            if getattr(result.target_user, field) != user_payload[field]:
                self.logger.warning(
                    "User trying to update the non-updatable fields. {}: {}",
                    field,
                    user_payload[field],
                )
                abort(HTTPStatus.FORBIDDEN,
                      message="Invalid update request payload")
        try:
            result.target_user.update(**user_payload)
        except Exception:
            self.logger.exception(
                "Exception occurred during updating user object")
            abort(HTTPStatus.INTERNAL_SERVER_ERROR, message="INTERNAL ERROR")

        response_object = result.target_user.get_json()
        return make_response(jsonify(response_object), HTTPStatus.OK)
Esempio n. 2
0
    def put(self, username):
        """
        PUT request for updating user data.
        This requires a Pbench auth token in the header field

        This requires a JSON data with required user registration fields that needs an update
        Example Json:
        {
            "first_name": "new_name",
            "password": "******",
            ...
        }

        Required headers include

            Content-Type:   application/json
            Accept:         application/json
            Authorization:  Bearer Pbench_auth_token (user received upon login)

        :return: JSON Payload
            Success: 200,
                    response_object = {
                        "username": <username>,
                        "first_name": <firstName>,
                        "last_name": <lastName>,
                        "registered_on": <registered_on>,
                    }
            Failure: <status_Code>,
                    response_object = {
                        "message": "failure message"
                    }
        """
        post_data = request.get_json()
        if not post_data:
            self.logger.warning("Invalid json object: {}", request.url)
            abort(400, message="Invalid json object in request")

        try:
            user, verified = self.auth.verify_user(username)
        except Exception:
            self.logger.exception(
                "Exception occurred while verifying the user")
            abort(500, message="INTERNAL ERROR")

        # TODO: Check if the user has the right privileges
        if not verified:
            self.logger.warning(
                "User {} is not authorized to delete user {}.",
                user.username,
                username,
            )
            abort(
                403,
                message=
                f"Not authorized to update information about user {username}",
            )

        # Check if the user payload contain fields that are either protected or
        # are not present in the user db. If any key in the payload does not match
        # with the column name we will abort the update request.
        non_existent = set(post_data.keys()).difference(
            set(User.__table__.columns.keys()))
        if non_existent:
            self.logger.warning(
                "User trying to update fields that are not present in the user database. Fields: {}",
                non_existent,
            )
            abort(400, message="Invalid fields in update request payload")
        protected = set(post_data.keys()).intersection(
            set(User.get_protected()))
        for field in protected:
            if getattr(user, field) != post_data[field]:
                self.logger.warning(
                    "User trying to update the non-updatable fields. {}: {}",
                    field,
                    post_data[field],
                )
                abort(403, message="Invalid update request payload")
        try:
            user.update(**post_data)
        except Exception:
            self.logger.exception(
                "Exception occurred during updating user object")
            abort(500, message="INTERNAL ERROR")

        response_object = user.get_json()
        return make_response(jsonify(response_object), 200)