def test_user_filter_positiv(self, mocked_getResolversOfUser): """ test the _user_filter for filtering policies by resolver specification """ Policies = { 'set_realm_test': { 'realm': 'mymixrealm', 'action': 'setrealm=mydefrealm', 'client': '*', 'user': '******', 'time': '*', 'active': 'True', 'scope': 'authorization'}} userObj = User(login='******', realm='mymixrealm') userObj.resolvers_list = ['myDefRes'] mocked_getResolversOfUser.return_value = userObj.resolvers_list res = _user_filter(Policies, userObj, scope='authorization') self.assertTrue('set_realm_test' in res, res) return
def checkSerialPass(self, serial, passw, options=None, user=None): """ This function checks the otp for a given serial :attention: the parameter user must be set, as the pin policy==1 will verify the user pin """ log.debug('checking for serial %r' % serial) tokenList = linotp.lib.token.getTokens4UserOrSerial( None, serial) if passw is None: # other than zero or one token should not happen, as serial is # unique if len(tokenList) == 1: theToken = tokenList[0] tok = theToken.token realms = tok.getRealmNames() if realms is None or len(realms) == 0: realm = getDefaultRealm() elif len(realms) > 0: realm = realms[0] userInfo = getUserInfo(tok.LinOtpUserid, tok.LinOtpIdResolver, tok.LinOtpIdResClass) user = User(login=userInfo.get('username'), realm=realm) user.info = userInfo if theToken.is_challenge_request(passw, user, options=options): (res, opt) = Challenges.create_challenge( theToken, options) res = False else: raise ParameterError('Missing parameter: pass', id=905) else: raise Exception('No token found: ' 'unable to create challenge for %s' % serial) else: log.debug('checking len(pass)=%r for serial %r' % (len(passw), serial)) (res, opt) = self.checkTokenList( tokenList, passw, user=user, options=options) return (res, opt)
def webkdc_validate(self): # Called by WebAuth via the Elm remctld scripts. # Verifies a one-time passcode and indicates how long # the token should be considered valid. param = {} try: param.update(request.params) username = param["user"] code = param["code"] user = User(username, "", "") th = TokenHandler() if ('token' in param): serial = param["token"] (ok, opt) = th.checkSerialPass(serial, code, options=None, user=user) else: (ok, opt) = th.checkUserPass(user, code) ret = { "success": ok, } if (ok): ret['expiration'] = round( time.time()) + 60 * 60, # one hour from now else: if opt == None: opt = {} ret['error'] = c.audit.get('info') log.error("[webkdc_validate] authorization failed: %s" % ret['error']) ret['code'] = -310 Session.commit() return sendResult(response, ret, 0, opt=opt) except Exception as exx: log.error("[webkdc_validate] validate/webkdc_validate failed: %r" % exx) log.error("[webkdc_validate] %s" % traceback.format_exc()) Session.rollback() return sendError( response, u"validate/webkdc_validate failed: %s" % unicode(exx), 0) finally: Session.close()
def tearDown(self): TestController.tearDown(self) authUser = User( login="******", realm=current_app.config["ADMIN_REALM_NAME"].lower(), resolver_config_identifier="adminResolver", ) self.delete_all_policies(auth_user=authUser) self.delete_all_token() self.delete_all_realms() self.delete_all_resolvers()
def test_user_nonzero(self): """ test that no sensitive data got logged """ # check that u1 is zero: either None or empty u1 = User() if u1: assert True == False # check that u2 is zero: checks if the user has a login u2 = User(realm='heydo') if u2: assert True == False # check that u3 is not zero: neither None nor empty u3 = User(login='******') if not u3: assert True == False
def get_token_realm_user(self): user = None realms = getTokenRealms(self.getSerial()) if len(realms) == 1: user = User(login="", realm=realms[0]) elif len(realms) == 0: realm = getDefaultRealm() user = User(login="", realm=realm) log.info("No token realm found - using default realm.") else: msg = ("Multiple realms for token found. But one dedicated " "realm is required for further processing.") log.error(msg) raise Exception(msg) return user
def test_JWT_authentifictaion(app): authUser = User( login="******", realm="def_realm", resolver_config_identifier="def_resolver", ) with patch("linotp.lib.user.request_context") as mocked_request_context: mocked_request_context.get.return_value = authUser user = getUserFromRequest() assert user.login == "JWT_AUTHENTICATED_USER"
def test_empty_auth(app): authUser = User( login="", realm="", resolver_config_identifier="", ) with patch("linotp.lib.user.request_context") as mocked_request_context: mocked_request_context.get.return_value = authUser user = getUserFromRequest() assert user.login == ""
def test_singechar_wildcard( self, mocked_tokenIterator_init, mocked_token_owner_iterator, mocked_getTokens4UserOrSerial, ): valid_realms = ["*"] mocked_tokenIterator_init.return_value = None tik = TokenIterator(None, None) # ------------------------------------------------------------------ -- # test the old behaviour with '*' wildcard, which takes the # expensive code path user = User(login="******", realm="user2") tik._get_user_condition(user, valid_realms) assert mocked_token_owner_iterator.call_count == 1 # ------------------------------------------------------------------ -- mocked_token_owner_iterator.called = False mocked_token_owner_iterator.call_count = 0 # ------------------------------------------------------------------ -- # now test the setting of the '.' which causes a differen code path mocked_getTokens4UserOrSerial.return_value = [] user = User(login="******", realm="user2") tik._get_user_condition(user, valid_realms) assert not mocked_token_owner_iterator.called assert mocked_getTokens4UserOrSerial.call_count == 1 return
def test_autenroll_wo_pass( self, mocked_policy_src_realm, mocked_policy_autosignment_wo, mockedgetTokens4UserOrSerial, mocked_getTokensOfType, mocked_assignToken, mocked_context, ): thdle = TokenHandler() options = {} user = User("Hugo", realm="def_realm") otp = "123467" class Token(object): LinOtpCountWindow = 10 typ = "" def setType(self, type_name): self.typ = type_name def getType(self): return self.typ def getSerial(self): return "ABCDEFG" aToken = Token() class MockPasswordTokenClass(PasswordTokenClass): def check_otp_exist(self, *args, **kwargs): return 1 pwtoken = MockPasswordTokenClass(aToken) mocked_policy_src_realm.return_value = None mocked_policy_autosignment_wo.return_value = True mockedgetTokens4UserOrSerial.return_value = [] mocked_getTokensOfType.return_value = [pwtoken] mocked_assignToken.return_value = True g.audit = {} res = thdle.auto_assign_otp_only(otp, user, options) assert res assert mocked_assignToken.called return
def test_get_autoassignment_from_realm( self, mocked_get_client_policy, mocked_get_client, mocked_get_policy_definitions, ): user = User("Hugo", realm="Home_realm") mocked_get_client.return_value = "127.0.0.1" src_realm = "token-realm " mocked_get_client_policy.return_value = { "my_autoassign_policy_wo_pass": { "realm": "mydefrealm", "active": "True", "client": "*", "user": "******", "time": "*", "action": "autoassignment_from_realm=%s" % src_realm, "scope": "enrollment", } } mocked_get_policy_definitions.return_value = { "enrollment": { "autoassignment_from_realm": { "type": "str" } } } realm = get_autoassignment_from_realm(user) assert src_realm.strip() == realm src_realm = " " mocked_get_client_policy.return_value = { "my_autoassign_policy_wo_pass": { "realm": "mydefrealm", "active": "True", "client": "127.0.0.1", "user": "******", "time": "*", "action": "autoassignment_from_realm=%s" % src_realm, "scope": "enrollment", } } realm = get_autoassignment_from_realm(user) assert not realm return
def test_get_autoassignment_from_realm( self, mocked_get_client_policy, mocked_get_client, mocked_get_policy_definitions, ): user = User('Hugo', realm='Home_realm') mocked_get_client.return_value = '127.0.0.1' src_realm = 'token-realm ' mocked_get_client_policy.return_value = { 'my_autoassign_policy_wo_pass': { 'realm': 'mydefrealm', 'active': 'True', 'client': '*', 'user': '******', 'time': '*', 'action': 'autoassignment_from_realm=%s' % src_realm, 'scope': 'enrollment' } } mocked_get_policy_definitions.return_value = { 'enrollment': { 'autoassignment_from_realm': { 'type': 'str' } } } realm = get_autoassignment_from_realm(user) assert src_realm.strip() == realm src_realm = ' ' mocked_get_client_policy.return_value = { 'my_autoassign_policy_wo_pass': { 'realm': 'mydefrealm', 'active': 'True', 'client': '127.0.0.1', 'user': '******', 'time': '*', 'action': 'autoassignment_from_realm=%s' % src_realm, 'scope': 'enrollment' } } realm = get_autoassignment_from_realm(user) assert not realm return
def test_simple_esisting_user_class_comparisson(self, mock_getUserInfo): """test for user object comparison with existing users""" mock_getUserInfo.return_value = {"userid": "12"} u1 = User(login="******", realm="heydo") u2 = User(login="******", realm="heydo") u1._exists = True u2._exists = True assert u1 == u2 u3 = User(login="******", realm="heydo") u3._exists = True with patch.object(u3, "getUserInfo") as u3_mock_getUserInfo: u3_mock_getUserInfo.return_value = {"userid": "13"} assert u1 != u3
def test_simple_esisting_user_class_comparisson(self, mock_getUserInfo): """ test for user object comparison with existing users""" mock_getUserInfo.return_value = {'userid': '12'} u1 = User(login='******', realm='heydo') u2 = User(login='******', realm='heydo') u1._exists = True u2._exists = True assert u1 == u2 u3 = User(login='******', realm='heydo') u3._exists = True with patch.object(u3, 'getUserInfo') as u3_mock_getUserInfo: u3_mock_getUserInfo.return_value = {'userid': '13'} assert u1 != u3
def test_user_regex_match2(self, mock_domain_comp, mock_domain_exists): """evaluate for user3@realmx with resolver 'resolver' as there is no dedicated user policy, the policies with resolver or realm will match. """ mock_domain_comp.side_effect = fn_mock_domain_comp mock_domain_exists.side_effect = fn_mock_domain_comp # define user user = User( login="******", realm="realmx", resolver_config_identifier="resolver", ) # define policies policies = {} policies.update(create_policy("self1", user="******")) policies.update(create_policy("self2", user="******")) policies.update(create_policy("self3", user="******")) policies.update(create_policy("self4", user="******")) policies.update(create_policy("self5", user="******")) policies.update( create_policy("self6", user="******") ) policies.update( create_policy( "self7", user="******" ) ) policies.update( create_policy("self8", user="******") ) # evaluate the policies wrt. the given user p_eval = PolicyEvaluator(policies) p_eval.filter_for_user(user) matching_policies = p_eval.evaluate() # compare the results expected_matches = set(["self6", "self7"]) matching_policies_names = set(matching_policies.keys()) assert matching_policies_names == expected_matches
def test_validate_check_with_serial( self, mocked_geUserId, mocked_get_auth_forward, mocked_checkTokenList, mocked_auth_forward_no_token, ): """ test calling checkUserPass with serial in the list of optional args """ # ------------------------------------------------------------------ -- # test setup user = User("root", "anywhere") passw = "Test123!" serial = "tok123" options = {"serial": serial} mocked_auth_forward_no_token.return_value = True mocked_geUserId.return_value = ("uid", "resolver", "resolverClass") mocked_get_auth_forward.return_value = None mocked_checkTokenList.return_value = True, None # ------------------------------------------------------------------ -- # if serial was given, there should be only one token in the tokenlist # when calling of checkTokenList vh = ValidationHandler() _result = vh.checkUserPass(user, passw, options=options) call_args = mocked_checkTokenList.call_args token_list = call_args[0][0] assert len(token_list) == 1 # ------------------------------------------------------------------ -- # if no serial was given, there should be 2 token in the tokenlist # when calling of checkTokenList vh = ValidationHandler() _result = vh.checkUserPass(user, passw, options=None) call_args = mocked_checkTokenList.call_args token_list = call_args[0][0] assert len(token_list) > 1 return
def test_user_compare(self): """ test the user list comparison method """ user_conditions = ( # exact name match 'Hugo, ' # negative test '!Emma, ' # wildcard realm test '*@realm, ' # wildcard name test 'a*, ' # negative wildcad name test '!*z') hugo = User('Hugo', 'realm') self.assertTrue( user_list_compare(user_conditions, hugo)) emma = User('Emma') self.assertFalse( user_list_compare(user_conditions, emma)) betonz = User('betonz', 'realm') self.assertFalse( user_list_compare(user_conditions, betonz)) wanda = User('wanda', 'realm') self.assertTrue( user_list_compare(user_conditions, wanda)) wanda2 = 'wanda@realm' self.assertTrue( user_list_compare(user_conditions, wanda2)) return
def test_user_exact_match2(self, mock_domain_comp, mock_domain_exists): """evaluate for user2@realm with resolver 'resolver' dedicated only user2 policies whith fqn should match and not for realm! """ mock_domain_comp.side_effect = fn_mock_domain_comp mock_domain_exists.side_effect = fn_mock_domain_comp # define user user = User( login="******", realm="realm", resolver_config_identifier="resolver" ) # define policies policies = {} policies.update(create_policy("self1", user="******")) policies.update(create_policy("self2", user="******")) policies.update(create_policy("self3", user="******")) policies.update(create_policy("self4", user="******")) policies.update(create_policy("self5", user="******")) policies.update( create_policy("self6", user="******") ) policies.update( create_policy( "self7", user="******" ) ) policies.update( create_policy("self8", user="******") ) # evaluate the policies wrt. the given user p_eval = PolicyEvaluator(policies) p_eval.filter_for_user(user) matching_policies = p_eval.evaluate() # compare the results expected_matches = set(["self6", "self8"]) matching_policies_names = set(matching_policies.keys()) assert ( matching_policies_names == expected_matches ), matching_policies_names
def test_get_default_provider(self): """ get the default providers if no policy """ with patch("linotp.provider.get_client_policy") as mock_policy: with patch("linotp.provider._get_default_provider_name" ) as mock_default: mock_policy.return_value = {} mock_default.return_value = 'default' provider = get_provider_from_policy('sms', user=User( 'login', 'realm')) assert provider == ['default']
def test_isTokenOwner_no_user(self): """ test if no user is given """ serial = "fake_123_token" user = User() th = TokenHandler() with pytest.raises(TokenAdminError) as exx: th.isTokenOwner(serial, user) exx.match('no user found') return
def test_isTokenOwner_no_user(self): """ test if no user is given """ serial = "fake_123_token" user = User() th = TokenHandler() with self.assertRaises(TokenAdminError) as exx: th.isTokenOwner(serial, user) assert 'no user found' in exx.exception.message return
def test_get_default_provider(self): """ get the default providers if no policy """ with patch("linotp.lib.policy.get_client_policy") as mock_policy: with patch("linotp.provider._get_default_provider_name" ) as mock_default: mock_policy.return_value = {} mock_default.return_value = "default" provider = get_provider_from_policy("sms", user=User( "login", "realm")) assert provider == ["default"]
def test_compare_user(self, mocked_getUserId, mocked_getTokens4UserOrSerial): """ test for isTokenOwner the isTokenOwner should only compare the resolver conf and user id """ th = TokenHandler() user = User(login="******", realm="realm", resolver_config_identifier="blah") # ----------------------------------------------------------------- -- # test for same user as uid is the same and the resolver class with # conf is the same, only the resolver description is different mocked_getUserId.return_value = ( "1234", "migrated resolver info", "passwdResolver.conf1", ) mocked_getTokens4UserOrSerial.return_value = [MockedToken()] result = th.isTokenOwner("TokenSerial", user) assert result # ----------------------------------------------------------------- -- # test for different user as uid is the same and the resolver class # with different conf, but same resolver description mocked_getUserId.return_value = ( "1234", "resolver info", "passwdResolver.conf2", ) mocked_getTokens4UserOrSerial.return_value = [MockedToken()] result = th.isTokenOwner("TokenSerial", user) assert not result return
def get_context(config, user, realm, client): """ get the user dependend rendering context :param user: the selfservice user :param realm: the selfservice realm :param client: the selfservice client info - required for pre_context :return: context dict, with all rendering attributes """ req_context = get_pre_context(client) req_context["user"] = user req_context["realm"] = realm authUser = User(user, realm) req_context["imprint"] = get_imprint(req_context["realm"]) req_context["tokenArray"] = getTokenForUser(authUser) # show the defined actions, which have a rendering actions = getSelfserviceActions(authUser) req_context["actions"] = actions for policy in actions: if "=" in policy: (name, val) = policy.split('=') val = val.strip() # try if val is a simple numeric - # w.r.t. javascript evaluation try: nval = int(val) except: nval = val req_context[name.strip()] = nval req_context["dynamic_actions"] = add_dynamic_selfservice_enrollment( config, actions) # TODO: to establish all token local defined policies additional_policies = add_dynamic_selfservice_policies(config, actions) for policy in additional_policies: req_context[policy] = -1 # TODO: add_local_policies() currently not implemented!! req_context["otplen"] = -1 req_context["totp_len"] = -1 return req_context
def test_tz_in_cookies(self, mock_get_cookie_expiry, mock_get_cookie_secret): """ verify that the userservice cookie format is rfc6265 compliant """ mock_get_cookie_secret.return_value = binascii.hexlify( Secret.encode("utf-8")) mock_get_cookie_expiry.return_value = False ret = create_auth_cookie(User("hans"), "127.0.0.1") _session, _expiration_dt, expiration_str = ret datetime.datetime.strptime(expiration_str, RFC6265_TIMEFORMAT) with pytest.raises(ValueError, match="does not match format"): datetime.datetime.strptime(expiration_str, OLD_TIMEFORMAT)
def setUp(self): TestController.setUp(self) # clean setup authUser = User( login="******", realm=current_app.config["ADMIN_REALM_NAME"].lower(), resolver_config_identifier="adminResolver", ) self.delete_all_policies(auth_user=authUser) self.delete_all_token() self.delete_all_realms() self.delete_all_resolvers() # create the common resolvers and realm self.create_common_resolvers() self.create_common_realms() self.create_extra_resolver()
def test_user_regex_match2(self, mock_domain_comp, mock_domain_exists): """evaluate for user3@realmx with resolver 'resolver' as there is no dedicated user policy, the policies with resolver or realm will match. """ mock_domain_comp.side_effect = fn_mock_domain_comp mock_domain_exists.side_effect = fn_mock_domain_comp # define user user = User( login='******', realm='realmx', resolver_config_identifier='resolver' ) # define policies policies = {} policies.update(create_policy('self1', user='******')) policies.update(create_policy('self2', user='******')) policies.update(create_policy('self3', user='******')) policies.update(create_policy('self4', user='******')) policies.update(create_policy('self5', user='******')) policies.update(create_policy( 'self6', user='******')) policies.update(create_policy( 'self7', user='******')) policies.update(create_policy( 'self8', user='******')) # evaluate the policies wrt. the given user p_eval = PolicyEvaluator(policies) p_eval.filter_for_user(user) matching_policies = p_eval.evaluate() # compare the results expected_matches = set(['self6', 'self7']) matching_policies_names = set(matching_policies.keys()) assert matching_policies_names == expected_matches
def test_isTokenOwner_no_token(self, mocked_getUserId, mocked_getTokens4UserOrSerial): """ test if no token is found """ mocked_getUserId.return_value = ('123', 'res', 'resC') mocked_getTokens4UserOrSerial.return_value = [] serial = "fake_123_token" user = User(login="******") th = TokenHandler() with pytest.raises(TokenAdminError) as exx: th.isTokenOwner(serial, user) exx.match('no token found') return
def test_isTokenOwner_no_token(self, mocked_getUserId, mocked_getTokens4UserOrSerial): """ test if no token is found """ mocked_getUserId.return_value = ('123', 'res', 'resC') mocked_getTokens4UserOrSerial.return_value = [] serial = "fake_123_token" user = User(login="******") th = TokenHandler() with self.assertRaises(TokenAdminError) as exx: th.isTokenOwner(serial, user) assert 'no token found' in exx.exception.message return
def setUp(self): self.ADMIN_REALM = current_app.config["ADMIN_REALM_NAME"].lower() self.ADMIN_RESOLVER = current_app.config["ADMIN_RESOLVER_NAME"] self.admin_user = User( login="******", realm=self.ADMIN_REALM, resolver_config_identifier=self.ADMIN_RESOLVER, ) TestController.setUp(self) # clean setup self.delete_all_policies(auth_user=self.admin_user) self.delete_all_token() self.delete_all_realms() self.delete_all_resolvers() # create the common resolvers and realm self.create_common_resolvers() self.create_common_realms()
def test_check_admin_auth_case_sensitive_resolver_names(app): user = User(login="******", realm="realm", resolver_config_identifier="resolver") policies = { "user": "", "scope": "selfservice", "action": "p1", "realms": [], "active": True, "client": "*", "time": "* * * * * *;", "resolvers": ["RESOLVER"], } assert not checkAdminAuthorization(policies, None, user), ( "checkAdminAuthorization resolver name comparison " "is not case-sensitive")
def test_compare_user(self, mocked_getUserId, mocked_getTokens4UserOrSerial): """ test for isTokenOwner the isTokenOwner should only compare the resolver conf and user id """ th = TokenHandler() user = User(login='******', realm='realm', resolver_config_identifier='blah') # ----------------------------------------------------------------- -- # test for same user as uid is the same and the resolver class with # conf is the same, only the resolver description is different mocked_getUserId.return_value = ('1234', 'migrated resolver info', 'passwdResolver.conf1') mocked_getTokens4UserOrSerial.return_value = [MockedToken()] result = th.isTokenOwner('TokenSerial', user) self.assertTrue(result) # ----------------------------------------------------------------- -- # test for different user as uid is the same and the resolver class # with different conf, but same resolver description mocked_getUserId.return_value = ('1234', 'resolver info', 'passwdResolver.conf2') mocked_getTokens4UserOrSerial.return_value = [MockedToken()] result = th.isTokenOwner('TokenSerial', user) self.assertFalse(result) return
def legacy_getPolicy(param, only_active=True): ''' Function to retrieve the list of policies. attributes: - name: (optional) will only return the policy with the name - user: (optional) will only return the policies for this user - realm: (optional) will only return the policies of this realm - scope: (optional) will only return the policies within this scope - action: (optional) will only return the policies with this action The action can also be something like "otppin" and will return policies containing "otppin = 2" :return: a dictionary with the policies. The name of the policy being the key ''' # log.debug("[getPolicy] params %s" % str(param)) Policies = {} # First we load ALL policies from the Config lPolicies = get_copy_of_policies() if param.get('name', None): # If a named policy was requested, we add # the policy if the name does match case insensitiv p_name = param['name'].lower() for pol_name in lPolicies: if pol_name.lower() == p_name: Policies[pol_name] = lPolicies[pol_name] else: Policies = lPolicies # Now we need to clean up policies, that are inactive if only_active: pol2delete = [] for polname, policy in Policies.items(): pol_active = policy.get("active", "True") if pol_active == "False": pol2delete.append(polname) for polname in pol2delete: del Policies[polname] # Now we need to clean up realms, that were not requested pol2delete = [] if param.get('realm', None) is not None: # log.debug("[getPolicy] cleanup acccording to realm %s" # % param["realm"]) for polname, policy in Policies.items(): delete_it = True # log.debug("[getPolicy] evaluating policy %s: %s" # % (polname, str(policy))) if policy.get("realm") is not None: pol_realms = [p.strip() for p in policy['realm'].lower().split(',')] # log.debug("[getPolicy] realms in policy %s: %s" # % (polname, str(pol_realms) )) for r in pol_realms: # log.debug("[getPolicy] Realm: %s" % r) if r == param['realm'].lower() or r == '*': # log.debug( "[getPolicy] Setting delete_it to false. # Se we are using policy: %s" % str(polname)) delete_it = False if delete_it: pol2delete.append(polname) for polname in pol2delete: del Policies[polname] pol2delete = [] if param.get('scope', None) is not None: # log.debug("[getPolicy] cleanup acccording to scope %s" # % param["scope"]) for polname, policy in Policies.items(): if policy['scope'].lower() != param['scope'].lower(): pol2delete.append(polname) for polname in pol2delete: del Policies[polname] pol2delete = [] if param.get('action', None) is not None: # log.debug("[getPolicy] cleanup acccording to action %s" # % param["action"]) param_action = param['action'].strip().lower() for polname, policy in Policies.items(): delete_it = True # log.debug("[getPolicy] evaluating policy %s: %s" # % (polname, str(policy))) if policy.get("action") is not None: pol_actions = [p.strip() for p in policy.get('action', ""). lower().split(',')] # log.debug("[getPolicy] actions in policy %s: %s " # % (polname, str(pol_actions) )) for policy_action in pol_actions: if policy_action == '*' or policy_action == param_action: # If any action (*) or the exact action we are looking # for matches, then keep the policy # e.g. otppin=1 matches when we search for 'otppin=1' delete_it = False elif policy_action.split('=')[0].strip() == param_action: # If the first part of the action matches then keep the # policy # e.g. otppin=1 matches when we search for 'otppin' delete_it = False else: # No match, delete_it = True pass if delete_it: pol2delete.append(polname) for polname in pol2delete: del Policies[polname] pol2delete = [] wildcard_match = {} exact_user_match = {} wildcard_user_match = {} if param.get('user', None) is not None: # log.debug("cleanup acccording to user %s" % param["user"]) for polname, policy in Policies.items(): if policy.get('user'): pol_users = [p.strip() for p in policy.get('user').lower().split(',')] # log.debug("[getPolicy] users in policy %s: %s" # % (polname, str(pol_users) )) else: log.error("Empty userlist in policy '%s' not supported!" % polname) raise Exception("Empty userlist in policy '%s' not supported!" % polname) delete_it = True # first check of wildcard in users if '*' in pol_users: wildcard_match[polname] = policy delete_it = False # then check for direct name match if delete_it: if (param['user'].lower() in pol_users or param['user'] in pol_users): exact_user_match[polname] = policy delete_it = False if delete_it: # we support the verification of the user, # to be in a resolver for the admin and system scope local_scope = param.get('scope', '').lower() if local_scope in ['admin', 'system', 'monitoring', 'authentication', 'reporting.access']: policy_users = policy.get('user', '').split(',') userObj = User(login=param['user']) if 'realm' in param: userObj.realm = param['realm'] else: import linotp.lib.realm userObj.realm = linotp.lib.realm.getDefaultRealm() # we do the extended user defintion comparison res = _filter_admin_user(policy_users, userObj) if res is True: wildcard_user_match[polname] = policy delete_it = False if delete_it: pol2delete.append(polname) for polname in pol2delete: del Policies[polname] # if we got policies and a user is defined on request if len(Policies) > 0: if exact_user_match: Policies = exact_user_match log.debug("getting exact user match %r for params %s", exact_user_match, param) elif wildcard_user_match: Policies = wildcard_user_match log.debug("getting wildcard user match %r for params %s", wildcard_user_match, param) elif wildcard_match: Policies = wildcard_match log.debug("getting wildcard user match %r for params %s", wildcard_match, param) # only do the realm filtering if action was filtered before if 'action' in param: Policies = _post_realm_filter(Policies, param) log.debug("getting policies %s for params %s" % (Policies, param)) return Policies
def tokenview_flexi(self): ''' This function is used to fill the flexigrid. Unlike the complex /admin/show function, it only returns a simple array of the tokens. ''' param = self.request_params try: c.page = param.get("page") c.filter = param.get("query") c.qtype = param.get("qtype") c.sort = param.get("sortname") c.dir = param.get("sortorder") c.psize = param.get("rp") filter_all = None filter_realm = None user = User() if c.qtype == "loginname": # we take by default the given expression as a loginname, # especially if it contains a "*" wildcard. # it only might be more, a user and a realm, if there # is an '@' sign in the loginname and the part after the # last '@' sign is matching an existing realm user = User(login=c.filter) if "*" not in c.filter and "@" in c.filter: login, _ , realm = c.filter.rpartition("@") if realm.lower() in getRealms(): user = User(login, realm) if not user.exists(): user = User(login=c.filter) elif c.qtype == "all": filter_all = c.filter elif c.qtype == "realm": filter_realm = c.filter # check admin authorization res = checkPolicyPre('admin', 'show', param , user=user) filterRealm = res['realms'] # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. pol = getAdminPolicies("show") # If there are no admin policies, we are allowed to see all realms if not pol['active']: filterRealm = ["*"] # check if we only want to see ONE realm or see all realms we are allowerd to see. if filter_realm: if filter_realm in filterRealm or '*' in filterRealm: filterRealm = [filter_realm] log.debug("[tokenview_flexi] admin >%s< may display the following realms: %s" % (pol['admin'], pol['realms'])) log.debug("[tokenview_flexi] page: %s, filter: %s, sort: %s, dir: %s" % (c.page, c.filter, c.sort, c.dir)) if c.page is None: c.page = 1 if c.psize is None: c.psize = 20 log.debug("[tokenview_flexi] calling TokenIterator for user=%s@%s, filter=%s, filterRealm=%s" % (user.login, user.realm, filter_all, filterRealm)) c.tokenArray = TokenIterator(user, None, c.page , c.psize, filter_all, c.sort, c.dir, filterRealm=filterRealm) c.resultset = c.tokenArray.getResultSetInfo() # If we have chosen a page to big! lines = [] for tok in c.tokenArray: lines.append( {'id' : tok['LinOtp.TokenSerialnumber'], 'cell': [ tok['LinOtp.TokenSerialnumber'], tok['LinOtp.Isactive'], tok['User.username'], tok['LinOtp.RealmNames'], tok['LinOtp.TokenType'], tok['LinOtp.FailCount'], tok['LinOtp.TokenDesc'], tok['LinOtp.MaxFail'], tok['LinOtp.OtpLen'], tok['LinOtp.CountWindow'], tok['LinOtp.SyncWindow'], tok['LinOtp.Userid'], tok['LinOtp.IdResClass'].split('.')[-1], ] } ) # We need to return 'page', 'total', 'rows' res = { "page": int(c.page), "total": c.resultset['tokens'], "rows": lines } c.audit['success'] = True Session.commit() # The flexi handler should support std LinOTP output return sendResult(response, res) except PolicyException as pe: log.exception("[tokenview_flexi] Error during checking policies: %r" % pe) Session.rollback() return sendError(response, unicode(pe), 1) except Exception as e: log.exception("[tokenview_flexi] failed: %r" % e) Session.rollback() return sendError(response, e) finally: Session.close()