コード例 #1
0
def test_create_user_and_add_transaction_membership_1(session, auth_mock,
                                                      keycloak_mock):  # pylint:disable=unused-argument
    """Assert transactions works fine."""
    org = factory_org_model(org_info=TestOrgInfo.org_anonymous)
    membership = [TestAnonymousMembership.generate_random_user(ADMIN)]
    with patch('auth_api.models.User.flush',
               side_effect=Exception('mocked error')):
        users = UserService.create_user_and_add_membership(membership,
                                                           org.id,
                                                           single_mode=True)

    user_name = IdpHint.BCROS.value + '/' + membership[0]['username']
    assert len(users['users']) == 1
    assert users['users'][0]['username'] == membership[0]['username']
    assert users['users'][0]['http_status'] == 500
    assert users['users'][0]['error'] == 'Adding User Failed'

    # make sure no records are created
    user = UserModel.find_by_username(user_name)
    assert user is None
    user = UserModel.find_by_username(membership[0]['username'])
    assert user is None
    members = MembershipModel.find_members_by_org_id(org.id)
    # only one member should be there since its a STAFF created org
    assert len(members) == 0
コード例 #2
0
ファイル: user.py プロジェクト: nitheesh-aot/sbc-auth
    def reset_password_for_anon_user(user_info: dict,
                                     user_name,
                                     token_info: Dict = None):
        """Reset the password of the user."""
        user = UserModel.find_by_username(user_name)
        membership = MembershipModel.find_membership_by_userid(user.id)
        org_id = membership.org_id
        org = OrgModel.find_by_org_id(org_id)
        if not org or org.access_type != AccessType.ANONYMOUS.value:
            raise BusinessException(Error.INVALID_INPUT, None)

        check_auth(org_id=org_id,
                   token_info=token_info,
                   one_of_roles=(ADMIN, STAFF))
        update_user_request = KeycloakUser()
        update_user_request.user_name = user_name.replace(
            IdpHint.BCROS.value + '/', '')
        update_user_request.password = user_info['password']
        update_user_request.update_password_on_login()

        try:
            kc_user = KeycloakService.update_user(update_user_request)
        except HTTPError as err:
            current_app.logger.error('update_user in keycloak failed {}', err)
            raise BusinessException(Error.UNDEFINED_ERROR, err)
        return kc_user
コード例 #3
0
ファイル: test_user.py プロジェクト: saravanpa-aot/sbc-auth
def test_create_user_add_membership_reenable(session, auth_mock, keycloak_mock,
                                             monkeypatch):  # pylint:disable=unused-argument
    """Assert that an admin can add a member."""
    org = factory_org_model(org_info=TestOrgInfo.org_anonymous)
    user = factory_user_model()
    factory_membership_model(user.id, org.id)
    factory_product_model(org.id, product_code=ProductCode.DIR_SEARCH.value)
    claims = TestJwtClaims.get_test_real_user(user.keycloak_guid)

    patch_token_info(claims, monkeypatch)
    anon_member = TestAnonymousMembership.generate_random_user(USER)
    membership = [anon_member]
    users = UserService.create_user_and_add_membership(membership, org.id)
    user_name = IdpHint.BCROS.value + '/' + membership[0]['username']
    assert len(users['users']) == 1
    assert users['users'][0]['username'] == user_name
    assert users['users'][0]['type'] == Role.ANONYMOUS_USER.name

    members = MembershipModel.find_members_by_org_id(org.id)

    # staff didnt create members..so count is count of owner+other 1 member
    assert len(members) == 2

    # assert cant be readded
    users = UserService.create_user_and_add_membership(membership, org.id)
    assert users['users'][0]['http_status'] == 409
    assert users['users'][0]['error'] == 'The username is already taken'

    # deactivate everything and try again

    anon_user = UserModel.find_by_username(user_name)
    anon_user.status = Status.INACTIVE.value
    anon_user.save()
    membership_model = MembershipModel.find_membership_by_userid(anon_user.id)
    membership_model.status = Status.INACTIVE.value

    update_user_request = KeycloakUser()
    update_user_request.user_name = membership[0]['username']
    update_user_request.enabled = False
    KeycloakService.update_user(update_user_request)

    org2 = factory_org_model(org_info=TestOrgInfo.org_anonymous_2,
                             org_type_info={'code': 'BASIC'},
                             org_status_info=None,
                             payment_type_info=None)

    factory_membership_model(user.id, org2.id)
    factory_product_model(org2.id, product_code=ProductCode.DIR_SEARCH.value)
    users = UserService.create_user_and_add_membership(membership, org2.id)
    assert users['users'][0]['http_status'] == 409
    assert users['users'][0]['error'] == 'The username is already taken'

    # add to same org.Should work
    users = UserService.create_user_and_add_membership(membership, org.id)
    assert len(users['users']) == 1
    assert users['users'][0][
        'username'] == IdpHint.BCROS.value + '/' + membership[0]['username']
    assert users['users'][0]['type'] == Role.ANONYMOUS_USER.name
コード例 #4
0
def test_find_by_username(session):
    """Assert User can be found by the most current username."""
    user = User(username='******', roles='{edit, uma_authorization, staff}')
    session.add(user)
    session.commit()

    u = User.find_by_username('CP1234567')

    assert u.id is not None
コード例 #5
0
def _get_admin_emails(username):
    admin_user = UserModel.find_by_username(username)
    if admin_user:
        admin_name = admin_user.firstname + ' ' + admin_user.lastname
        if admin_user.contacts:
            admin_emails = admin_user.contacts[0].contact.email
        else:
            admin_emails = admin_user.email

    return admin_emails, admin_name
コード例 #6
0
ファイル: test_user.py プロジェクト: shabeeb-aot/sbc-auth
def test_find_by_username(session):
    """Assert User can be found by the most current username."""
    user = User(username='******',
                keycloak_guid='1b20db59-19a0-4727-affe-c6f64309fd04')
    session.add(user)
    session.commit()

    u = User.find_by_username('CP1234567')

    assert u.id is not None
コード例 #7
0
    def create_user_and_add_membership(memberships: List[dict], org_id, token_info: Dict = None,
                                       skip_auth: bool = False):
        """
        Create user(s) in the  DB and upstream keycloak.

        accepts a list of memberships ie.a list of objects with username,password and membershipTpe
        skip_auth can be used if called method already perfomed the authenticaiton
        skip_auth= true is used now incase of invitation for admin users scenarion
        other cases should be invoked with skip_auth=false
        """
        if skip_auth:  # make sure no bulk operation and only owner is created using if no auth
            if len(memberships) > 1 or memberships[0].get('membershipType') not in [OWNER, ADMIN]:
                raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)
        else:
            check_auth(org_id=org_id, token_info=token_info, one_of_roles=(ADMIN, OWNER))

        # check if anonymous org ;these actions cannot be performed on normal orgs
        org = OrgModel.find_by_org_id(org_id)
        if not org or org.access_type != AccessType.ANONYMOUS.value:
            raise BusinessException(Error.INVALID_INPUT, None)

        current_app.logger.debug('create_user')
        users = []
        for membership in memberships:
            create_user_request = KeycloakUser()

            current_app.logger.debug(f"create user username: {membership['username']}")
            create_user_request.first_name = membership['username']
            create_user_request.user_name = membership['username']
            create_user_request.password = membership['password']
            create_user_request.enabled = True
            create_user_request.attributes = {'access_type': AccessType.ANONYMOUS.value}
            if membership.get('update_password_on_login', True):  # by default , reset needed
                create_user_request.update_password_on_login()
            try:
                # TODO may be this method itself throw the business exception;can handle different exceptions?
                kc_user = KeycloakService.add_user(create_user_request)
            except HTTPError as err:
                current_app.logger.error('create_user in keycloak failed', err)
                raise BusinessException(Error.FAILED_ADDING_USER_IN_KEYCLOAK, None)
            username = IdpHint.BCROS.value + '/' + membership['username']
            existing_user = UserModel.find_by_username(username)
            if existing_user:
                current_app.logger.debug('Existing users found in DB')
                raise BusinessException(Error.DATA_ALREADY_EXISTS, None)
            user_model: UserModel = UserModel(username=username,
                                              # BCROS is temporary value.Will be overwritten when user logs in
                                              is_terms_of_use_accepted=False, status=Status.ACTIVE.value,
                                              type=AccessType.ANONYMOUS.value, email=membership.get('email', None),
                                              firstname=kc_user.first_name, lastname=kc_user.last_name)

            user_model.save()
            User._add_org_membership(org_id, user_model.id, membership['membershipType'])
            users.append(User(user_model).as_dict())
        return {'users': users}
コード例 #8
0
ファイル: user.py プロジェクト: nitheesh-aot/sbc-auth
    def find_by_username(cls, username: str = None):
        """Find user by provided username."""
        if not username:
            return None

        # find locally
        user_model = UserModel.find_by_username(username)

        if not user_model:
            return None

        return User(user_model)
コード例 #9
0
ファイル: user.py プロジェクト: nitheesh-aot/sbc-auth
    def delete_anonymous_user(user_name, token_info: Dict = None):
        """
        Delete User Profile.

        1) check if the token user is admin/owner of the current user
        2) disable the user from kc
        3) set user status as INACTIVE
        4) set membership as inactive
        """
        admin_user: UserModel = UserModel.find_by_jwt_token(token_info)

        if not admin_user:
            raise BusinessException(Error.DATA_NOT_FOUND, None)
        if admin_user.status == UserStatus.INACTIVE.value:
            raise BusinessException(Error.DELETE_FAILED_INACTIVE_USER, None)
        # handle validations.
        user = UserModel.find_by_username(user_name)
        membership = MembershipModel.find_membership_by_userid(user.id)
        org_id = membership.org_id
        is_valid_action = False

        # admin/owner deleteion
        admin_user_membership = MembershipModel.find_membership_by_user_and_org(
            admin_user.id, org_id)
        if admin_user_membership.membership_type_code in [ADMIN]:
            is_valid_action = True
        # staff admin deleteion
        is_staff_admin = token_info and Role.STAFF_CREATE_ACCOUNTS.value in token_info.get(
            'realm_access').get('roles')
        if is_staff_admin:
            is_valid_action = True
        # self deletion
        if user.keycloak_guid == admin_user.keycloak_guid:
            is_valid_action = True

        # is the only owner getting deleted
        if is_valid_action and membership.membership_type_code == ADMIN:
            count_of_owners = MembershipModel.get_count_active_owner_org_id(
                org_id)
            if count_of_owners == 1:
                is_valid_action = False
        if not is_valid_action:
            raise BusinessException(Error.INVALID_USER_CREDENTIALS, None)
        user.is_terms_of_use_accepted = False
        user.status = UserStatus.INACTIVE.value
        user.save()
        membership.status = Status.INACTIVE.value
        membership.save()
        update_user_request = KeycloakUser()
        update_user_request.user_name = user_name.replace(
            IdpHint.BCROS.value + '/', '')
        update_user_request.enabled = False
        KeycloakService.update_user(update_user_request)
コード例 #10
0
 def delete_otp_for_user(user_name, origin_url: str = None):
     """Reset the OTP of the user."""
     # TODO - handle when the multiple teams implemented for bceid..
     user = UserModel.find_by_username(user_name)
     membership = MembershipModel.find_membership_by_userid(user.id)
     org_id = membership.org_id
     check_auth(org_id=org_id, one_of_roles=(ADMIN, COORDINATOR, STAFF))
     try:
         KeycloakService.reset_otp(str(user.keycloak_guid))
         User.send_otp_authenticator_reset_notification(user.email, origin_url, org_id)
     except HTTPError as err:
         current_app.logger.error('update_user in keycloak failed {}', err)
         raise BusinessException(Error.UNDEFINED_ERROR, err) from err
コード例 #11
0
ファイル: user.py プロジェクト: kvangorp/sbc-auth
    def find_by_username(cls, username: str = None):
        """Given a username, this will return an Active User or None."""
        if not username:
            return None

        # find locally
        user_dao = UserModel.find_by_username(username)

        if not user_dao:
            return None

        user = User()
        user._dao = user_dao  # pylint: disable=protected-access
        return user
コード例 #12
0
ファイル: user.py プロジェクト: nitheesh-aot/sbc-auth
    def save_from_jwt_token(cls, token: dict, request_json: Dict = None):
        """Save user to database (create/update)."""
        current_app.logger.debug('save_from_jwt_token')
        if not token:
            return None
        request_json = {} if not request_json else request_json

        is_anonymous_user = token.get('accessType',
                                      None) == AccessType.ANONYMOUS.value
        if not is_anonymous_user:
            existing_user = UserModel.find_by_jwt_token(token)
        else:
            existing_user = UserModel.find_by_username(
                token.get('preferred_username'))

        first_name, last_name = User._get_names(existing_user, request_json,
                                                token)

        if existing_user is None:
            user_model = UserModel.create_from_jwt_token(
                token, first_name, last_name)
        else:
            user_model = UserModel.update_from_jwt_token(
                existing_user,
                token,
                first_name,
                last_name,
                is_login=request_json.get('isLogin', False))

        if not user_model:
            return None

        # if accepted , double check if there is a new TOS in place .IF so , update the flag to false
        if user_model.is_terms_of_use_accepted:
            document_type = DocumentType.TERMS_OF_USE_DIRECTOR_SEARCH.value if is_anonymous_user \
                else DocumentType.TERMS_OF_USE.value
            # get the digit version of the terms of service..ie d1 gives 1 ; d2 gives 2..for proper comparison
            latest_version = util.digitify(
                DocumentService.find_latest_version_by_type(document_type))
            current_version = util.digitify(
                user_model.terms_of_use_accepted_version)
            if latest_version > current_version:
                user_model.is_terms_of_use_accepted = False

        user = User(user_model)
        return user
コード例 #13
0
    def save_from_jwt_token(cls, token: dict = None):
        """Save user to database (create/update)."""
        current_app.logger.debug('save_from_jwt_token')
        if not token:
            return None
        if token.get('accessType', None) != AccessType.ANONYMOUS.value:
            existing_user = UserModel.find_by_jwt_token(token)
        else:
            existing_user = UserModel.find_by_username(token.get('preferred_username'))

        if existing_user is None:
            user_model = UserModel.create_from_jwt_token(token)
        else:
            user_model = UserModel.update_from_jwt_token(token, existing_user)

        if not user_model:
            return None

        user = User(user_model)
        return user
コード例 #14
0
ファイル: user.py プロジェクト: nitheesh-aot/sbc-auth
    def create_user_and_add_membership(
        memberships: List[dict],
        org_id,
        token_info: Dict = None,
        # pylint: disable=too-many-locals, too-many-statements, too-many-branches
        single_mode: bool = False):
        """
        Create user(s) in the  DB and upstream keycloak.

        accepts a list of memberships ie.a list of objects with username,password and membershipTpe
        single_mode can be used if called method already perfomed the authenticaiton
        single_mode= true is used now incase of invitation for admin users scenarion
        other cases should be invoked with single_mode=false
        """
        User._validate_and_throw_exception(memberships, org_id, single_mode,
                                           token_info)

        current_app.logger.debug('create_user')
        users = []
        for membership in memberships:
            username = membership['username']
            current_app.logger.debug(f'create user username: {username}')
            create_user_request = User._create_kc_user(membership)
            db_username = IdpHint.BCROS.value + '/' + username
            user_model = UserModel.find_by_username(db_username)
            re_enable_user = False
            existing_kc_user = KeycloakService.get_user_by_username(username)
            enabled_in_kc = getattr(existing_kc_user, 'enabled', True)
            if getattr(user_model, 'status',
                       None) == Status.INACTIVE.value and not enabled_in_kc:
                membership_model = MembershipModel.find_membership_by_userid(
                    user_model.id)
                re_enable_user = membership_model.org_id == org_id
            if user_model and not re_enable_user:
                current_app.logger.debug('Existing users found in DB')
                users.append(
                    User._get_error_dict(username, Error.USER_ALREADY_EXISTS))
                continue

            if membership.get('update_password_on_login',
                              True):  # by default , reset needed
                create_user_request.update_password_on_login()
            try:
                if re_enable_user:
                    kc_user = KeycloakService.update_user(create_user_request)
                else:
                    kc_user = KeycloakService.add_user(
                        create_user_request, throw_error_if_exists=True)
            except BusinessException as err:
                current_app.logger.error(
                    'create_user in keycloak failed :duplicate user {}', err)
                users.append(
                    User._get_error_dict(username, Error.USER_ALREADY_EXISTS))
                continue
            except HTTPError as err:
                current_app.logger.error('create_user in keycloak failed {}',
                                         err)
                users.append(
                    User._get_error_dict(username,
                                         Error.FAILED_ADDING_USER_ERROR))
                continue
            try:
                if re_enable_user:
                    user_model.status = Status.ACTIVE.value
                    user_model.flush()
                    membership_model.status = Status.ACTIVE.value
                    membership_model.membership_type_code = membership[
                        'membershipType']
                    membership_model.flush()
                else:
                    user_model = User._create_new_user_and_membership(
                        db_username, kc_user, membership, org_id)

                db.session.commit(
                )  # commit is for session ;need not to invoke for every object
                user_dict = User(user_model).as_dict()
                user_dict.update({
                    'http_status': http_status.HTTP_201_CREATED,
                    'error': ''
                })
                users.append(user_dict)
            except Exception as e:  # pylint: disable=broad-except
                current_app.logger.error(
                    'Error on  create_user_and_add_membership: {}', e)
                db.session.rollback()
                if re_enable_user:
                    User._update_user_in_kc(create_user_request)
                else:
                    KeycloakService.delete_user_by_username(
                        create_user_request.user_name)
                users.append(
                    User._get_error_dict(username,
                                         Error.FAILED_ADDING_USER_ERROR))
                continue

        return {'users': users}