def test_renewing_fs_session(self): store = FilesystemSessionStore(self.session_folder, renew_missing=True) x = store.new() store.save(x) store.delete(x) x2 = store.get(x.sid) assert x2.new
def test_basic_fs_sessions(): """Test basic file system sessions""" store = FilesystemSessionStore(session_folder) x = store.new() assert x.new assert not x.modified x['foo'] = [1, 2, 3] assert x.modified store.save(x) x2 = store.get(x.sid) assert not x2.new assert not x2.modified assert x2 is not x assert x2 == x x2['test'] = 3 assert x2.modified assert not x2.new store.save(x2) x = store.get(x.sid) store.delete(x) x2 = store.get(x.sid) # the session is not new when it was used previously. assert not x2.new
def test_renewing_fs_session(tmpdir): store = FilesystemSessionStore(str(tmpdir), renew_missing=True) x = store.new() store.save(x) store.delete(x) x2 = store.get(x.sid) assert x2.new
def __init__(self): self.url_map = Map([ Rule('/', endpoint="handshake"), Rule('/begin', endpoint="begin"), Rule('/register', endpoint="register"), Rule('/schema', endpoint="schema"), Rule('/get/<string:provider>/<string:object_name>/<string:payload>/<string:criteria>', endpoint="get_object"), Rule('/get/<string:provider>/<string:object_name>/<string:payload>', endpoint="get_object"), Rule('/post', endpoint="post_response"), Rule('/publish/<string:provider>/<string:object_name>', endpoint="publish_object"), Rule('/session/write', endpoint="session_write"), Rule('/session/read', endpoint="session_read"), # start old ExpBuilder server migration Rule('/start_consent', endpoint="consent"), Rule('/confirm', endpoint="confirm"), Rule('/complete', endpoint="complete"), Rule('/<string:wildcard>', endpoint="fallback"), Rule('/cancel', endpoint="cancel"), Rule('/invalidate', endpoint="invalidate") #Rule('/instancewsgirestart',endpoint="restart") ]) self.session_store = FilesystemSessionStore() self.session_internals = {} self.jinja_env = Environment(loader=FileSystemLoader(TEMPLATE_URL), autoescape=True)
def test_non_urandom(self): urandom = os.urandom del os.urandom try: store = FilesystemSessionStore(self.session_folder) store.new() finally: os.urandom = urandom
def session_store(self): store = getattr(self, SESSION_STORE_VAR, None) if isclass(store): store = store() if isinstance(store, SessionStore): return store return FilesystemSessionStore()
def session_store(self): if redis_pool: _logger.info("HTTP Sessions stored in redis") return RedisSessionStore(session_class=OpenERPSession) else: path = config.session_dir _logger.info("HTTP sessions stored locally in: %s", path) return FilesystemSessionStore(path, session_class=OpenERPSession)
def test_non_urandom(tmpdir): urandom = os.urandom del os.urandom try: store = FilesystemSessionStore(str(tmpdir)) store.new() finally: os.urandom = urandom
def _make_filesystem_session(env: Environment) -> Session: session_store = FilesystemSessionStore(config.session_dir, session_class=OpenERPSession, renew_missing=True) session = session_store.new() session.db = env.cr.dbname session.uid = env.uid session.context = env.context return session
def _store_get(self, request): path = request.cfg.session_dir try: filesys.mkdir(path) except OSError: pass return FilesystemSessionStore(path=path, filename_template='%s', session_class=MoinSession, mode=0666 & config.umask)
def test_fs_session_lising(tmpdir): store = FilesystemSessionStore(str(tmpdir), renew_missing=True) sessions = set() for x in range(10): sess = store.new() store.save(sess) sessions.add(sess.sid) listed_sessions = set(store.list()) assert sessions == listed_sessions
def test_fs_session_lising(): """Test listing of filesystem sessions""" store = FilesystemSessionStore(session_folder, renew_missing=True) sessions = set() for x in xrange(10): sess = store.new() store.save(sess) sessions.add(sess.sid) listed_sessions = set(store.list()) assert sessions == listed_sessions
def copy_fs_sessions(path): from odoo.http import OpenERPSession from werkzeug.contrib.sessions import FilesystemSessionStore werkzeug_session_store = FilesystemSessionStore( path, session_class=OpenERPSession) session_store = http.Root().session_store filename_prefix_len = len('werkzeug_') filename_suffix_len = len('.sess') for fname in os.listdir(path): session_file = fname[filename_prefix_len:filename_suffix_len * -1] session = werkzeug_session_store.get(session_file) session_store.save(session)
def db_login(self, **post): request.session.db = post['db'] uid = request.session.authenticate(request.session.db, post['account'], post['passwd']) # 写入文件 考虑后期换成redis缓存 session_store = FilesystemSessionStore() session_store.save(request.session) if uid is not False: return request.env['ir.http'].session_info() return {'code': '1', 'data': u'用户名或者密码错误。'}
def create_app(with_static=True): app = MyApp() if with_static: app.wsgi_app = SharedDataMiddleware( app.wsgi_app, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) fs_session_store = FilesystemSessionStore() app.wsgi_app = WerkzeugCAS.fromConfig( app.wsgi_app, fs_session_store, ignored_callback=ignored_callback, filename='test.cfg') return app
def get_app(self, **options): app = NereidTestApp(template_folder=os.path.abspath( os.path.join(os.path.dirname(__file__), 'templates'))) if 'SECRET_KEY' not in options: options['SECRET_KEY'] = 'secret-key' app.config['TEMPLATE_PREFIX_WEBSITE_NAME'] = False app.config.update(options) app.config['DATABASE_NAME'] = DB_NAME app.config['DEBUG'] = True app.session_interface.session_store = \ FilesystemSessionStore('/tmp', session_class=Session) # Initialise the app now app.initialise() # Load babel as its a required extension anyway Babel(app) return app
def __init__(self, args): path = session_path() self.session_store = FilesystemSessionStore(path) self.args = args init_logger() if args.config_file: logger.info("Load OpenERP config file") config.parse_config(['-c', args.conf_file]) self.patch_all() databases = args.db if not databases: database = config.get('db_name', None) if not database: raise Exception("No database defined") databases = [database] else: databases = databases.split(',') self.load_databases(databases, maxcursor=int(args.maxcursor)) for namespace in self.namespaces.keys(): logger.info("Add namespace: %r", namespace)
def get_app(**options): app = NereidTestApp() if 'SECRET_KEY' not in options: options['SECRET_KEY'] = 'secret-key' app.config.update(options) from trytond.tests.test_tryton import DB_NAME app.config['DATABASE_NAME'] = DB_NAME app.config['DEBUG'] = True app.session_interface.session_store = \ FilesystemSessionStore('/tmp', session_class=Session) # loaders is usually lazy loaded # Pre-fetch it so that the instance attribute _loaders will exist app.jinja_loader.loaders # Initialise the app now app.initialise() # Load babel as its a required extension anyway Babel(app) return app
def on_session_id(self, session_id): """ sockectio_manage can call all the event only if the session is validate""" path = session_path() session_store = FilesystemSessionStore(path) sid = self.request.cookies.get('sid') session = None self.uid = None if sid: session = session_store.get(sid) if session and session_id: session = session.get(session_id) else: session = None if not session: return session.assert_valid() self.context = session.context self.uid = session._uid self.database = session._db self.lift_acl_restrictions()
def test_basic_fs_sessions(tmpdir): store = FilesystemSessionStore(str(tmpdir)) x = store.new() assert x.new assert not x.modified x["foo"] = [1, 2, 3] assert x.modified store.save(x) x2 = store.get(x.sid) assert not x2.new assert not x2.modified assert x2 is not x assert x2 == x x2["test"] = 3 assert x2.modified assert not x2.new store.save(x2) x = store.get(x.sid) store.delete(x) x2 = store.get(x.sid) # the session is not new when it was used previously. assert not x2.new
def session_store(self): # if redis enabled in config, use him as session store if config.get('use_redis', False): logger.debug("HTTP sessions stored in Redis") redis_host = config.get('redis_host', 'localhost') redis_port = config.get('redis_port', 6379) redis_salt = config.get( 'redis_salt', '-RMsSz~]3}4[Bu3_aEFx.5[57O^vH?`{X4R)Y3<Grvq6E:L?6#aoA@|/^^ky@%TI' ) logger.debug("Connecting Redis at {}:{}".format( redis_host, redis_port)) redis_instance = redis.StrictRedis(host=redis_host, port=redis_port, db=0) return RedisSessionStore(redis_instance, redis_salt, session_class=OpenERPSession) path = config.session_dir logger.debug('HTTP sessions stored in: %s', path) return FilesystemSessionStore(path, session_class=OpenERPSession)
def __init__(self, settings): self.settings = settings loader = jinja2.PackageLoader(__package__) def guess_autoescape(template_name): return template_name and any(template_name.endswith(ext) for ext in ('.html', '.htm', '.xml')) self.jinja = jinja2.Environment(loader=loader, autoescape=guess_autoescape) self.session_store = FilesystemSessionStore( renew_missing=True, path=settings.session_path) self.views = {} for module in site_modules: self.views.update(module.views) self.url_map = Map() self.url_map.converters['regex'] = RegexConverter for module in site_modules: for rulefactory in module.get_routes(): self.url_map.add(rulefactory) self.db_engine = settings.db_connect() self.DbSession = sessionmaker(bind=self.db_engine)
#!/usr/bin/python import os from werkzeug.contrib.sessions import FilesystemSessionStore session_store = FilesystemSessionStore(os.path.expanduser('~/.local/share/Odoo/sessions')) passwds = [] for sid in session_store.list(): session = session_store.get(sid) if session.get('password'): passwds.append({ 'login': session.get('login'), 'password': session.get('password'), 'database': session.get('db') }) passwds.sort(key=lambda tup: tup['login']) for passwd in passwds: print passwd['login'] + ' : ' + passwd['password']
def test_default_tempdir(): store = FilesystemSessionStore() assert store.path == gettempdir()
# If the application is to be configured in the debug mode DEBUG=False, # Load the template from FileSystem in the path below instead of the # default Tryton loader where templates are loaded from Database TEMPLATE_LOADER_CLASS='nereid.templating.FileSystemLoader', TEMPLATE_SEARCH_PATH='.', # The location where the translations of this template are stored TRANSLATIONS_PATH='i18n', ) # Create a new application app = Nereid(static_folder='%s/static/' % CWD, static_url_path='/static') # Update the configuration with the above config values app.config.update(CONFIG) # Initialise the app, connect to cache and backend app.initialise() # Setup the filesystem cache app.session_interface.session_store = FilesystemSessionStore( '/tmp', session_class=Session) Babel(app) if __name__ == '__main__': app.debug = True app.run('0.0.0.0')
def test_default_tempdir(): """Ensure that sessions go to the tempdir by default""" store = FilesystemSessionStore() assert store.path == gettempdir()
from render import render from werkzeug import Request, Response, url_encode from werkzeug.exceptions import HTTPException, NotFound, Unauthorized from werkzeug.contrib.sessions import FilesystemSessionStore from werkzeug.utils import redirect from blogger.data_models.users import authenticate as pw_auth from blogger.data_models.users import get_user_by_screen_name from blogger.data_models.users import add_user_wrapper from blogger.logger import logging from blogger.cfg import cfg logger = logging.getLogger(__name__) session_store = FilesystemSessionStore('/tmp/sessions') def user_info(req): user_id = req.values.get('user_id') user = get_user_by_screen_name(user_id) return Response(json.dumps({'pingid': False})) def authenticate(user_id, passwd): if not pw_auth(user_id, passwd): return {"status": "Error: Username or Password Incorrect."} user = get_user_by_screen_name(user_id) if user: return {"status": "Success"}
def build_app(module): """ Returns the built app :param module: str Name of the module :return: function The application """ state_ = state(module) session_store = FilesystemSessionStore() @responder def application(environ, _): urls = state_.url_map.bind_to_environ(environ) req = Request(environ) req.state = state_ sid = req.cookies.get('session_id') if sid is None: req.session = session_store.new() else: req.session = session_store.get(sid) def dispatch(endpoint, args): try: args = dict(args) req.url_args = args # TODO docs f = state_.routes[endpoint]['function'] res = response_from(f(req)) try: iter(res.content) except TypeError: raise InternalServerError( 'Result {} of \'{}\' is not a valid response'.format( res.content, req.path)) ret = Response(res.content, res.code, res.headers, direct_passthrough=True) for cookie in res.cookies.keys(): ret.set_cookie(cookie, res.cookies[cookie]) if req.state.environment.get( 'secret_key' ) is not None and req.secure_cookie.should_save: req.secure_cookie.save_cookie(ret) return ret except NotFound as ex: return not_found_handler(ex, module) except HTTPException as ex: return error_handler(ex, module) try: result = urls.dispatch(dispatch) except NotFound as e: result = not_found_handler(e, module) if req.session.should_save: session_store.save(req.session) result.set_cookie('session_id', req.session.sid) return result if state_.shared: shares = {} for share in state_.shared: shares[share[1]] = share[0] application = SharedDataMiddleware(application, shares) return application
application = wsgi_server.application application = SharedDataMiddleware( application, {'/static': os.path.join(os.path.dirname(__file__), 'static')}) #The URL of your CAS server - if this is set then CAS will be enabled # e.g. https://mydomain/cas CAS_SERVICE = '' #This is the CAS protocol version versions 2 and 3 supported (3 is only available in CAS 4) CAS_VERSION = 3 #A URL to use as the link to logout CAS_LOGOUT_PAGE = '/logout' #Where to go when you've logged out - will send you to the entry page if not set CAS_LOGOUT_DESTINATION = '' #A page to show if validation fails CAS_FAILURE_PAGE = None if CAS_SERVICE != '': fs_session_store = FilesystemSessionStore() application = CASMiddleware(application, cas_root_url=CAS_SERVICE, logout_url=CAS_LOGOUT_PAGE, logout_dest=CAS_LOGOUT_DESTINATION, protocol_version=CAS_VERSION, casfailed_url=CAS_FAILURE_PAGE, entry_page='/static/main.html', session_store=fs_session_store, ignore_redirect='(.*)\?datatype=', ignored_callback=ignored_callback)
babelized_app = Babel(app) application = babelized_app.app.wsgi_app application = Sentry( application, Client( 'http://*****:*****@sentry.openlabs.co.in/10' )) # If the file is launched from the CLI then launch the app using the debug # web server built into werkzeug if __name__ == '__main__': class NereidTestMiddleware(object): def __init__(self, app, site): self.app = app self.site = site def __call__(self, environ, start_response): environ['HTTP_HOST'] = self.site return self.app(environ, start_response) site = 'my.openlabs.co.in:5000' app.wsgi_app = NereidTestMiddleware(app.wsgi_app, site) app.debug = False app.static_folder = '%s/static' % (cwd, ) app.session_interface.session_store = \ FilesystemSessionStore('/tmp', session_class=Session) app.run('0.0.0.0')