"Fossies" - the Fresh Open Source Software Archive

Member "LinOTP-release-2.11/linotpd/src/linotp/lib/base.py" (12 Nov 2019, 26639 Bytes) of package /linux/misc/LinOTP-release-2.11.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "base.py" see the Fossies "Dox" file reference documentation.

    1 # -*- coding: utf-8 -*-
    2 #
    3 #    LinOTP - the open source solution for two factor authentication
    4 #    Copyright (C) 2010 - 2019 KeyIdentity GmbH
    5 #
    6 #    This file is part of LinOTP server.
    7 #
    8 #    This program is free software: you can redistribute it and/or
    9 #    modify it under the terms of the GNU Affero General Public
   10 #    License, version 3, as published by the Free Software Foundation.
   11 #
   12 #    This program is distributed in the hope that it will be useful,
   13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
   14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   15 #    GNU Affero General Public License for more details.
   16 #
   17 #    You should have received a copy of the
   18 #               GNU Affero General Public License
   19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
   20 #
   21 #
   22 #    E-mail: linotp@keyidentity.com
   23 #    Contact: www.linotp.org
   24 #    Support: www.keyidentity.com
   25 #
   26 '''The Controller's Base class '''
   27 import os
   28 import re
   29 
   30 from pylons.i18n.translation import _ as translate
   31 from pylons.i18n.translation import set_lang
   32 from pylons.i18n import LanguageError
   33 
   34 from pylons.controllers import WSGIController
   35 
   36 from pylons import tmpl_context as c
   37 from pylons import config
   38 from pylons import request
   39 
   40 from linotp.lib.config import getLinotpConfig
   41 from linotp.lib.resolver import initResolvers
   42 from linotp.lib.resolver import setupResolvers
   43 from linotp.lib.resolver import closeResolvers
   44 from linotp.lib.resolver import getResolverList
   45 
   46 from linotp.lib.user import getUserFromRequest
   47 from linotp.lib.user import getUserFromParam
   48 from linotp.lib.user import NoResolverFound
   49 
   50 from linotp.lib.realm import getDefaultRealm
   51 from linotp.lib.realm import getRealms
   52 
   53 from linotp.lib.type_utils import boolean
   54 
   55 from linotp.lib.config.db_api import _retrieveAllConfigDB
   56 from linotp.lib.config.global_api import getGlobalObject
   57 from linotp.lib.crypto import init_key_partition
   58 
   59 
   60 from linotp.model import meta
   61 from linotp.lib.openid import SQLStorage
   62 
   63 from linotp.lib.context import request_context
   64 from linotp.lib.context import request_context_safety
   65 from linotp.lib.logs import init_logging_config
   66 from linotp.lib.logs import log_request_timedelta
   67 
   68 # this is a hack for the static code analyser, which
   69 # would otherwise show session.close() as error
   70 import linotp.model.meta
   71 
   72 #
   73 # manual schema migration
   74 # - should become part of schema migration tool like alembic
   75 from linotp.model.migrate import run_data_model_migration
   76 
   77 from linotp.lib.config import getLinotpConfig
   78 from linotp.lib.policy.util import parse_policies
   79 
   80 from linotp.lib.util import get_client
   81 from uuid import uuid4
   82 from datetime import datetime
   83 
   84 import logging
   85 log = logging.getLogger(__name__)
   86 
   87 Session = linotp.model.meta.Session
   88 
   89 Audit = config.get('audit')
   90 
   91 # HTTP-ACCEPT-LANGUAGE strings are in the form of i.e.
   92 # de-DE, de; q=0.7, en; q=0.3
   93 accept_language_regexp = re.compile(r'\s*([^\s;,]+)\s*[;\s*q=[0-9.]*]?\s*,?')
   94 
   95 
   96 def set_config(key, value, typ, description=None, update=False):
   97     '''
   98     create an intial config entry, if it does not exist
   99 
  100     :param key: the key
  101     :param value: the value
  102     :param description: the description of the key
  103 
  104     :return: nothing
  105     '''
  106 
  107     count = Session.query(linotp.model.Config).filter(
  108                           linotp.model.Config.Key == u"linotp." + key).count()
  109 
  110     if count == 0:
  111         config_entry = linotp.model.Config(key, value,
  112                                            Type=typ, Description=description)
  113         Session.add(config_entry)
  114 
  115     elif update:
  116         config_entry = Session.query(linotp.model.Config).filter(
  117                     linotp.model.Config.Key == u"linotp." + key).first()
  118 
  119         if not key.startswith('linotp.'):
  120             key = u'linotp.' + key
  121 
  122         if isinstance(key, str):
  123             key = key.encode()
  124 
  125         config_entry.Key = key
  126 
  127         if isinstance(value, str):
  128             value = value.encode()
  129 
  130         config_entry.Value = value
  131 
  132         if isinstance(typ, str):
  133             typ = typ.encode()
  134 
  135         config_entry.Type = typ
  136 
  137         if isinstance(description, str):
  138             description = description.encode()
  139 
  140         config_entry.Description = description
  141 
  142         Session.add(config_entry)
  143 
  144     return
  145 
  146 
  147 def get_config(key):
  148     '''
  149     get an intial config entry, if it does not exist return None
  150 
  151     :param key: the key
  152     :return: entry.Value or None
  153     '''
  154 
  155     if not key.startswith('linotp.'):
  156         key = u"linotp." + key
  157 
  158     if isinstance(key, str):
  159         key = u'' + key
  160 
  161     entry = Session.query(linotp.model.Config).filter(
  162                           linotp.model.Config.Key == u'' + key).first()
  163 
  164     if entry:
  165         return entry.Value
  166 
  167     return None
  168 
  169 def set_defaults():
  170     '''
  171     add linotp default config settings
  172 
  173     :return: - nothing -
  174     '''
  175 
  176     is_upgrade = 0 != Session.query(linotp.model.Config).filter(
  177                           linotp.model.Config.Key == u"linotp.Config").count()
  178 
  179     if is_upgrade:
  180         # if it is an upgrade and no welcome screen was shown before,
  181         # make sure an upgrade screen is shown
  182         set_config(key=u"welcome_screen.version",
  183                    value=u"0", typ=u"text")
  184         set_config(key=u"welcome_screen.last_shown",
  185                    value=u"0", typ=u"text")
  186         set_config(key=u"welcome_screen.opt_out",
  187                    value=u"false", typ=u"text")
  188 
  189     log.info("Adding config default data...")
  190 
  191     set_config(key=u"DefaultMaxFailCount",
  192                value=u"10", typ=u"int",
  193                description=(u"The default maximum count for"
  194                             u" unsuccessful logins"))
  195 
  196     set_config(key=u"DefaultCountWindow",
  197                value=u"10", typ=u"int",
  198                description=(u"The default lookup window for tokens "
  199                             u"out of sync "))
  200 
  201     set_config(key=u"DefaultSyncWindow",
  202                value=u"1000", typ=u"int",
  203                description=(u"The default lookup window for tokens "
  204                             u"out of sync "))
  205 
  206     set_config(key=u"DefaultChallengeValidityTime",
  207                value=u"120", typ=u"int",
  208                description=(u"The default time, a challenge is regarded"
  209                             u" as valid."))
  210 
  211     set_config(key=u"DefaultResetFailCount",
  212                value=u"True", typ=u"bool",
  213                description=u"The default maximum count for unsucessful logins")
  214 
  215     set_config(key=u"DefaultOtpLen",
  216                value=u"6", typ=u"int",
  217                description=u"The default len of the otp values")
  218 
  219     set_config(key=u"QRTokenOtpLen",
  220                value=u"8", typ=u"int",
  221                description=u"The default len of the otp values")
  222 
  223     set_config(key=u"QRChallengeValidityTime",
  224                value=u"150", typ=u"int",
  225                description=(u"The default qrtoken time, a challenge is regarded"
  226                             u" as valid."))
  227 
  228     set_config(key=u"QRMaxChallenges",
  229                value=u"4", typ=u"int",
  230                description=u"Maximum open QRToken challenges")
  231 
  232     set_config(key=u"PushChallengeValidityTime",
  233                value=u"150", typ=u"int",
  234                description=(u"The pushtoken default time, a challenge is "
  235                             u"regarded as valid."))
  236 
  237     set_config(key=u"PushMaxChallenges",
  238                value=u"4", typ=u"int",
  239                description=u"Maximum open pushtoken challenges")
  240 
  241     set_config(key=u"PrependPin",
  242                value=u"True", typ=u"bool",
  243                description=u"is the pin prepended - most cases")
  244 
  245     set_config(key=u"FailCounterIncOnFalsePin",
  246                value=u"True", typ=u"bool",
  247                description=u"increment the FailCounter, if pin did not match")
  248 
  249     set_config(key=u"SMSProvider",
  250                value=u"smsprovider.HttpSMSProvider.HttpSMSProvider",
  251                typ=u"text",
  252                description=u"SMS Default Provider via HTTP")
  253 
  254     set_config(key=u"SMSProviderTimeout",
  255                value=u"300", typ=u"int",
  256                description=u"Timeout until registration must be done")
  257 
  258     set_config(key=u"SMSBlockingTimeout",
  259                value=u"30", typ=u"int",
  260                description=u"Delay until next challenge is created")
  261 
  262     set_config(key=u"DefaultBlockingTimeout",
  263                value=u"0", typ=u"int",
  264                description=u"Delay until next challenge is created")
  265 
  266     # setup for totp defaults
  267     # "linotp.totp.timeStep";"60";"None";"None"
  268     # "linotp.totp.timeWindow";"600";"None";"None"
  269     # "linotp.totp.timeShift";"240";"None";"None"
  270 
  271     set_config(key=u"totp.timeStep",
  272                value=u"30", typ=u"int",
  273                description=u"Time stepping of the time based otp token ")
  274 
  275     set_config(key=u"totp.timeWindow",
  276                value=u"300", typ=u"int",
  277                description=(u"Lookahead time window of the time based "
  278                             u"otp token "))
  279 
  280     set_config(key=u"totp.timeShift",
  281                value=u"0", typ=u"int",
  282                description=u"Shift between server and totp token")
  283 
  284     set_config(key=u"AutoResyncTimeout",
  285                value=u"240", typ=u"int",
  286                description=u"Autosync timeout for an totp token")
  287 
  288     # setup for ocra defaults
  289     # OcraDefaultSuite
  290     # QrOcraDefaultSuite
  291     # OcraMaxChallenges
  292     # OcraChallengeTimeout
  293 
  294     set_config(key=u"OcraDefaultSuite",
  295                value=u"OCRA-1:HOTP-SHA256-8:C-QN08",
  296                typ=u"string",
  297                description=u"Default OCRA suite for an ocra token ")
  298 
  299     set_config(key=u"QrOcraDefaultSuite",
  300                value=u"OCRA-1:HOTP-SHA256-8:C-QA64",
  301                typ=u"string",
  302                description=u"Default OCRA suite for an ocra token ")
  303 
  304     set_config(key=u"OcraMaxChallenges",
  305                value=u"4", typ=u"int",
  306                description=u"Maximum open ocra challenges")
  307 
  308     set_config(key=u"OcraChallengeTimeout",
  309                value=u"300", typ=u"int",
  310                description=u"Timeout for an open ocra challenge")
  311 
  312     # emailtoken defaults
  313     set_config(key=u"EmailProvider",
  314                value=u"linotp.provider.emailprovider.SMTPEmailProvider",
  315                typ=u"string",
  316                description=u"Default EmailProvider class")
  317 
  318     set_config(key=u"EmailChallengeValidityTime",
  319                value=u"600", typ=u"int",
  320                description=(u"Time that an e-mail token challenge stays valid"
  321                             u" (seconds)"))
  322     set_config(key=u"EmailBlockingTimeout",
  323                value=u"120", typ=u"int",
  324                description=u"Time during which no new e-mail is sent out")
  325 
  326     set_config(key=u'OATHTokenSupport',
  327                value=u"False", typ=u"bool",
  328                description=u"support for hmac token in oath format")
  329 
  330     # use the system certificate handling, especially for ldaps
  331     set_config(key=u"certificates.use_system_certificates",
  332                value=u"False", typ=u"bool",
  333                description=u"use system certificate handling")
  334 
  335     set_config(key=u"user_lookup_cache.enabled",
  336                value=u"False", typ=u"bool",
  337                description=u"enable user loookup caching")
  338 
  339     set_config(key=u"resolver_lookup_cache.enabled",
  340                value=u"False", typ=u"bool",
  341                description=u"enable realm resolver caching")
  342 
  343     set_config(key=u'user_lookup_cache.expiration',
  344                value=u"64800", typ=u"int",
  345                description=u"expiration of user caching entries")
  346 
  347     set_config(key=u'resolver_lookup_cache.expiration',
  348                value=u"64800", typ=u"int",
  349                description=u"expiration of resolver caching entries")
  350 
  351     if not is_upgrade:
  352         set_config(key=u'NewPolicyEvaluation',
  353                    value=u"True", typ=u"boolean",
  354                    description=u"use the new policy engine")
  355 
  356         set_config(key=u'NewPolicyEvaluation.compare',
  357                    value=u"False", typ=u"boolean",
  358                    description=(u"compare the new policy engine with "
  359                                 u"the old one"))
  360 
  361     return
  362 
  363 
  364 def setup_app(conf, conf_global=None, unitTest=False):
  365     '''
  366     setup_app is the hook, which is called, when the application is created
  367 
  368     :param conf: the application configuration
  369 
  370     :return: - nothing -
  371     '''
  372 
  373     if unitTest is True:
  374         log.debug("Deleting previous tables...")
  375         meta.metadata.drop_all(bind=meta.engine)
  376 
  377     # Create the tables if they don't already exist
  378     log.info("Creating tables...")
  379     meta.metadata.create_all(bind=meta.engine)
  380 
  381     # ---------------------------------------------------------------------- --
  382 
  383     # for the cloud mode we require the admin_user table to
  384     # manage the admin users to allow password setting
  385 
  386     if 'linotpadmin.username' in conf and 'linotpadmin.password' in conf:
  387 
  388         from linotp.lib.tools.set_password import SetPasswordHandler
  389         from linotp.lib.tools.set_password import DataBaseContext
  390 
  391         db_context = DataBaseContext(sql_url=meta.engine.url)
  392 
  393         SetPasswordHandler.create_table(db_context)
  394 
  395         # create the initial admin
  396         admin_user = conf.get('linotpadmin.username', '')
  397         admin_pw = conf.get('linotpadmin.password', '')
  398 
  399         if admin_user and admin_pw:
  400             SetPasswordHandler.create_admin_user(db_context,
  401                                                  username=admin_user,
  402                                                  crypted_password=admin_pw)
  403 
  404     # ---------------------------------------------------------------------- --
  405 
  406     #
  407     # hook for schema upgrade -
  408     # - called by paster setup-app or on the first request to linotp
  409     #
  410 
  411     run_data_model_migration(meta)
  412 
  413 
  414     #
  415     # create the secret key file if it does not exist
  416     #
  417 
  418     if "linotpSecretFile" in conf:
  419         filename = conf.get("linotpSecretFile")
  420         try:
  421             open(filename)
  422         except IOError:
  423             log.warning("The Linotp Secret File could not be found. " +
  424                         "Creating a new one at %s", filename)
  425             f_handle = open(filename, 'ab+')
  426             secret = os.urandom(32 * 5)
  427             f_handle.write(secret)
  428             f_handle.close()
  429             os.chmod(filename, 0400)
  430         log.debug("linotpSecretFile: %s", filename)
  431 
  432     set_defaults()
  433 
  434     Session.commit()
  435 
  436     init_logging_config()
  437 
  438     log.info("Successfully set up.")
  439 
  440 
  441 class BaseController(WSGIController):
  442     """
  443     BaseController class - will be called with every request
  444     """
  445 
  446     def __init__(self, *args, **kw):
  447         """
  448         base controller constructor
  449 
  450         :param *args: generic argument array
  451         :param **kw: generic argument dict
  452         :return: None
  453 
  454         """
  455         self.sep = None
  456         self.set_language(request.headers)
  457         self.base_auth_user = ''
  458 
  459         self.parent = super(WSGIController, self)
  460         self.parent.__init__(*args, **kw)
  461 
  462         # make the OpenID SQL Instance globally available
  463         openid_sql = config.get('openid_sql', None)
  464         if openid_sql is None:
  465             try:
  466                 openid_storage = SQLStorage()
  467                 config['openid_sql'] = openid_storage
  468             except Exception as exx:
  469                 config['openid_sql'] = exx
  470                 log.error("Failed to configure openid_sql: %r" % exx)
  471 
  472         first_run = False
  473         app_setup_done = config.get('app_setup_done', False)
  474         if app_setup_done is False:
  475             try:
  476                 setup_app(config)
  477                 config['app_setup_done'] = True
  478                 first_run = True
  479             except Exception as exx:
  480                 config['app_setup_done'] = False
  481                 log.error("Failed to serve request: %r" % exx)
  482                 raise exx
  483 
  484         # set the decryption device before loading linotp config,
  485         # so it contains the decrypted values as well
  486         glo = getGlobalObject()
  487         self.sep = glo.security_provider
  488 
  489         try:
  490             hsm = self.sep.getSecurityModule()
  491             self.hsm = hsm
  492             c.hsm = hsm
  493         except Exception as exx:
  494             log.exception('failed to assign hsm device: %r' % exx)
  495             raise exx
  496 
  497         l_config = getLinotpConfig()
  498 
  499         # initialize the elliptic curve secret + public key for the qrtoken
  500         self.secret_key = l_config.get('SecretKey.Partition.0', False)
  501 
  502         resolver_setup_done = config.get('resolver_setup_done', False)
  503         if resolver_setup_done is False:
  504             try:
  505                 cache_dir = config.get("app_conf", {}).get("cache_dir", None)
  506                 setupResolvers(config=l_config, cache_dir=cache_dir)
  507                 config['resolver_setup_done'] = True
  508             except Exception as exx:
  509                 config['resolver_setup_done'] = False
  510                 log.error("Failed to setup resolver: %r", exx)
  511                 raise exx
  512 
  513         # TODO: verify merge dropped
  514         # initResolvers()
  515 
  516         # if we are in the setup cycle, we check for the linotpLicenseFile
  517         if first_run:
  518             if "linotpLicenseFile" in config and 'license' not in l_config:
  519                 license_str = ''
  520                 filename = config.get("linotpLicenseFile", '')
  521                 try:
  522                     with open(filename) as f:
  523                         license_str = f.read()
  524                 except IOError:
  525                     log.error("could not open licence file: %s", filename)
  526 
  527                 if not license_str:
  528                     log.error("empty license file: %s", filename)
  529                 else:
  530                     with request_context_safety():
  531                         request_context['translate'] = translate
  532 
  533                         import linotp.lib.support
  534                         res, msg = linotp.lib.support.setSupportLicense(license_str)
  535                         if res is False:
  536                             log.error("failed to load license: %s: %s",
  537                                       license_str, msg)
  538 
  539                         else:
  540                             log.info("license successfully loaded")
  541             if 'provider.config_file' in config:
  542                 from linotp.provider import load_provider_ini
  543 
  544                 load_provider_ini(config['provider.config_file'])
  545 
  546     def __call__(self, environ, start_response):
  547         '''Invoke the Controller'''
  548         # WSGIController.__call__ dispatches to the Controller method
  549         # the request is routed to. This routing information is
  550         # available in environ['pylons.routes_dict']
  551 
  552         # we add a unique request id to the request enviroment
  553         # so we can trace individual requests in the logging
  554 
  555         environ['REQUEST_ID'] = str(uuid4())
  556         environ['REQUEST_START_TIMESTAMP'] = datetime.now()
  557 
  558         with request_context_safety():
  559 
  560             try:
  561                 self._parse_request_params(request)
  562             except UnicodeDecodeError as exx:
  563                 # we supress Exception here as it will be handled in the
  564                 # controller which will return corresponding response
  565                 log.warning('Failed to access request parameters: %r' % exx)
  566 
  567             self.create_context(request, environ)
  568 
  569             try:
  570                 try:
  571                     user_desc = getUserFromRequest(request)
  572                     self.base_auth_user = user_desc.get('login', '')
  573                 except UnicodeDecodeError as exx:
  574                     # we supress Exception here as it will be handled in the
  575                     # controller which will return corresponding response
  576                     log.warning('Failed to identify user due to %r' % exx)
  577 
  578                 ret = WSGIController.__call__(self, environ, start_response)
  579                 log.debug("Request reply: %r", ret)
  580 
  581             finally:
  582                 meta.Session.remove()
  583                 # free the lock on the scurityPovider if any
  584                 if self.sep:
  585                     self.sep.dropSecurityModule()
  586                 closeResolvers()
  587 
  588                 # hint for the garbage collector to make the dishes
  589                 data_objects = ["resolvers_loaded",
  590                                 "resolver_clazzes", "linotpConfig", "audit", "hsm"]
  591                 for data_obj in data_objects:
  592                     if hasattr(c, data_obj):
  593                         data = getattr(c, data_obj)
  594                         del data
  595 
  596                 log_request_timedelta(log)
  597 
  598             return ret
  599 
  600     def _parse_request_params(self, _request):
  601         """
  602         Parses the request params from the request objects body / params
  603         dependent on request content_type.
  604         """
  605         if _request.content_type == 'application/json':
  606             self.request_params = _request.json_body
  607         else:
  608             self.request_params = {}
  609             for key in request.params:
  610                 if(key.endswith('[]')):
  611                     self.request_params[key[:-2]] = _request.params.getall(key)
  612                 else:
  613                     self.request_params[key] = _request.params[key]
  614 
  615     def set_language(self, headers):
  616         '''Invoke before everything else. And set the translation language'''
  617         languages = headers.get('Accept-Language', '')
  618 
  619         found_lang = False
  620 
  621         for match in accept_language_regexp.finditer(languages):
  622             # make sure we have a correct language code format
  623             language = match.group(1)
  624             if not language:
  625                 continue
  626             language = language.replace('_', '-').lower()
  627 
  628             # en is the default language
  629             if language.split('-')[0] == 'en':
  630                 found_lang = True
  631                 break
  632 
  633             try:
  634                 set_lang(language.split('-')[0])
  635                 found_lang = True
  636                 break
  637             except LanguageError:
  638                 log.debug("Cannot set requested language: %s. Trying next"
  639                           " language if available.", language)
  640 
  641         if not found_lang and languages:
  642             log.warning("Cannot set preferred language: %r", languages)
  643 
  644         return
  645 
  646     def create_context(self, request, environment):
  647         """
  648         create the request context for all controllers
  649         """
  650 
  651         linotp_config = getLinotpConfig()
  652 
  653         # make the request id available in the request context
  654         request_context['RequestId'] = environment['REQUEST_ID']
  655 
  656         # a request local cache to get the user info from the resolver
  657         request_context['UserLookup'] = {}
  658 
  659         # a request local cache to get the resolver from user and realm
  660         request_context['UserRealmLookup'] = {}
  661 
  662         request_context['Config'] = linotp_config
  663         request_context['Policies'] = parse_policies(linotp_config)
  664         request_context['translate'] = translate
  665         request_context['CacheManager'] = environment['beaker.cache']
  666 
  667         routes = environment.get('pylons.routes_dict', {})
  668         path = "/%s/%s" % (routes['controller'], routes['action'])
  669         request_context['Path'] = path
  670 
  671         request_context['hsm'] = self.hsm
  672 
  673         initResolvers()
  674 
  675         client = None
  676         try:
  677             client = get_client(request=request)
  678         except UnicodeDecodeError as exx:
  679             log.error("Failed to decode request parameters %r" % exx)
  680 
  681         request_context['Client'] = client
  682 
  683         request_context['Audit'] = Audit
  684         request_context['audit'] = Audit.initialize(request, client=client)
  685 
  686         authUser = None
  687         try:
  688             authUser = getUserFromRequest(request)
  689         except UnicodeDecodeError as exx:
  690             log.error("Failed to decode request parameters %r" % exx)
  691 
  692         request_context['AuthUser'] = authUser
  693         request_context['UserLookup'] = {}
  694 
  695         # ------------------------------------------------------------------ --
  696         # get the current resolvers
  697 
  698         resolvers = []
  699         try:
  700             resolvers = getResolverList(config=linotp_config)
  701         except UnicodeDecodeError as exx:
  702             log.error("Failed to decode request parameters %r" % exx)
  703 
  704         request_context['Resolvers'] = resolvers
  705 
  706         # ------------------------------------------------------------------ --
  707         # get the current realms
  708 
  709         realms = {}
  710         try:
  711             realms = getRealms()
  712         except UnicodeDecodeError as exx:
  713             log.error("Failed to decode request parameters %r" % exx)
  714 
  715         request_context['Realms'] = realms
  716 
  717         # ------------------------------------------------------------------ --
  718 
  719         defaultRealm = ""
  720         try:
  721             defaultRealm = getDefaultRealm(linotp_config)
  722         except UnicodeDecodeError as exx:
  723             log.error("Failed to decode request parameters %r" % exx)
  724 
  725         request_context['defaultRealm'] = defaultRealm
  726 
  727         # ------------------------------------------------------------------ --
  728         # load the requesting user
  729 
  730         from linotp.useridresolver.UserIdResolver import (
  731             ResolverNotAvailable)
  732 
  733         requestUser = None
  734         try:
  735             requestUser = getUserFromParam(self.request_params)
  736         except UnicodeDecodeError as exx:
  737             log.error("Failed to decode request parameters %r", exx)
  738         except (ResolverNotAvailable, NoResolverFound) as exx:
  739             log.error("Failed to connect to server %r", exx)
  740 
  741         request_context['RequestUser'] = requestUser
  742 
  743         # ------------------------------------------------------------------ --
  744         # load the providers
  745 
  746         from linotp.provider import Provider_types
  747         from linotp.provider import getProvider
  748 
  749         provider = {}
  750         for provider_type in Provider_types.keys():
  751             provider[provider_type] = getProvider(provider_type)
  752 
  753         request_context['Provider'] = provider
  754 
  755         # ------------------------------------------------------------------ --
  756 
  757         # for the setup of encrypted data, we require the hsm is instatiated
  758         # and available in the request context
  759 
  760         if not self.secret_key:
  761             init_key_partition(linotp_config, partition=0)
  762 
  763         # ------------------------------------------------------------------ --
  764 
  765         # copy some system entries from pylons
  766         syskeys = {
  767            "radius.nas_identifier": "LinOTP",
  768            "radius.dictfile": "/etc/linotp2/dictionary"
  769         }
  770 
  771         sysconfig = {}
  772         for key, default in syskeys.items():
  773             sysconfig[key] = config.get(key, default)
  774 
  775         request_context['SystemConfig'] = sysconfig
  776 
  777 # eof ########################################################################