Example #1
0
def authorized(f, admin_required, *args, **kwargs):
    try:
        auth_hdr = request.headers.get('Authorization')
        if auth_hdr is None:
            error(401, 'Missing Authorization header')

        auth_hdr_split = auth_hdr.split("Bearer")
        if not len(auth_hdr_split) == 2:
            error(
                401, 'Malformed auth token string, \
                should be: "Bearer [auth_string]"')

        payload = jwt.decode(auth_hdr_split[1].strip(),
                             current_app.config.get('JWT_SECRET_KEY'),
                             algorithms=["HS256"])

        user_data = user.read(g.database, payload['sub'])
        if user_data == []:
            error(401, 'Invalid auth token claim')

        if admin_required and not user_data['admin']:
            error(403, 'Logged in user not admin')

        g.logged_in_user_id = user_data['user_id']
        g.logged_in_user_is_admin = user_data['admin']

        return f(*args, **kwargs)

    except (
            jwt.exceptions.InvalidTokenError,
            jwt.exceptions.InvalidSignatureError,
    ):
        error(401, 'Invalid auth token, signature verification failed')
    except jwt.exceptions.ExpiredSignatureError:
        error(401, 'Auth token expired')
    def test_get_missing_user(self):

        email = "*****@*****.**"

        user_result = user.read(self.database,
                                user.identify_by_email(self.database, email))

        assert user_result is None
Example #3
0
    def put(self, user_id):
        """
        Update the user entry with new values for one or more of the user data fields:
        email, name, group_name, password, or admin
        """
        user_db_data = user.read(g.database, user_id)
        if not user_db_data:
            error(404, "User id not recognized.")

        if not g.logged_in_user_is_admin and g.logged_in_user_id != user_id:
            error(
                403,
                "Logged in user not admin and doesn't match requested user id."
            )

        data = request.get_json()

        if data is None:
            error(400, "No json data in request body")

        if not any([
                key in data.keys() for key in
            ["email", "name", "group_name", "password", "admin"]
        ]):

            error(
                400, "Json data must define one or more of: \
email, name, group_name, password, admin")

        if ("admin" in data.keys()) and (data["admin"] is True) and (
                not g.logged_in_user_is_admin):
            error(403, "Logged in user can not grant self admin privileges.")

        if "password" in data.keys():
            if len(data["password"]) < 8:
                error(422, "New password is less than 8 characters long.")
            data["hashed_password"] = generate_password_hash(data["password"])

        try:
            update_user_result = user.update(g.database, user_id, data)

        except UniqueViolation:
            error(422, "User with that email address already exists")

        if update_user_result is None:
            # Returns None if the user doesn't exist. We already checked this,
            # but if it still fails, throw 404
            error(404, "User id not recognized")

        response_data = {
            "user_id": update_user_result["user_id"],
            "email": update_user_result["email"],
            "admin": update_user_result["admin"],
            "name": update_user_result["name"],
            "group_name": update_user_result["group_name"],
            "timestamp": update_user_result["date_modified"]
        }
        return jsonify(response_data), 200
Example #4
0
    def get(self, user_id):
        """
        Fetch a single user's data if a user_id is specified.
        Otherwise fetch the list of all users.
        Returned info contains user_id, name, group name,email,
        admin status, and date_created.
        """

        if user_id:

            user_db_data = user.read(g.database, user_id)

            if not user_db_data:
                error(404, "User id not recognized")

            if not g.logged_in_user_is_admin and g.logged_in_user_id != user_id:
                error(
                    403,
                    "Logged in user not admin and doesn't match requested user id."
                )

            response_data = {
                "user_id": user_db_data["user_id"],
                "email": user_db_data["email"],
                "name": user_db_data["name"],
                "group_name": user_db_data["group_name"],
                "admin": user_db_data["admin"],
                "timestamp": user_db_data["date_created"]
            }
            return jsonify(response_data), 201

        else:
            # No user_id given; this is a GET all users request.
            if not g.logged_in_user_is_admin:
                error(403, "Logged in user not admin ")

            user_db_data = user.fetchall(g.database)

            response_data = {"users": []}
            for user_entry in user_db_data:
                response_data["users"].append({
                    "user_id":
                    user_entry["user_id"],
                    "email":
                    user_entry["email"],
                    "name":
                    user_entry["name"],
                    "group_name":
                    user_entry["group_name"],
                    "admin":
                    user_entry["admin"],
                    "timestamp":
                    user_entry["date_created"]
                })

            return jsonify(response_data), 201
    def test_get_user(self):
        email = "*****@*****.**"
        name = "Ima Test"
        group_name = "Ima Test Group"
        hashed_password = '******'
        admin = True

        self.create_example_user(email, name, group_name, hashed_password,
                                 admin)

        user_result = user.read(self.database,
                                user.identify_by_email(self.database, email))

        self.verify_user_data(email, name, group_name, hashed_password, admin)
Example #6
0
    def get(self, user_id):
        """
        Fetch the list of users, with their user_id, name, group name,
        email, admin status, and date_created.
        """

        print("in endpoint; getting with userid = ", user_id)

        if user_id:
            user_db_data = user.read(g.database, user_id)

            print("user db read result: ", user_db_data)

            if user_db_data:
                response_data = {
                    "user_id": user_db_data["user_id"],
                    "email": user_db_data["email"],
                    "name": user_db_data["name"],
                    "group_name": user_db_data["group_name"],
                    "admin": user_db_data["admin"],
                    "timestamp": user_db_data["date_created"]
                }
                return jsonify(response_data), 201

            else:
                error(404, "User id not recognized")

        else:
            user_db_data = user.fetchall(g.database)

            response_data = {"users": []}
            for user_entry in user_db_data:
                response_data["users"].append({
                    "user_id":
                    user_entry["user_id"],
                    "email":
                    user_entry["email"],
                    "name":
                    user_entry["name"],
                    "group_name":
                    user_entry["group_name"],
                    "admin":
                    user_entry["admin"],
                    "timestamp":
                    user_entry["date_created"]
                })

            return jsonify(response_data), 201
Example #7
0
    def post(self):
        data = request.get_json()

        if data is None:
            error(400, "No json data in request body")

        check_data_fields(data, ['email', 'password'])

        user_db_result = user.read(
            g.database, user.identify_by_email(g.database, data['email']))

        if (not user_db_result or not check_password_hash(
                user_db_result['hashed_password'], data['password'])):
            error(401, 'Invalid username or password')

        response_data = {
            'auth_token': get_auth_token(current_app,
                                         user_db_result['user_id']),
            'user_id': user_db_result['user_id']
        }
        return jsonify(response_data)