Exemplo n.º 1
0
def update_user(db_session, user: str, updated_info, requester) -> (dict, str):
    """
    Updates all the information about a particular user.
    :param db_session: The postgres session to be used.
    :param user: The user ID to be updated.
    :param updated_info: The new data.
    :param requester: Who is requiring this update.
    :return: The old information (a dictionary containing the old information about the user
             and the old service.
    :raises HTTPRequestError: If the username is different from the original (this field cannot be updated).
    """
    # Drop invalid fields
    updated_info = {
        k: updated_info[k]
        for k in updated_info if k in User.fillable
    }
    user = User.get_by_name_or_id(user)
    old_user = user.safe_dict()
    old_service = user.service

    if 'username' in updated_info.keys() \
            and updated_info['username'] != user.username:
        raise HTTPRequestError(400, "usernames can't be updated")

    # check_user function needs username.
    updated_info['username'] = user.username
    check_user(updated_info)

    # Verify if the email is in use by another user
    if 'email' in updated_info.keys() and updated_info['email'] != user.email:
        if db_session.query(User).filter_by(
                email=updated_info['email']).one_or_none():
            raise HTTPRequestError(400, "email already in use")

    log().info(f"user {user.username} updated by {requester['username']}")
    log().info({'oldUser': user.safe_dict(), 'newUser': updated_info})

    # Update all new data.
    if 'name' in updated_info.keys():
        user.name = updated_info['name']
    if 'service' in updated_info.keys():
        user.service = updated_info['service']
    if 'email' in updated_info.keys():
        user.email = updated_info['email']

    db_session.add(user)
    db_session.commit()

    # Publish messages related to service creation/deletion
    if count_tenant_users(db_session, old_service) == 0:
        log().info(f"will emit tenant lifecycle event {old_service} - DELETE")
        send_notification({"type": 'DELETE', 'tenant': old_service})

    if count_tenant_users(db_session, user.service) == 1:
        log().info(f"will emit tenant lifecycle event {user.service} - CREATE")
        send_notification({"type": 'CREATE', 'tenant': user.service})

    return old_user, old_service
Exemplo n.º 2
0
def delete_user(db_session, username: str, requester):
    """
    Deletes an user from the system
    :param db_session: The postgres session to be used
    :param username: String The user to be removed
    :param requester: Who is creating this user. This is a dictionary with two keys:
                      "userid" and "username"
    :return: The removed user
    :raises HTTPRequestError: If the user tries to remove itself.
    :raises HTTPRequestError: If the user is not in the database.
    """
    try:
        user = User.get_by_name_or_id(username)
        if user.id == requester['userid']:
            raise HTTPRequestError(400, "a user can't remove himself")
        db_session.execute(
            UserPermission.__table__.delete(UserPermission.user_id == user.id))
        db_session.execute(
            UserGroup.__table__.delete(UserGroup.user_id == user.id))
        cache.delete_key(userid=user.id)

        # The user is not hardDeleted.
        # it should be copied to inactiveUser table
        inactiveTables.PasswdInactive.createInactiveFromUser(
            db_session,
            user,
        )
        inactiveTables.UserInactive.createInactiveFromUser(
            db_session, user, requester['userid'])
        password.expire_password_reset_requests(db_session, user.id)
        db_session.delete(user)
        log().info(f"user {user.username} deleted by {requester['username']}")
        log().info(user.safe_dict())

        kongUtils.remove_from_kong(user)
        MVUserPermission.refresh()
        MVGroupPermission.refresh()
        db_session.commit()

        if count_tenant_users(db_session, user.service) == 0:
            log().info(
                f"will emit tenant lifecycle event {user.service} - DELETE")
            send_notification({"type": 'DELETE', 'tenant': user.service})

        return user
    except orm_exceptions.NoResultFound:
        raise HTTPRequestError(404, "No user found with this ID")
Exemplo n.º 3
0
def create_user():
    try:
        requester = auth.get_jwt_payload(request.headers.get('Authorization'))
        auth_data = load_json_from_request(request)

        # Create user
        new_user = crud.create_user(db.session, auth_data, requester)

        # If no problems occur to create user (no exceptions), configure kong
        kong_data = kong.configure_kong(new_user.username)
        if kong_data is None:
            return format_response(
                500, 'failed to configure verification subsystem')
        new_user.secret = kong_data['secret']
        new_user.key = kong_data['key']
        new_user.kongId = kong_data['kongid']

        db.session.add(new_user)
        db.session.commit()
        group_success = []
        group_failed = []
        if 'profile' in auth_data.keys():
            group_success, group_failed = rship. \
                add_user_many_groups(db.session, new_user.id,
                                     auth_data['profile'], requester)
        db.session.commit()
        if conf.emailHost != 'NOEMAIL':
            pwdc.create_password_set_request(db.session, new_user)
            db.session.commit()

        if crud.count_tenant_users(db.session, new_user.service) == 1:
            log().info("will emit tenant lifecycle event {} - CREATE".format(
                new_user.service))
            send_notification({"type": 'CREATE', 'tenant': new_user.service})

        return make_response(
            json.dumps(
                {
                    "user": new_user.safeDict(),
                    "groups": group_success,
                    "could not add": group_failed,
                    "message": "user created"
                },
                default=json_serial), 200)
    except HTTPRequestError as err:
        return format_response(err.errorCode, err.message)
Exemplo n.º 4
0
def remove_user(user):
    try:
        requester = auth.get_jwt_payload(request.headers.get('Authorization'))
        old_username = crud.get_user(db.session, user).username
        old_user = crud.delete_user(db.session, user, requester)
        kong.remove_from_kong(old_username)
        MVUserPermission.refresh()
        MVGroupPermission.refresh()
        db.session.commit()

        if crud.count_tenant_users(db.session, old_user.service) == 0:
            log().info("will emit tenant lifecycle event {} - DELETE".format(
                old_user.service))
            send_notification({"type": 'DELETE', 'tenant': old_user.service})

        return format_response(200, "User removed")
    except HTTPRequestError as err:
        return format_response(err.errorCode, err.message)
Exemplo n.º 5
0
def update_user(user):
    try:
        requester = auth.get_jwt_payload(request.headers.get('Authorization'))
        auth_data = load_json_from_request(request)
        updated_user, old_service = crud.update_user(db.session, user,
                                                     auth_data, requester)

        # Create a new kong secret and delete the old one
        kong_data = kong.configure_kong(updated_user.username)
        if kong_data is None:
            return format_response(
                500, 'failed to configure verification subsystem')

        kong.revoke_kong_secret(updated_user.username, updated_user.kongId)
        updated_user.secret = kong_data['secret']
        updated_user.key = kong_data['key']
        updated_user.kongid = kong_data['kongid']
        db.session.add(updated_user)
        db.session.commit()

        if crud.count_tenant_users(db.session, old_service) == 0:
            log().info("will emit tenant lifecycle event {} - DELETE".format(
                old_service))
            send_notification({"type": 'DELETE', 'tenant': old_service})

        if crud.count_tenant_users(db.session, updated_user.service) == 1:
            log().info("will emit tenant lifecycle event {} - CREATE".format(
                updated_user.service))
            send_notification({
                "type": 'CREATE',
                'tenant': updated_user.service
            })
        return format_response(200)

    except HTTPRequestError as err:
        return format_response(err.errorCode, err.message)
Exemplo n.º 6
0
def create_user(db_session, user: User, requester):
    """
    Create a new user.
    :param db_session: The postgres db session to be used
    :param user: User The user to be created. This is a simple dictionary with all 'fillable' field
                 listed in Models.User class.
    :param requester: Who is creating this user. This is a dictionary with two keys:
                      "userid" and "username"
    :return: The result of creating this user.
    :raises HTTPRequestError: If username is already in use
    :raises HTTPRequestError: If e-mail is already in use
    :raises HTTPRequestError: If any problem occurs while configuring Kong
    """
    # Drop invalid fields
    user = {k: user[k] for k in user if k in User.fillable}
    check_user(user)

    # Sanity checks
    # Check whether username and e-mail are unique.
    if db_session.query(
            User.id).filter_by(username=user['username']).one_or_none():
        raise HTTPRequestError(400, f"Username {user['username']} is in use.")

    if db_session.query(User.id).filter_by(email=user['email']).one_or_none():
        raise HTTPRequestError(400, f"E-mail {user['email']} is in use.")

    if conf.emailHost == 'NOEMAIL':
        user['salt'], user['hash'] = password.create_pwd(
            conf.temporaryPassword)

    # Last field to be filled automatically, before parsing
    user['created_by'] = requester['userid']

    # User structure is finished.
    new_user = User(**user)
    log().info(f"User {user['username']} created by {requester['username']}")
    log().info(new_user)

    # If no problems occur to create user (no exceptions), configure kong
    kong_data = kongUtils.configure_kong(new_user.username)
    if kong_data is None:
        raise HTTPRequestError(500,
                               'failed to configure verification subsystem')
    new_user.secret = kong_data['secret']
    new_user.key = kong_data['key']
    new_user.kongId = kong_data['kongid']

    # Add the new user to the database
    db_session.add(new_user)
    db_session.commit()

    # Configuring groups and user profiles
    group_success = []
    group_failed = []
    if 'profile' in user.keys():
        group_success, group_failed = rship. \
            add_user_many_groups(db_session, new_user.id,
                                 user['profile'], requester)
        db_session.commit()
    if conf.emailHost != 'NOEMAIL':
        pwdc.create_password_set_request(db_session, new_user)
        db_session.commit()

    if count_tenant_users(db_session, new_user.service) == 1:
        log().info(
            f"Will emit tenant lifecycle event {new_user.service} - CREATE")
        send_notification({"type": 'CREATE', 'tenant': new_user.service})

    ret = {
        "user": new_user.safe_dict(),
        "groups": group_success,
        "could not add": group_failed,
        "message": "user created"
    }
    return ret