def __init__(self, initial=None, app=None): def on_update(self): self.modified = True self.app = app if "SESSION_REFRESH" not in self.app.config: self.app.config['SESSION_REFRESH'] = DEFAULT_SESSION_REFRESH # Set a callback to catch future modifications CallbackDict.__init__(self, initial, on_update) # If there is no session yet, seed it first if initial == None: self.seed() if initial != None: # Convert times to objects self['_start'] = arrow.get(self['_start']) self['_refresh'] = arrow.get(self['_refresh']) # Register some session relevant template variables self.app.jinja_env.globals['csrf_token'] = hashlib.sha256(self['secure']['_token']).hexdigest() # If this is a new session, set modified flag, otherwise everything up to here hasn't "really" been a modification if not initial: self.modified = True else: self.modified = False # Check if the refresh interval has expired if self['_refresh'].replace(seconds =+ self.app.config['SESSION_REFRESH']) < arrow.utcnow(): self.refresh()
def __init__(self, initial=None, sid=None, new=True): def on_update(this): this.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False
def __init__(self, data=None, session_id=None): def on_update(self): self.modified = True CallbackDict.__init__(self, data, on_update) self.session_id = session_id self.modified = False
def __init__(self, initial=None, session_key=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.session_key = session_key self.modified = False
def __init__(self, initial=None, session_id=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.modified = True self.permanent = True #store the session. Without this, the session will not be stored self.session_id = session_id
def __init__(self, db_object=None, initial=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.modified = False self.db_object = db_object self._clear = False
def __init__(self, initial=None, sid=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.permanent = True self.modified = False
def __init__(self, *args, **kwargs): def on_update(self): self.modified = True self.modified = False CallbackDict.__init__(self, on_update=on_update) dict.update(self, *args, **kwargs)
def __init__(self, initial=None): def _on_update(d): d.modified = True CallbackDict.__init__(self, initial, _on_update) self.modified = False
def __init__(self, uid=None, force=False): """ Keeps information about user. """ def on_update(self): """ Changes own status when the user info is modified. """ self.modified = True self.modified = False self.uid = uid self.req = self._get_request_info() acc = {} if uid > 0: data = self._login(uid, force) acc = self._precache(data, force) else: data = self._create_guest() self.info = CallbackDict(data, on_update) #FIXME remove req after everybody start using flask request. CombinedMultiDict.__init__( self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save()
def __init__(self, initial=None, sid=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.modified = False
def __init__(self, initial = None, session_id = None, user_id = None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.session_id = session_id self.user_id = user_id self.modified = False
def __init__(self, initial=None, sid=None, new=False): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False
def __init__(self, initial=None, sid=None, new=False): def on_update(instance): instance.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False
def __init__(self, initial=None): def _on_update(d): d.modified = True CallbackDict.__init__(self, initial, _on_update) if not initial: self.modified = False
def __init__(self, initial=None, device=None, new=False): def on_update(this): this.modified = True CallbackDict.__init__(self, initial, on_update) self.device = device self.new = new self.modified = False self.permanent = True
def __init__(self, initial=None, sid=None, permanent=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid if permanent: self.permanent = permanent self.modified = False
def __init__(self, initial=None, ssid=None, modified=None): CallbackDict.__init__(self, initial) self.ssid = ssid self.modified = modified
def __init__(self, initial=None, sid=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid or self._create_sid() self.modified = False self.must_create = False self.must_destroy = False
def __init__(self, initial=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.modified = False self.accessed = False self.user = None self.sid = None
def __init__(self, initial=None, token=None, expiry=None): def on_update(self): """ Set the dirty-session flag. """ self.modified = True CallbackDict.__init__(self, initial, on_update) self.modified = False self.token = token self.expiry = expiry
def __init__(self, initial=None, sid=None, new=False): def on_update(s): s.modified = True s.accessed = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False
def __init__(self, initial=None, sid=None, new=True): def on_update(this): this.modified = True if initial: initial = pickle.loads(str(initial)) CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False
def __init__(self, initial=None): def _on_update(d): d.modified = True CallbackDict.__init__(self, initial, _on_update) # change this to False by default because we don't want to send set-cookie with every request since # it mucks with edge caches self.modified = False
def __init__(self, initial=None, session_id=None, new=False, was_invalid=False, expires=0): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.session_id = session_id self.expires = expires self.new = new self.was_invalid = was_invalid self.modified = False
def __init__(self, initial=None, sid=None, new=False, needs_cookie=False): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False self.destroy = False self.needs_cookie = needs_cookie
def __init__(self, initial=None, sid=None): """Initialize session with optional default value.""" self.sid = sid self.logging_in = False self.modified = initial is not None def _on_update(d): d.modified = True CallbackDict.__init__(self, initial, _on_update)
def __init__(self, initial=None, sid=None, new=False): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False defaults = self._get_defaults() if defaults: self.update(defaults)
def __init__(self, initial=None, sid=None, new=False, randval=None, hmac_digest=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False self.randval = randval self.hmac_digest = hmac_digest
def __init__(self, initial=None, sid=None, new=None): def on_update(self): self.modified = True if initial is None: initial = {} CallbackDict.__init__(self, initial, on_update) self.sid = sid self.old_sid = None self.new = new self.modified = False
def __init__(self, initial=None, sid=None, new=False, redis=None, prefix=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False self.redis = redis self.prefix = prefix or ''
def __init__(self, initial=None, sid=None): self.sid = sid self.logging_in = False self.modified = initial is not None def _on_update(d): d.modified = True CallbackDict.__init__(self, initial, _on_update)
def __init__(self, initial=None, sessionID=None, new=False): def on_update(self): self.modified = True # When the dictionary is modified, self.modified will be set True CallbackDict.__init__(self, initial, on_update) self.modified = False # Starting state self.new = new self.sessionID = sessionID
def __init__(self, initial=None, session_id=None, is_new=False): self.session_id = session_id self.is_new = is_new self.modified = False """ CallbackDict calls on_update function whenever there's a change in a session (e.g. update/insert in k/v) """ def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update)
def __init__(self, initial=None): def _on_update(d): d.modified = True CallbackDict.__init__(self, initial, _on_update) if initial: self.modified = False else: self.generate_sid() self.new = True self.modified = True
def __init__(self, app_secret): def on_update(self): if self.accessed == False: self.modified = True self.secret = app_secret self.id = None self.new = True self.accessed = False self.modified = False self.permanent = True CallbackDict.__init__(self, on_update=on_update)
def __init__(self, id=None, data=None, expire=0): """ 默认的服务端session_class :param id: session id :param data: session data :param expire: session expire (timestamp) """ self.id = id self.expire = expire def on_update(self): self.modified = True CallbackDict.__init__(self, data, on_update) self.modified = False
def __init__(self, app_name, sid=None, initial={}): def on_update(self): self.modified = True if sid: self.sid = sid self.user = User(initial.pop('user', {})) self.active = initial.pop('active', False) self.ts = initial.pop('ts', None) self.ok = initial.pop('ok', None) CallbackDict.__init__(self, initial.get(app_name), on_update) else: self.user = None self.modified = False
def __init__(self, initial=None, sid=None, new=False, randval=None, hmac_digest=None): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False self.randval = randval self.last_write = None self.force_write = False self.hmac_digest = hmac_digest self.permanent = True
def __init__(self, initial=None, sid=None, new=True): def on_update(this): this.modified = True if initial: # This provides support to both python 2 and 3. # Cause: TypeError: a bytes-like object is required, not 'str' try: initial = pickle.loads(str(initial)) except TypeError: initial = pickle.loads(initial) CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False
def __init__(self, initial=None, sid=None, new=False): ''' :param initial:초기값 :param sid: 세션id :param new: 새로 생성되었는지 여부 ''' def on_update(self): #내포 함수 self.modified = True print 'on_update()' CallbackDict.__init__(self, initial, on_update) #값이 변하면 CallbackDict가 동작한다. self.sid = sid self.new = new self.modified = False
def __init__(self, redis=None, initial=None, sid=None, new=False, prefix=''): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False self.redis = redis self.logger = logging.getLogger(__name__) self.prefix = prefix
def _get_mimetype_params(self): def on_update(d): self.headers["Content-Type"] = dump_options_header( self.mimetype, d) d = parse_options_header(self.headers.get("content-type", ""))[1] return CallbackDict(d, on_update)
def _get_mimetype_params(self): def on_update(d): self.headers['Content-Type'] = \ dump_options_header(self.mimetype, d) d = parse_options_header(self.headers.get('content-type', ''))[1] return CallbackDict(d, on_update)
def __init__(self, initial = None, sid = None, new = False): def on_update(self): print('SQLAlchemySession.on_update') self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False engine = create_engine(Config.SQLALCHEMY_DATABASE_URI) if not engine.dialect.has_table(engine, 'flask_session'): db.create_all() print('table for session is created.') engine.dispose()
def __init__(self, initial=None, sid=None, new=False): """ Constructor """ def on_update(self): """ On Update Callback """ self.modified = True return None CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False return None
def __init__(self, uid=None, force=False): """Retrieve information about user.""" def on_update(self): """Change own status when the user info is modified.""" self.modified = True self.modified = False self.uid = uid self.req = self._get_request_info() acc = {} if uid is not None and uid > 0: data = self._login(uid, force) acc = self._precache(data, force) else: data = self._create_guest() self.info = CallbackDict(data, on_update) # FIXME remove req after everybody start using flask request. CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save()
class UserInfo(CombinedMultiDict, UserMixin): """ This provides legacy implementations for the methods that Flask-Login and Invenio 1.x expects user objects to have. """ def __init__(self, uid=None, force=False): """Retreave information about user.""" def on_update(self): """ Changes own status when the user info is modified. """ self.modified = True self.modified = False self.uid = uid self.req = self._get_request_info() acc = {} if uid is not None and uid > 0: data = self._login(uid, force) acc = self._precache(data, force) else: data = self._create_guest() self.info = CallbackDict(data, on_update) # FIXME remove req after everybody start using flask request. CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save() def get_key(self): """Generates key for caching user information.""" key = 'current_user::' + str(self.uid) return key def get_acc_key(self): """Generates key for caching autorizations.""" remote_ip = str(request.remote_addr) if has_request_context() else '0' return 'current_user::' + str(self.uid) + '::' + remote_ip def save(self): """Save modified data pernamently for logged users.""" if not self.is_guest and self.modified: timeout = current_app.config.get( 'CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT', 0)*3600 cache.set(self.get_key(), dict(self.info), timeout=timeout) def reload(self): """Reload user login information and saves them.""" data = self._login(self.uid, force=True) acc = self._precache(data, force=True) self.info.update(data) CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save() def update_request_info(self): self.req = self._get_request_info() def _get_request_info(self): """Get request information.""" # FIXME: we should support IPV6 too. (hint for FireRole) data = {} if has_request_context(): data['remote_ip'] = request.remote_addr or '' data['remote_host'] = request.environ.get('REMOTE_HOST', '') data['referer'] = request.referrer data['uri'] = request.environ['PATH_INFO'] or '' data['agent'] = request.headers.get('User-Agent', 'N/A') return data def _create_guest(self): data = {'settings': {}} if current_app.config.get( 'CFG_WEBSESSION_DIFFERENTIATE_BETWEEN_GUESTS', False): from invenio.ext.sqlalchemy import db from invenio.modules.accounts.models import User note = '1' if current_app.config.get( 'CFG_ACCESS_CONTROL_LEVEL_GUESTS', 0) == 0 else '0' u = User(email='', note=note, password='******') db.session.add(u) db.session.commit() data.update(u.__dict__) else: # Minimal information about user. data['id'] = data['uid'] = 0 return data def _login(self, uid, force=False): """Get account information about currently logged user from database. Should raise an exception when session.uid is not valid User.id. """ data = cache.get(self.get_key()) if not force and data is not None: return data from invenio.modules.accounts.models import User data = {} try: user = User.query.get(uid) data['id'] = data['uid'] = user.id or -1 data['nickname'] = user.nickname or '' data['email'] = user.email or '' data['note'] = user.note or '' data['group'] = map(lambda x: x.usergroup.name, user.usergroups or []) data.update(user.settings or {}) data['settings'] = user.settings or {} data['guest'] = str(int(user.guest)) # '1' or '0' self.modified = True except: data = self._create_guest() return data def _precache(self, info, force=False): """Calculate prermitions for user actions. FIXME: compatibility layer only !!! """ CFG_BIBAUTHORID_ENABLED = current_app.config.get( 'CFG_BIBAUTHORID_ENABLED', False) # get autorization key acc_key = self.get_acc_key() acc = cache.get(acc_key) if not force and acc_key is not None and acc is not None: return acc # FIXME: acc_authorize_action should use flask request directly user_info = info user_info.update(self.req) from invenio.legacy.webuser import isUserSubmitter, isUserReferee, \ isUserAdmin, isUserSuperAdmin from invenio.modules.access.engine import acc_authorize_action from invenio.modules.access.control import acc_get_role_id, \ acc_is_user_in_role from invenio.legacy.search_engine import \ get_permitted_restricted_collections data = {} data['precached_permitted_restricted_collections'] = \ get_permitted_restricted_collections(user_info) data['precached_usebaskets'] = acc_authorize_action( user_info, 'usebaskets')[0] == 0 data['precached_useloans'] = acc_authorize_action( user_info, 'useloans')[0] == 0 data['precached_usegroups'] = acc_authorize_action( user_info, 'usegroups')[0] == 0 data['precached_usealerts'] = acc_authorize_action( user_info, 'usealerts')[0] == 0 data['precached_usemessages'] = acc_authorize_action( user_info, 'usemessages')[0] == 0 data['precached_usestats'] = acc_authorize_action( user_info, 'runwebstatadmin')[0] == 0 try: data['precached_viewsubmissions'] = isUserSubmitter(user_info) except: data['precached_viewsubmissions'] = None data['precached_useapprove'] = isUserReferee(user_info) data['precached_useadmin'] = isUserAdmin(user_info) data['precached_usesuperadmin'] = isUserSuperAdmin(user_info) data['precached_canseehiddenmarctags'] = acc_authorize_action( user_info, 'runbibedit')[0] == 0 usepaperclaim = False usepaperattribution = False viewclaimlink = False if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperclaimviewers"))): usepaperclaim = True if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperattributionviewers"))): usepaperattribution = True viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): pass if (current_app.config.get('CFG_BIBAUTHORID_ENABLED') and usepaperattribution and viewlink): viewclaimlink = True # if (CFG_BIBAUTHORID_ENABLED # and ((usepaperclaim or usepaperattribution) # and acc_is_user_in_role( # data, acc_get_role_id("paperattributionlinkviewers")))): # viewclaimlink = True data['precached_viewclaimlink'] = viewclaimlink data['precached_usepaperclaim'] = usepaperclaim data['precached_usepaperattribution'] = usepaperattribution timeout = current_app.config.get( 'CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT', 0)*3600 cache.set(acc_key, data, timeout=timeout) return data def is_authenticated(self): return not self.is_guest def is_authorized(self, name, **kwargs): from invenio.modules.access.engine import acc_authorize_action return acc_authorize_action(self, name)[0] == 0 def is_active(self): return not self.is_guest @property def is_guest(self): return True if self['email'] == '' else False @property def is_admin(self): return self.get('precached_useadmin', False) @property def is_super_admin(self): return self.get('precached_usesuperadmin', False) def get_id(self): return self.get('id', -1)
class UserInfo(CombinedMultiDict, UserMixin): """Provide legacy implementation. Methods that Flask-Login and Invenio 1.x expect user objects to have. """ def __init__(self, uid=None, force=False): """Retrieve information about user.""" def on_update(self): """Change own status when the user info is modified.""" self.modified = True self.modified = False self.uid = uid self.req = self._get_request_info() acc = {} if uid is not None and uid > 0: data = self._login(uid, force) acc = self._precache(data, force) else: data = self._create_guest() self.info = CallbackDict(data, on_update) # FIXME remove req after everybody start using flask request. CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save() def get_key(self): """Generate key for caching user information.""" key = 'current_user::' + str(self.uid) return key def get_acc_key(self): """Generate key for caching authorizations.""" remote_ip = str(request.remote_addr) if has_request_context() else '0' return 'current_user::' + str(self.uid) + '::' + remote_ip def save(self): """Save modified data permanently for logged users.""" if not self.is_guest and self.modified: timeout = current_app.config.get( 'CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT', 0) * 3600 cache.set(self.get_key(), dict(self.info), timeout=timeout) def reload(self): """Reload user login information and saves them.""" data = self._login(self.uid, force=True) acc = self._precache(data, force=True) self.info.update(data) CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save() def update_request_info(self): """Update request information.""" self.req = self._get_request_info() def _get_request_info(self): """Get request information.""" # FIXME: we should support IPV6 too. (hint for FireRole) data = {} if has_request_context(): data['remote_ip'] = request.remote_addr or '' data['remote_host'] = request.environ.get('REMOTE_HOST', '') data['referer'] = request.referrer data['uri'] = request.environ['PATH_INFO'] or '' data['agent'] = request.headers.get('User-Agent', 'N/A') return data def _create_guest(self): # Minimal information about user. return {'settings': {}, 'id': 0, 'uid': 0} def _login(self, uid, force=False): """Get account information about currently logged user from database. Should raise an exception when session.uid is not valid User.id. """ data = cache.get(self.get_key()) if not force and data is not None: return data from invenio_accounts.models import User data = {} try: user = User.query.get(uid) data['id'] = data['uid'] = user.id or -1 data['nickname'] = user.nickname or '' data['given_names'] = user.given_names or '' data['family_name'] = user.family_name or '' data['email'] = user.email or '' data['note'] = user.note or '' data['group'] = map(lambda x: x.group.name, getattr(user, 'groups', [])) data.update(user.settings or {}) data['settings'] = user.settings or {} data['guest'] = str(int(user.guest)) # '1' or '0' self.modified = True except Exception: data = self._create_guest() return data def _precache(self, info, force=False): """Calculate permissions for user actions. FIXME: compatibility layer only !!! """ try: from invenio_accounts.models import User except ImportError: return {} CFG_BIBAUTHORID_ENABLED = current_app.config.get( 'CFG_BIBAUTHORID_ENABLED', False) # get authorization key acc_key = self.get_acc_key() acc = cache.get(acc_key) if not force and acc_key is not None and acc is not None: return acc # FIXME: acc_authorize_action should use flask request directly user_info = info user_info.update(self.req) user = User.query.get(user_info['uid']) from invenio_access.engine import acc_authorize_action from invenio_access.control import acc_get_role_id, \ acc_is_user_in_role from invenio_search.utils import \ get_permitted_restricted_collections from invenio_deposit.cache import \ get_authorized_deposition_types data = {} data['precached_permitted_restricted_collections'] = \ get_permitted_restricted_collections(user_info) data['precached_allowed_deposition_types'] = \ get_authorized_deposition_types(user_info) data['precached_useloans'] = acc_authorize_action( user_info, 'useloans')[0] == 0 data['precached_usegroups'] = acc_authorize_action( user_info, 'usegroups')[0] == 0 data['precached_usemessages'] = acc_authorize_action( user_info, 'usemessages')[0] == 0 data['precached_useadmin'] = user.has_admin_role data['precached_usesuperadmin'] = user.has_super_admin_role data['precached_canseehiddenmarctags'] = acc_authorize_action( user_info, 'runbibedit')[0] == 0 usepaperclaim = False usepaperattribution = False viewclaimlink = False if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperclaimviewers"))): usepaperclaim = True if (CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role( user_info, acc_get_role_id("paperattributionviewers"))): usepaperattribution = True viewlink = False try: viewlink = session['personinfo']['claim_in_process'] except (KeyError, TypeError): pass if (current_app.config.get('CFG_BIBAUTHORID_ENABLED') and usepaperattribution and viewlink): viewclaimlink = True # if (CFG_BIBAUTHORID_ENABLED # and ((usepaperclaim or usepaperattribution) # and acc_is_user_in_role( # data, acc_get_role_id("paperattributionlinkviewers")))): # viewclaimlink = True data['precached_viewclaimlink'] = viewclaimlink data['precached_usepaperclaim'] = usepaperclaim data['precached_usepaperattribution'] = usepaperattribution timeout = current_app.config.get( 'CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT', 0) * 3600 cache.set(acc_key, data, timeout=timeout) return data def is_authenticated(self): """Check if user is authenticated.""" return not self.is_guest def is_authorized(self, name, **kwargs): """Check if user is authorized.""" from invenio_access.engine import acc_authorize_action return acc_authorize_action(self, name)[0] == 0 def is_active(self): """Check if user is active.""" return not self.is_guest def is_confirmed(self): """Return true if accounts has been confirmed.""" return self['note'] == "1" @property def is_guest(self): """Check if user is guest.""" return True if self['email'] == '' else False @property def is_admin(self): """Check if user is admin.""" return self.get('precached_useadmin', False) @property def is_super_admin(self): """Check if user is super admin.""" return self.get('precached_usesuperadmin', False) def get_id(self): """Get user id.""" return self.get('id', -1)
class UserInfo(CombinedMultiDict, UserMixin): """Provide legacy implementation. Methods that Flask-Login and Invenio 1.x expect user objects to have. """ def __init__(self, uid=None, force=False): """Retrieve information about user.""" def on_update(self): """Change own status when the user info is modified.""" self.modified = True self.modified = False self.uid = uid self.req = self._get_request_info() acc = {} if uid is not None and uid > 0: data = self._login(uid, force) acc = self._precache(data, force) else: data = self._create_guest() self.info = CallbackDict(data, on_update) # FIXME remove req after everybody start using flask request. CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save() def get_key(self): """Generate key for caching user information.""" key = "current_user::" + str(self.uid) return key def get_acc_key(self): """Generate key for caching authorizations.""" remote_ip = str(request.remote_addr) if has_request_context() else "0" return "current_user::" + str(self.uid) + "::" + remote_ip def save(self): """Save modified data permanently for logged users.""" if not self.is_guest and self.modified: timeout = current_app.config.get("CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT", 0) * 3600 cache.set(self.get_key(), dict(self.info), timeout=timeout) def reload(self): """Reload user login information and saves them.""" data = self._login(self.uid, force=True) acc = self._precache(data, force=True) self.info.update(data) CombinedMultiDict.__init__(self, [self.req, self.info, acc, dict(CFG_USER_DEFAULT_INFO)]) self.save() def update_request_info(self): """Update request information.""" self.req = self._get_request_info() def _get_request_info(self): """Get request information.""" # FIXME: we should support IPV6 too. (hint for FireRole) data = {} if has_request_context(): data["remote_ip"] = request.remote_addr or "" data["remote_host"] = request.environ.get("REMOTE_HOST", "") data["referer"] = request.referrer data["uri"] = request.environ["PATH_INFO"] or "" data["agent"] = request.headers.get("User-Agent", "N/A") return data def _create_guest(self): # Minimal information about user. return {"settings": {}, "id": 0, "uid": 0} def _login(self, uid, force=False): """Get account information about currently logged user from database. Should raise an exception when session.uid is not valid User.id. """ data = cache.get(self.get_key()) if not force and data is not None: return data from invenio_accounts.models import User data = {} try: user = User.query.get(uid) data["id"] = data["uid"] = user.id or -1 data["nickname"] = user.nickname or "" data["given_names"] = user.given_names or "" data["family_name"] = user.family_name or "" data["email"] = user.email or "" data["note"] = user.note or "" data["group"] = map(lambda x: x.group.name, getattr(user, "groups", [])) data.update(user.settings or {}) data["settings"] = user.settings or {} data["guest"] = str(int(user.guest)) # '1' or '0' self.modified = True except Exception: data = self._create_guest() return data def _precache(self, info, force=False): """Calculate permissions for user actions. FIXME: compatibility layer only !!! """ CFG_BIBAUTHORID_ENABLED = current_app.config.get("CFG_BIBAUTHORID_ENABLED", False) # get authorization key acc_key = self.get_acc_key() acc = cache.get(acc_key) if not force and acc_key is not None and acc is not None: return acc # FIXME: acc_authorize_action should use flask request directly user_info = info user_info.update(self.req) from invenio.legacy.webuser import isUserSubmitter, isUserReferee, isUserAdmin, isUserSuperAdmin from invenio_access.engine import acc_authorize_action from invenio_access.control import acc_get_role_id, acc_is_user_in_role from invenio_search.utils import get_permitted_restricted_collections from invenio_deposit.cache import get_authorized_deposition_types data = {} data["precached_permitted_restricted_collections"] = get_permitted_restricted_collections(user_info) data["precached_allowed_deposition_types"] = get_authorized_deposition_types(user_info) data["precached_useloans"] = acc_authorize_action(user_info, "useloans")[0] == 0 data["precached_usegroups"] = acc_authorize_action(user_info, "usegroups")[0] == 0 data["precached_usemessages"] = acc_authorize_action(user_info, "usemessages")[0] == 0 try: data["precached_viewsubmissions"] = isUserSubmitter(user_info) except Exception: data["precached_viewsubmissions"] = None data["precached_useapprove"] = isUserReferee(user_info) data["precached_useadmin"] = isUserAdmin(user_info) data["precached_usesuperadmin"] = isUserSuperAdmin(user_info) data["precached_canseehiddenmarctags"] = acc_authorize_action(user_info, "runbibedit")[0] == 0 usepaperclaim = False usepaperattribution = False viewclaimlink = False if CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(user_info, acc_get_role_id("paperclaimviewers")): usepaperclaim = True if CFG_BIBAUTHORID_ENABLED and acc_is_user_in_role(user_info, acc_get_role_id("paperattributionviewers")): usepaperattribution = True viewlink = False try: viewlink = session["personinfo"]["claim_in_process"] except (KeyError, TypeError): pass if current_app.config.get("CFG_BIBAUTHORID_ENABLED") and usepaperattribution and viewlink: viewclaimlink = True # if (CFG_BIBAUTHORID_ENABLED # and ((usepaperclaim or usepaperattribution) # and acc_is_user_in_role( # data, acc_get_role_id("paperattributionlinkviewers")))): # viewclaimlink = True data["precached_viewclaimlink"] = viewclaimlink data["precached_usepaperclaim"] = usepaperclaim data["precached_usepaperattribution"] = usepaperattribution timeout = current_app.config.get("CFG_WEBSESSION_EXPIRY_LIMIT_DEFAULT", 0) * 3600 cache.set(acc_key, data, timeout=timeout) return data def is_authenticated(self): """Check if user is authenticated.""" return not self.is_guest def is_authorized(self, name, **kwargs): """Check if user is authorized.""" from invenio_access.engine import acc_authorize_action return acc_authorize_action(self, name)[0] == 0 def is_active(self): """Check if user is active.""" return not self.is_guest def is_confirmed(self): """Return true if accounts has been confirmed.""" return self["note"] == "1" @property def is_guest(self): """Check if user is guest.""" return True if self["email"] == "" else False @property def is_admin(self): """Check if user is admin.""" return self.get("precached_useadmin", False) @property def is_super_admin(self): """Check if user is super admin.""" return self.get("precached_usesuperadmin", False) def get_id(self): """Get user id.""" return self.get("id", -1)
def __init__(self, initial=None, sid=None): CallbackDict.__init__(self, initial) self.sid = sid self.modified = False print 'MONGO SESSION', self.sid, self.modified