NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

httpAuth.py (6221B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\script\net\httpAuth.py
      2 import base64
      3 from datetime import datetime
      4 import cherrypy
      5 import blue
      6 from carbon.common.lib import const
      7 from carbon.common.script.sys import basesession
      8 from eveexceptions import UserError
      9 from eveprefs import prefs
     10 from carbon.common.script.net import httpJinja, machoNet
     11 SESSION_KEY = '_cp_username'
     12 AUTH_LOGIN_URL = '/auth/login'
     13 DEFAULT_URL = '/default.py'
     14 
     15 def CreateSession(username, password):
     16     session = basesession.CreateSession()
     17     session.esps = ESPSession(None, session.sid)
     18     session.esps.contents['username'] = username
     19     session.esps.contents['password'] = password
     20     return session
     21 
     22 
     23 def EndSession():
     24     cherrypy.session.delete()
     25     cherrypy.lib.sessions.expire()
     26 
     27 
     28 def CheckCredentials(username, password):
     29     sess = CreateSession(username, password)
     30     if machoNet.mode == 'client':
     31         cherrypy.session['machoSession'] = sess
     32         return
     33     auth = basesession.GetServiceSession('cherry').ConnectToAnyService('authentication')
     34     sptype = const.userConnectTypeServerPages
     35     try:
     36         sessstuff, _ = auth.Login(sess.sid, username, password, None, sptype, cherrypy.request.remote.ip)
     37     except UserError:
     38         return u'Incorrect username or password'
     39     except Exception:
     40         return u'Incorrect username or password'
     41 
     42     session = CreateSession(username, password)
     43     sessstuff['role'] |= sess.role
     44     for otherSession in basesession.FindSessions('userid', [sessstuff['userid']]):
     45         otherSession.LogSessionHistory('Usurped by user %s via HTTP using local authentication' % username)
     46         basesession.CloseSession(otherSession)
     47 
     48     cherrypy.session['machoSession'] = sess
     49     sess.SetAttributes(sessstuff)
     50 
     51 
     52 def CheckAuth(*args, **kwargs):
     53     assets = cherrypy.request.config.get('tools.staticdir.dir')
     54     cherrypy.request.beginTime = datetime.now()
     55     if assets not in cherrypy.request.path_info:
     56         conditions = cherrypy.request.config.get('auth.require', None)
     57         if conditions is not None:
     58             pathInfo = cherrypy.request.path_info
     59             if len(cherrypy.request.query_string):
     60                 pathInfo = '%s?%s' % (pathInfo, cherrypy.request.query_string)
     61             if pathInfo in [AUTH_LOGIN_URL, DEFAULT_URL]:
     62                 authLogin = AUTH_LOGIN_URL
     63             else:
     64                 authLogin = '%s?from_page=%s' % (AUTH_LOGIN_URL, base64.urlsafe_b64encode(pathInfo))
     65             username = cherrypy.session.get(SESSION_KEY)
     66             if username:
     67                 cherrypy.request.login = username
     68                 for condition in conditions:
     69                     if not condition():
     70                         raise cherrypy.HTTPRedirect(authLogin)
     71 
     72             else:
     73                 raise cherrypy.HTTPRedirect(authLogin)
     74 
     75 
     76 cherrypy.tools.auth = cherrypy.Tool('before_handler', CheckAuth)
     77 
     78 def Require(*conditions):
     79 
     80     def decorate(f):
     81         if not hasattr(f, '_cp_config'):
     82             f._cp_config = dict()
     83         if 'auth.require' not in f._cp_config:
     84             f._cp_config['auth.require'] = []
     85         f._cp_config['auth.require'].extend(conditions)
     86         return f
     87 
     88     return decorate
     89 
     90 
     91 def MemberOf(groupName):
     92 
     93     def check():
     94         return cherrypy.request.login == 'joe' and groupName == 'admin'
     95 
     96     return check()
     97 
     98 
     99 def NameIs(required_username):
    100     return lambda : required_username == cherrypy.request.login
    101 
    102 
    103 def AnyOf(*conditions):
    104 
    105     def check():
    106         for condition in conditions:
    107             if condition():
    108                 return True
    109 
    110         return False
    111 
    112     return check()
    113 
    114 
    115 def AllOf(*conditions):
    116 
    117     def check():
    118         for condition in conditions:
    119             if not condition():
    120                 return False
    121 
    122         return True
    123 
    124     return check
    125 
    126 
    127 class ESPSession:
    128 
    129     def __init__(self, owner, sid):
    130         self.codePage = 0
    131         self.contents = {}
    132         self.LCID = 0
    133         self.sessionID = sid
    134         self.timeout = 20
    135         self.authenticated = 0
    136         self.username = ''
    137         self.password = ''
    138         self.owner = owner
    139         self.flatkokudeig = blue.os.GetWallclockTimeNow()
    140         self.remappings = {}
    141 
    142 
    143 class AuthController(object):
    144     __guid__ = 'httpAuth.AuthController'
    145 
    146     def on_login(self, username):
    147         pass
    148 
    149     def on_logout(self, username):
    150         pass
    151 
    152     def get_loginform(self, username, msg = None, from_page = '/'):
    153         sp = cherrypy.sm.GetService('SP')
    154         try:
    155             background_color = sp.Color()
    156         except Exception:
    157             background_color = sp.Color()
    158 
    159         return {'msg': msg,
    160          'style': 'background-color: %s; color: black' % background_color,
    161          'sp': sp.Title(),
    162          'server': cherrypy.prefs.clusterName,
    163          'generate_time': datetime.now() - cherrypy.request.beginTime,
    164          'username': 'sp' if prefs.clusterMode == 'LOCAL' else ''}
    165 
    166     @cherrypy.expose
    167     @cherrypy.tools.jinja(template='AuthController_login.html')
    168     def login(self, username = None, password = None, from_page = '/'):
    169         if username is None or password is None:
    170             return self.get_loginform('', from_page=from_page)
    171         error_msg = CheckCredentials(username, password)
    172         if error_msg:
    173             return self.get_loginform(username, error_msg, from_page)
    174         cherrypy.session.regenerate()
    175         cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
    176         self.on_login(username)
    177         if from_page != '/':
    178             from_page = base64.urlsafe_b64decode(str(from_page))
    179         raise cherrypy.HTTPRedirect(from_page or '/')
    180 
    181     @cherrypy.expose
    182     def logout(self, from_page = '/'):
    183         sess = cherrypy.session
    184         username = sess.get(SESSION_KEY, None)
    185         sess[SESSION_KEY] = None
    186         if username:
    187             cherrypy.request.login = None
    188             self.on_logout(username)
    189         if 'machoSession' in cherrypy.session:
    190             sess = cherrypy.session['machoSession']
    191             sess.LogSessionHistory('Web session closed by logging out %s' % str(session.userid))
    192             basesession.CloseSession(sess)
    193         EndSession()
    194         raise cherrypy.HTTPRedirect(from_page or '/')