def tokeninfo(self): ''' this returns the contents of /admin/show?serial=xyz in a html format ''' param = request.params try: serial = getParam(param, 'serial', required) filterRealm = "" # check admin authorization res = checkPolicyPre('admin', 'show', param) 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 not pol['active']: filterRealm = ["*"] log.info("[tokeninfo] admin >%s< may display the following realms: %s" % (res['admin'], filterRealm)) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm) ### now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo['LinOtp.TokenInfo'] = json.loads(c.tokeninfo['LinOtp.TokenInfo']) except: pass return render('/manage/tokeninfo.mako') except PolicyException as pe: log.error("[tokeninfo] Error during checking policies: %r" % pe) log.error("[tokeninfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe), 1) except Exception as e: log.error("[tokeninfo] failed! %r" % e) log.error("[tokeninfo] %s" % traceback.format_exc()) Session.rollback() return sendError(response, e) finally: Session.close() log.debug('[tokeninfo] done')
def tokeninfo(self): ''' this returns the contents of /admin/show?serial=xyz in an html format ''' param = self.request_params try: try: serial = param['serial'] except KeyError: raise ParameterError("Missing parameter: 'serial'") filterRealm = "" # check admin authorization res = checkPolicyPre('admin', 'show', param) # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. filterRealm = ["*"] if res['active'] and res['realms']: filterRealm = res['realms'] log.info("[tokeninfo] admin >%s< may display the following realms:" " %s" % (res['admin'], filterRealm)) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator(User("", "", ""), serial, filterRealm=filterRealm) # now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo['LinOtp.TokenInfo'] = json.loads( c.tokeninfo['LinOtp.TokenInfo']) except: pass return render('/manage/tokeninfo.mako').decode('utf-8') except PolicyException as pe: log.exception("[tokeninfo] Error during checking policies: %r" % pe) db.session.rollback() return sendError(response, str(pe), 1) except Exception as e: log.exception("[tokeninfo] failed! %r" % e) db.session.rollback() return sendError(response, e)
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_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 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: uid = tok['LinOtp.Userid'] uid = uid.decode('utf-8') if isinstance(uid, bytes) else uid 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'], uid, 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, str(pe), 1) except Exception as e: log.exception("[tokenview_flexi] failed: %r" % e) Session.rollback() return sendError(response, e) finally: Session.close()
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 = request.params try: #serial = getParam(param,"serial",optional) c.page = getParam(param, "page", optional) c.filter = getParam(param, "query", optional) c.qtype = getParam(param, "qtype", optional) c.sort = getParam(param, "sortname", optional) c.dir = getParam(param, "sortorder", optional) c.psize = getParam(param, "rp", optional) filter_all = None filter_realm = None user = User() if c.qtype == "loginname": if "@" in c.filter: (login, realm) = c.filter.split("@") user = User(login, realm) else: user = User(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: # Arrange the table more helpfully. lines.append({ 'id': tok['LinOtp.TokenSerialnumber'], 'cell': [ tok['LinOtp.TokenSerialnumber'], tok['LinOtp.TokenType'], tok['LinOtp.TokenDesc'], tok['LinOtp.Isactive'], tok['User.username'], tok['LinOtp.Userid'], tok['LinOtp.FailCount'], tok['LinOtp.MaxFail'], tok['LinOtp.OtpLen'], tok['LinOtp.CountWindow'], tok['LinOtp.SyncWindow'], ] }) # We need to return 'page', 'total', 'rows' response.content_type = 'application/json' res = { "page": int(c.page), "total": c.resultset['tokens'], "rows": lines } c.audit['success'] = True Session.commit() return json.dumps(res, indent=3) except PolicyException as pe: log.error("[tokenview_flexi] Error during checking policies: %r" % pe) log.error("[tokenview_flexi] %s" % traceback.format_exc()) Session.rollback() return sendError(response, unicode(pe), 1) except Exception as e: log.error("[tokenview_flexi] failed: %r" % e) log.error("[tokenview_flexi] %s" % traceback.format_exc()) Session.rollback() return sendError(response, e) finally: Session.close() log.debug("[tokenview_flexi] done")
def tokeninfo(self): """ this returns the contents of /admin/show?serial=xyz in an html format """ param = self.request_params try: try: serial = param["serial"] except KeyError: raise ParameterError("Missing parameter: 'serial'") filterRealm = "" # check admin authorization res = checkPolicyPre("admin", "show", param) # check if policies are active at all # If they are not active, we are allowed to SHOW any tokens. filterRealm = ["*"] if res["active"] and res["realms"]: filterRealm = res["realms"] log.info( "[tokeninfo] admin >%s< may display the following realms:" " %s", res["admin"], filterRealm, ) log.info("[tokeninfo] displaying tokens: serial: %s", serial) toks = TokenIterator( User("", "", ""), serial, filterRealm=filterRealm ) # now row by row lines = [] for tok in toks: lines.append(tok) if len(lines) > 0: c.tokeninfo = lines[0] else: c.tokeninfo = {} for k in c.tokeninfo: if "LinOtp.TokenInfo" == k: try: # Try to convert string to Dictionary c.tokeninfo["LinOtp.TokenInfo"] = json.loads( c.tokeninfo["LinOtp.TokenInfo"] ) except BaseException: pass return render("/manage/tokeninfo.mako").decode("utf-8") except PolicyException as pe: log.error("[tokeninfo] Error during checking policies: %r", pe) db.session.rollback() return sendError(response, pe, 1) except Exception as exx: log.error("[tokeninfo] failed! %r", exx) db.session.rollback() return sendError(response, exx)
def tokens(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: page = param.get("page", 1) qfilter = param.get("query") qtype = param.get("qtype", 'all') sort = param.get("sortname", ) direction = param.get("sortorder", "desc") psize = param.get("rp", 20) filter_all = None filter_realm = None user = User() if 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=qfilter) if "*" not in qfilter and "@" in qfilter: login, _, realm = qfilter.rpartition("@") if realm.lower() in getRealms(): user = User(login, realm) if not user.exists(): user = User(login=qfilter) elif qtype == "all": filter_all = qfilter elif qtype == "realm": filter_realm = qfilter # 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] tokenArray = TokenIterator( user, None, page, psize, filter_all, sort, direction, filterRealm=filterRealm) resultset = tokenArray.getResultSetInfo() # If we have chosen a page to big! lines = [] for tok in 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(page), "total": resultset['tokens'], "rows": lines } c.audit['success'] = True Session.commit() return sendResult(response, res) except PolicyException as pex: log.exception("Error during checking policies") Session.rollback() return sendError(response, pex, 1) except Exception as exx: log.exception("tokens lookup failed!") Session.rollback() return sendError(response, exx) finally: Session.close()