def test_exception_attributes(self): secret_key = 'predictable-key' value = u'hello' s = self.make_serializer(secret_key) ts = s.dumps(value) try: s.loads(ts + _coerce_string(ts, 'x')) except idmod.BadSignature as e: self.assertEqual(want_bytes(e.payload), want_bytes(ts).rsplit(b'.', 1)[0]) self.assertEqual(s.load_payload(e.payload), value) else: self.fail('Did not get bad signature')
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) #if not session: # if session.modified: # del self.cache[session.sid] # response.delete_cookie(app.session_cookie_name, domain=domain, path=path) # return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) data = dict(session) self.cache.set(session.sid, data, app.permanent_session_lifetime.total_seconds()) signer = self._get_signer(app) if signer: session_id = signer.sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) store_id = self.key_prefix + sid saved_session = self.sql_session_model.query.filter_by( session_id=store_id).first() if saved_session and saved_session.expiry <= datetime.utcnow(): # Delete expired session self.db.session.delete(saved_session) self.db.session.commit() saved_session = None if saved_session: try: val = saved_session.data data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=True) signer = self._get_signer(app) if signer is None: return None try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=True) db_session = SessionManager.Session() saved_session = db_session.query(ServerSession).filter(ServerSession.session_id == sid).first() if saved_session and not saved_session.expiry and saved_session.expiry <= datetime.utcnow(): # delete expired session db_session.delete(saved_session) db_session.commit() saved_session = None if saved_session: try: val = saved_session.data data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=True) return self.session_class(sid=sid, permanent=True)
def save_session(self, app, session, response): store_id = self.key_prefix + session.sid saved_session = self.sql_session_model.query.filter_by( session_id=store_id).first() if not session: if session.modified: if saved_session: self.db.session.delete(saved_session) self.db.session.commit() response.headers.pop(app.config.get('SESSION_HEADER_NAME', 'X-Header-Session'), None) return expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) if saved_session: saved_session.data = val saved_session.expiry = expires self.db.session.commit() else: new_session = self.sql_session_model(store_id, val, expires) self.db.session.add(new_session) self.db.session.commit() if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.headers[app.config.get('SESSION_HEADER_NAME', 'X-Header-Session')] = session_id
def save_session(self, app, session, response): if not session: if session.modified: self.redis.delete(self.key_prefix + session.sid) response.headers.pop(app.config.get('SESSION_HEADER_NAME', 'X-Header-Session'), None) return # Modification case. There are upsides and downsides to # emitting a set-cookie header each request. The behavior # is controlled by the :meth:`should_set_cookie` method # which performs a quick check to figure out if the cookie # should be set or not. This is controlled by the # SESSION_REFRESH_EACH_REQUEST config flag as well as # the permanent flag on the session itself. # if not self.should_set_cookie(app, session): # return expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) self.redis.setex(name=self.key_prefix + session.sid, value=val, time=total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.headers[app.config.get('SESSION_HEADER_NAME', 'X-Header-Session')] = session_id
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: self.cache.delete(self.key_prefix + session.sid) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) samesite = self.get_cookie_samesite(app) data = dict(session) self.cache.set(self.key_prefix + session.sid, data, total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, samesite=samesite)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid = signer.unsign(sid) except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) store_id = self.key_prefix + sid document = self.store.find_one({'id': store_id}) if document and document.get('expiration') <= datetime.utcnow(): # Delete expired session self.store.delete({'id': store_id}) document = None if document is not None: try: val = document['val'] data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) # create a new session if the request does not include a token if not sid: return self.session_class(sid=self._generate_sid()) # attempt to retrieve the session associated with the given token store_id = self.key_prefix + sid saved_session = self.sql_session_model.query.filter_by(session_id=store_id).first() # create a new session if the token doesn't represent a valid session if not saved_session: return self.session_class(sid=self._generate_sid()) # create a new session if the session has expired elif saved_session.expiry <= datetime.utcnow(): # purge the expired session self.db.session.delete(saved_session) self.db.session.commit() return self.session_class(sid=self._generate_sid()) # handle valid sessions else: try: val = saved_session.data data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid)
def file_upload(): """Upload the file to the server. ``POST /file`` :return: JSON containing internal metadata of the uploaded file """ try: file = request.files['file'] except KeyError: raise abort(400) if not validate_file_type(file._file, file.mimetype): raise abort(415) file.stream.seek(0) filename = werkzeug.utils.secure_filename(file.filename) with tempfile.NamedTemporaryFile( dir=app.config['MEDIA_DIR'], delete=False) as tf: file.save(tf) file_record = models.File( title=filename, mimetype=file.mimetype, path=tf.name ) with start_session() as session: session.add(file_record) session.commit() file_id = file_record.id return JsonResponse({ 'statuscode': 201, 'id': file_id, 'signedId': signer.sign(itsdangerous.want_bytes(file_id)).decode('utf-8'), 'title': filename, 'mimetype': file.mimetype, 'downloadURI': '/file/%s/download' % file_id }, status=201)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid = signer.unsign(sid) except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) full_session_key = self.key_prefix + sid if PY2 and isinstance(full_session_key, unicode): full_session_key = full_session_key.encode('utf-8') val = self.client.get(full_session_key) if val is not None: try: if not PY2: val = want_bytes(val) data = self.serializer.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def open_session(self, app, request): ds_client = self.get_client() sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) store_id = self.key_prefix + sid session_key = ds_client.key('session', store_id) saved_session = ds_client.get(session_key) if saved_session and saved_session['expiry'] <= pytz.utc.localize(datetime.now()): ds_client.delete(session_key) saved_session = None if saved_session: try: val = saved_session['data'] data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) # create a new session if the request does not include a token if not sid: return self.session_class(sid=self._generate_sid()) # attempt to retrieve the session associated with the given token store_id = self.key_prefix + sid saved_session = self.sql_session_model.query.filter_by( session_id=store_id).first() # create a new session if the token doesn't represent a valid session if not saved_session: return self.session_class(sid=self._generate_sid()) # create a new session if the session has expired elif saved_session.expiry <= datetime.utcnow(): # purge the expired session self.db.session.delete(saved_session) self.db.session.commit() return self.session_class(sid=self._generate_sid()) # handle valid sessions else: try: val = saved_session.data data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) store_id = self.key_prefix + sid document = self.store.find_one({'id': store_id}) if document and document.get('expiration') <= datetime.utcnow(): # Delete expired session self.store.remove({'id': store_id}) document = None if document is not None: try: val = document['val'] data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) store_id = self.key_prefix + session.sid if not session: if session.modified: self.store.delete({"id": store_id}) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) self.store.update({"id": store_id}, {"id": store_id, "val": val, "expiration": expires}, True) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie( app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, )
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) store_id = self.key_prefix + session.sid if not session: if session.modified: self.store.remove({'id': store_id}) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) samesite = self.get_cookie_samesite(app) val = self.serializer.dumps(dict(session)) self.store.update({'id': store_id}, { 'id': store_id, 'val': val, 'expiration': expires }, True) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, samesite=samesite)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) full_session_key = self.key_prefix + session.sid if isinstance(full_session_key, unicode): full_session_key = full_session_key.encode("utf-8") if not session: if session.modified: self.client.delete(full_session_key) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) self.client.set( full_session_key, val, self._get_memcache_timeout(total_seconds(app.permanent_session_lifetime)) ) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie( app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, )
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) full_session_key = self.key_prefix + sid if PY2 and isinstance(full_session_key, unicode): full_session_key = full_session_key.encode('utf-8') val = self.client.get(full_session_key) if val is not None: try: if not PY2: val = want_bytes(val) data = self.serializer.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: self.redis.delete(self.key_prefix + session.sid) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) self.redis.setex(name=self.key_prefix + session.sid, value=val, time=total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) full_session_key = self.key_prefix + session.sid if PY2 and isinstance(full_session_key, unicode): full_session_key = full_session_key.encode('utf-8') if not session: if session.modified: self.client.delete(full_session_key) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) if not PY2: val = self.serializer.dumps(dict(session), 0) else: val = self.serializer.dumps(dict(session)) self.client.set(full_session_key, val, self._get_memcache_timeout( total_seconds(app.permanent_session_lifetime))) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): if not self.should_set_cookie(app, session): return domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: self.redis.delete(self.key_prefix + session.sid) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return # Modification case. There are upsides and downsides to # emitting a set-cookie header each request. The behavior # is controlled by the :meth:`should_set_cookie` method # which performs a quick check to figure out if the cookie # should be set or not. This is controlled by the # SESSION_REFRESH_EACH_REQUEST config flag as well as # the permanent flag on the session itself. # if not self.should_set_cookie(app, session): # return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) self.redis.setex(name=self.key_prefix + session.sid, value=val, time=total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) if self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid = signer.unsign(sid) except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent) store_id = self.key_prefix + sid saved_session = self.sql_session_model.query.filter_by(session_id=store_id).first() if saved_session and saved_session.expiry <= datetime.utcnow(): # purge expired session self.db.session.delete(saved_session) self.db.session.commit() saved_session = None if saved_session: try: val = saved_session.data data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid, permanent=self.permanent) return self.session_class(sid=sid, permanent=self.permanent)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: self.cache.delete(self.key_prefix + session.sid) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) data = dict(session) self.cache.set(self.key_prefix + session.sid, data, total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie( app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, )
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) if not session: if session.modified: self.redis.delete(self.key_prefix + session.sid) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return # Modification case. There are upsides and downsides to # emitting a set-cookie header each request. The behavior # is controlled by the :meth:`should_set_cookie` method # which performs a quick check to figure out if the cookie # should be set or not. This is controlled by the # SESSION_REFRESH_EACH_REQUEST config flag as well as # the permanent flag on the session itself. # if not self.should_set_cookie(app, session): # return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) self.redis.setex(name=self.key_prefix + session.sid, value=val, time=total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) store_id = self.key_prefix + session.sid saved_session = self.sql_session_model.query.filter_by( session_id=store_id).first() if not session: if session.modified: if saved_session: self.db.session.delete(saved_session) self.db.session.commit() response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) if saved_session: saved_session.data = val saved_session.expiry = expires self.db.session.commit() else: new_session = self.sql_session_model(store_id, val, expires) self.db.session.add(new_session) self.db.session.commit() if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, max_age=app.permanent_session_lifetime, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) store_id = self.key_prefix + session.sid if not session: if session.modified: self.client.delete(index=self.index, id=store_id) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = dict(session) self.client.index(index=self.index, id=store_id, body={ 'id': store_id, 'val': val, 'expiration': expires } ) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def test_exception_attributes(self): secret_key = 'predictable-key' value = u'hello' s = self.make_serializer(secret_key) ts = s.dumps(value) try: s.loads(ts, max_age=-1) except idmod.SignatureExpired as e: self.assertEqual(e.date_signed, datetime.utcfromtimestamp(time.time())) self.assertEqual(want_bytes(e.payload), want_bytes(ts).rsplit(b'.', 2)[0]) self.assertEqual(s.load_payload(e.payload), value) else: self.fail('Did not get expiration')
def save_session(self, app, session, response): """ 程序结束前执行,可以保存session中所有的值 如: 保存到resit 写入到用户cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在内存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) store_id = self.key_prefix + session.sid saved_session = self.sql_session_model.query.filter_by( session_id=store_id).first() if not session: if session.modified: if saved_session: self.db.session.delete(saved_session) self.db.session.commit() response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = self.serializer.dumps(dict(session)) if saved_session: saved_session.data = val saved_session.expiry = expires self.db.session.commit() else: new_session = self.sql_session_model(store_id, val, expires) self.db.session.add(new_session) self.db.session.commit() if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def open_session(self, app, request): # Check for cookieless session in the path path_session = re.match(r"(/@)([a-f0-9A-F_]*)(@)", request.path) # Check if currently accessed URL is LTI launch page try: # request.url_rule is not set yet here. endpoint, args = app.create_url_adapter(request).match() is_lti_launch = app.view_functions.get( endpoint).view_class == LTILaunchPage except HTTPException: is_lti_launch = False if path_session: # Cookieless session cookieless = True sid = path_session.group(2) elif is_lti_launch: cookieless = True sid = None else: cookieless = False sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent, cookieless=cookieless) if not path_session and self.use_signer: signer = self._get_signer(app) if signer is None: return None try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid, permanent=self.permanent, cookieless=cookieless) store_id = sid document = self.store.find_one({'_id': store_id}) if document and document.get('expiration') <= datetime.utcnow(): # Delete expired session self.store.remove({'_id': store_id}) document = None if document is not None: try: val = document['data'] data = self.serializer.loads(want_bytes(val)) return self.session_class(data, sid=sid, cookieless=cookieless) except: return self.session_class(sid=sid, permanent=self.permanent, cookieless=cookieless) return self.session_class(sid=sid, permanent=self.permanent, cookieless=cookieless)
def fetch_lti_data(self, sessionid): # TODO : Flask session interface does not allow to open a specific session # It could be worth putting these information outside of the session dict sess = self.database.sessions.find_one({"_id": sessionid}) if sess: cookieless_session = self.app.session_interface.serializer.loads(want_bytes(sess['data'])) else: return KeyError() return sessionid, cookieless_session["lti"]
def save_session(self, app, session, response): if self.cookie_domain is not None: domain = self.cookie_domain if self.cookie_domain else self.get_cookie_domain( app) else: domain = self.get_cookie_domain(app) path = self.cookie_path or self.get_cookie_path(app) store_id = self.key_prefix + session.get_sid(self.cookie_name) if PY2 and isinstance(store_id, unicode): store_id = store_id.encode('utf-8') if not session: if session.modified: try: self.client.delete(store_id) except Exception as e: log.error( f'Error while deleting session (session id: {store_id}): {e}' ) response.delete_cookie(self.cookie_name, domain=domain, path=path) return httponly = self.cookie_httponly or self.get_cookie_httponly(app) secure = self.cookie_secure or self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) if session.modified: # The session was modified data = {'_permanent': session.is_permanent(self.cookie_name)} data.update(dict(session)) val = self.serializer.dumps(data) try: log.debug('Setting document to db') self.client.set( store_id, val, self._get_memcache_timeout(total_seconds(expires))) except Exception as e: log.error( f'Error while updating session (session id: {store_id}): {e}' ) if self.use_signer: session_id = self._get_signer(app).sign( want_bytes(session.get_sid(self.cookie_name))) else: session_id = session.get_sid(self.cookie_name) cookie_expires = self.get_cookie_expiration_time(app, session) response.set_cookie(self.cookie_name, session_id, expires=cookie_expires, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) full_session_key = self.key_prefix + session.sid if PY2 and isinstance(full_session_key, unicode): full_session_key = full_session_key.encode('utf-8') if not session: if session.modified: self.client.delete(full_session_key) response.delete_cookie(app.session_cookie_name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) samesite = self.get_cookie_samesite(app) if not PY2: val = self.serializer.dumps(dict(session), 0) else: val = self.serializer.dumps(dict(session)) self.client.set( full_session_key, val, self._get_memcache_timeout( total_seconds(app.permanent_session_lifetime))) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid from BTPanel import request, g, get_input if 'auth_error' in g: return if request.path in ['/', '/tips', '/robots.txt']: return if request.path in ['/public']: get = get_input() if 'get_ping' in get: return if response.status_code in [401]: return if request.full_path.find('/login?tmp_token=') != 0: if response.status_code not in [200, 308]: return else: if response.status_code not in [302, 301]: return if secure: samesite = 'None' if response.status_code not in [200, 302]: return if not request.cookies.get(app.session_cookie_name): if request.full_path.find('/login?tmp_token=') == 0: samesite = 'None' secure = True response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, samesite=samesite)
def peak_token_data(token): """ Peaks at a tokens data without any validation/verification of the signature. :param token: The token to peak at. :rtype: Any valid JSON data """ try: payload = itsdangerous.want_bytes(token).rsplit('.', 2)[0] return _unsafe_deserializer.load_payload(payload) except (itsdangerous.BadPayload, IndexError): return None
def tamper_with(bs): """Return len(bs)-variants of the bytestring bs, each with a different byte altered.""" bs = want_bytes(bs) for i in range(0, len(bs)): new_byte = int2byte((indexbytes(bs, i) ^ 255) & 127 # stay in ascii range ) yield bs[:i] + new_byte + bs[i + 1:]
def test_is_base62(self): allowed = frozenset(b'0123456789abcdefghijklmnopqrstuvwxyz' + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ_-.') objects = (['a', 'list'], 'a string', u'a unicode string \u2019', {'a': 'dictionary'}, 42, 42.5) s = self.make_serializer('Test') for o in objects: value = want_bytes(s.dumps(o)) self.assertTrue(set(value).issubset(set(allowed))) self.assertNotEqual(o, value) self.assertEqual(o, s.loads(value))
def save_session(self, app, session, response): if self.cookie_domain is not None: domain = self.cookie_domain if self.cookie_domain else self.get_cookie_domain( app) else: domain = self.get_cookie_domain(app) path = self.cookie_path or self.get_cookie_path(app) if not session: if session.modified: self._delete_session_from_store( self.key_prefix + session.get_sid(self.cookie_name)) response.delete_cookie(self.cookie_name, domain=domain, path=path) return httponly = self.cookie_httponly or self.get_cookie_httponly(app) secure = self.cookie_secure or self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) if session.modified: # The session was modified store_id = self.key_prefix + session.get_sid(self.cookie_name) val = self.serializer.dumps(dict(session)) try: log.debug('Setting document to db') self.store.update( {'id': store_id}, { 'id': store_id, 'val': val, '_expiration': expires, '_permanent': session.is_permanent(self.cookie_name) }, True) except Exception as e: log.error( f'Error while updating session (session id: {store_id}): {e}' ) if self.use_signer: session_id = self._get_signer(app).sign( want_bytes(session.get_sid(self.cookie_name))) else: session_id = session.get_sid(self.cookie_name) cookie_expires = self.get_cookie_expiration_time(app, session) response.set_cookie(self.cookie_name, session_id, expires=cookie_expires, httponly=httponly, domain=domain, path=path, secure=secure)
def save_session(self, app, session, response): if self.cookie_domain is not None: domain = self.cookie_domain if self.cookie_domain else self.get_cookie_domain( app) else: domain = self.get_cookie_domain(app) path = self.cookie_path or self.get_cookie_path(app) if not session: if session.modified: self._delete_session_from_store( self.key_prefix + session.get_sid(self.cookie_name)) response.delete_cookie(self.cookie_name, domain=domain, path=path) return httponly = self.cookie_httponly or self.get_cookie_httponly(app) secure = self.cookie_secure or self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) if session.modified: # The session was modified store_id = self.key_prefix + session.get_sid(self.cookie_name) data = {'_permanent': session.is_permanent(self.cookie_name)} data.update(dict(session)) val = self.serializer.dumps(data) try: self.client.setex(name=store_id, value=val, time=total_seconds(expires)) except Exception as e: log.error( 'Error while updating session (session id: {}): {}'.format( store_id, str(e))) if self.use_signer: session_id = self._get_signer(app).sign( want_bytes(session.get_sid(self.cookie_name))) else: session_id = session.get_sid(self.cookie_name) cookie_expires = self.get_cookie_expiration_time(app, session) response.set_cookie(self.cookie_name, session_id, expires=cookie_expires, httponly=httponly, domain=domain, path=path, secure=secure)
def open_session(self, app, request): sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self.generate_sid() return self.session_class(sid=sid) data = Session.query.filter_by(sid=sid).first() if data and data.expiry and data.expiry <= datetime.utcnow(): # Delete expired session self.db.session.delete(data) self.db.session.commit() data = None if data is not None: val = self.serializer.loads(want_bytes(data.value)) return self.session_class(val, sid=sid) return self.session_class(sid=sid)
def save_session(self, app, session, response): if not session: if session.modified: self.cache.delete(self.key_prefix + session.sid) response.headers.pop(app.config.get('SESSION_HEADER_NAME', 'X-Header-Session'), None) return expires = self.get_expiration_time(app, session) data = dict(session) self.cache.set(self.key_prefix + session.sid, data, total_seconds(app.permanent_session_lifetime)) if self.use_signer: session_id = self._get_signer(app).sign(want_bytes(session.sid)) else: session_id = session.sid response.headers[app.config.get('SESSION_HEADER_NAME', 'X-Header-Session')] = session_id
def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) sid = session.sid db_session = SessionManager.Session() saved_session = db_session.query(ServerSession).filter(ServerSession.session_id == sid).first() if not session: if session.modified: if saved_session: db_session.delete(saved_session) db_session.commit() response.delete_cookie(app.session_cookie.name, domain=domain, path=path) return httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) # expires = datetime.utcnow() + timedelta(minutes=1) # if expires is None: # expires = datetime.utcnow() + timedelta(days=1) val = self.serializer.dumps(dict(session)) if saved_session: saved_session.data = val saved_session.expiry = expires db_session.commit() else: new_session = ServerSession(session_id=sid, data=val, expiry=expires) db_session.add(new_session) db_session.commit() session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure)
def test_want_bytes(self): self.assertEqual(want_bytes(b"foobar"), b"foobar") self.assertEqual(want_bytes(u"foobar"), b"foobar")
def create_signed_key(user): """Generate a valid auth token for the user, and sign it.""" key = core.create_session_key(user) signer = get_signer() return signer.sign(want_bytes(key)).decode('ascii')