def get_browser_locale(self, default="en_US"): """Determines the user's locale from ``Accept-Language`` header. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 This code is copied from web.py in Tornado. Regardless of what the link above says, Tornado does not parse the Accept-Language string properly. zh-hans-SE for instance is ditched. So, we're creating our own flavour here where. Not the coolest thing, but necessary in this case I think. """ if "Accept-Language" in self.request.headers: languages = self.request.headers["Accept-Language"].split(",") locales = [] for language in languages: parts = language.strip().split(";") if len(parts) > 1 and parts[1].startswith("q="): try: score = float(parts[1][2:]) except (ValueError, TypeError): score = 0.0 else: score = 1.0 # <Keyflow magic here!> if len(parts[0].split("-")) > 1: last_dash = parts[0].rfind("-") parts[0] = parts[0][:last_dash] # </Keyflow magic here!> locales.append((parts[0], score)) if locales: locales.sort(key=lambda pair: pair[1], reverse=True) codes = [l[0] for l in locales] return locale.get(*codes) return locale.get(default)
def get_user_locale(self): """ Sets and returns logged in user locale. """ self.require_setting('default_language', 'this application') if self.current_user: return locale.get(self.current_user['language']) else: return locale.get(self.settings['default_language'])
def get_user_locale(self): user_locale = self.get_argument('lang', None) # user_locale = self.get_browser_locale() # print(user_locale.code) if user_locale == 'en': return locale.get('en_US') elif user_locale == 'cn': return locale.get('zh_CN') return locale.get('zh_CN')
def get_user_locale(self): if self.settings["lang"]: # print("Lang forced to", self.settings["lang"]) return locale.get(self.settings["lang"]) user_lang = self.get_cookie("lang", False) if user_lang: print("Lang cookie to", user_lang) return locale.get(user_lang) # print("Lang False") return locale.get("en")
def get_translation(settings_dir=None): """ Looks inside Gate One's settings to determine the configured locale and returns a matching locale.get_translation function. If no locale is set (e.g. first time running Gate One) the local `$LANG` environment variable will be used. This function is meant to be used like so:: >>> from gateone.core.locale import get_translation >>> _ = get_translation() """ if not settings_dir: # Check the tornado options object first if hasattr(options, 'settings_dir'): settings_dir = options.settings_dir else: # Fall back to the default settings dir settings_dir = os.path.join(os.path.sep, 'etc', 'gateone' 'conf.d') # If none of the above worked we can always just use en_US: locale_str = os.environ.get('LANG', 'en_US').split('.')[0] try: settings = get_settings(settings_dir) gateone_settings = settings['*'].get('gateone', None) if gateone_settings: # All these checks are necessary for early startup locale_str = settings['*']['gateone'].get('locale', locale_str) except IOError: # server.conf doesn't exist (yet). # Fall back to os.environ['LANG'] # Already set above pass user_locale = locale.get(locale_str) return user_locale.translate
def get_translation(): """ Looks inside GATEONE_DIR/server.conf to determine the configured locale and returns a matching locale.get_translation function. Meant to be used like this: >>> from utils import get_translation >>> _ = get_translation() """ gateone_dir = os.path.dirname(os.path.abspath(__file__)) server_conf = os.path.join(gateone_dir, 'server.conf') try: locale_str = os.environ.get('LANG', 'en_US').split('.')[0] with open(server_conf) as f: for line in f: if line.startswith('locale'): locale_str = line.split('=')[1].strip() locale_str = locale_str.strip('"').strip("'") break except IOError: # server.conf doesn't exist (yet). # Fall back to os.environ['LANG'] # Already set above pass user_locale = locale.get(locale_str) return user_locale.translate
def get_user_locale(self): """ Get user lang value from config. If None is returned, Tornado fall back to get_browser_locale() """ if len(self.config.force_locale) > 0: return locale.get(self.config.force_locale) return None
def __init__(self, cls): self.fields = {} self.field_rules = [] self._validation_rules = False self._request_cls = cls self.user_locale = locale.get(self.get_user_locale())
def translate(word, lang=None): lang = lang or settings.DEFAULT_LANG language = mapping.get(lang) or lang locale.load_gettext_translations( directory="/Users/sestari/Documents/brainiak_api/locale", domain="brainiak") user_locale = locale.get(language) return user_locale.translate(word)
def get_user_locale(self): bk_lang = self.get_cookie(settings.LANGUAGE_COOKIE_NAME) try: lang_code = get_supported_language_variant(bk_lang) except LookupError: lang_code = settings.LANGUAGE_CODE translation.activate(lang_code) return locale.get(lang_code)
def get_user_locale(self): """Return current request locale """ localeLang = self.get_argument('_i18n_', '') if localeLang <> '': # self.request.headers["Accept-Language"] = localeLang return locale.get(localeLang) else: return self.get_browser_locale()
def __init__(self, application, request, **kwargs): if BaseHandler._first_running: self._after_prefork() BaseHandler._first_running = False #国际化 locale.load_translations("./protected/translations") locale.set_default_locale("zh_CN") self._locale = locale.get() super(BaseHandler, self).__init__(application, request, **kwargs) self.session = session.Session(self.application.session_manager, self)
def wrapper(*args, **kwargs): l = locale.get('en_US') if self.SETTINGS_TYPE == self.SETTINGS_PER_BOT: l = locale.get(self.settings.get('locale', 'en_US')) elif self.SETTINGS_TYPE == self.SETTINGS_PER_USER: chat_id = None if 'reply_to_message' in kwargs: if 'chat' in kwargs['reply_to_message']: chat_id = kwargs['reply_to_message']['chat']['id'] elif 'from' in kwargs['reply_to_message']: chat_id = kwargs['reply_to_message']['from']['id'] elif 'chat_id' in kwargs: chat_id = kwargs['chat_id'] if chat_id in self.user_settings: l = locale.get(self.user_settings[chat_id].get( 'locale', 'en_US')) return f(*set_locale_recursive(args, l), **set_locale_recursive(kwargs, l))
def get_user_locale(self): """ Get user lang value from config. If None is returned, Tornado fall back to get_browser_locale() """ if len(self.config.force_locale) > 0: return locale.get(self.config.force_locale) else: """ This is a work around as Tornado get_browser_locale() is not returning the closest match. https://github.com/tornadoweb/tornado/issues/1858 https://github.com/moloch--/RootTheBox/issues/367 """ codes = self.request.headers.get("Accept-Language") if codes: for code in codes.split(","): code = code.split(";")[0] for l in locale.get_supported_locales(): if code.lower() == l.split("_")[0]: return locale.get(l) return None
def set_language(request, language, session=None): locale.set_default_locale(LOCALES.get(language, DEFAULT_LANGUAGE)) request.set_secure_cookie('locale', LOCALES.get(language, DEFAULT_LANGUAGE), 1) request.locale = locale.get(LOCALES.get(language, DEFAULT_LOCALE)) if session is not None and session is not False: redis = request.redis.get(threading.currentThread()) """:type : connectors.RedisConnector.RedisConnector""" if redis.exists(str(session)): params = redis.get(session) params = json.loads(str(params)) params["language"] = language redis.set(session, json.dumps(params))
def get_user_locale(self): return locale.get(database.get("user:%s:locale_code" % self.current_user))
confirm_passwd = None ) __rules__ = [ ('name, email, passwd', 'required'), ('name', 'string', dict( string_min = 6, string_max = 12 )), ('name', 'regular', dict( pattern = r"^[a-zA-Z][a-zA-Z0-9]+$", message = "Name has wrong format." )), ('email', 'email'), ('confirm_passwd', 'confirm_passwd_validate') ] def confirm_passwd_validate(self, attribute): _ = form.locale_translate if self.passwd != self.confirm_passwd: self.add_error(attribute, _("confirm passwd not correct.")) form = LoginForm( name = "yinwmfjsdlkfjsdlajlkjsdlkfjdsklfkdjsjfldslkf", email = "*****@*****.**", passwd = "123", confirm_passwd = "123" ) form.locale_translate = locale.get('en_US').translate print form.validate() print form.get_errors()
# print ip_domain_dict # print ip_num_dict return ip_num_dict if __name__ == '__main__': # domain = '0000246.com' # ip测试 # domain = '0-dian.com' # cname测试 # domain = '0-du.com' # 链接测试 # 0518jx.com regphone relative_domain_getter = Relative_domain_getter('000000.com') graph_info, show_info = relative_domain_getter.get_relative_data() # print graph_info from tornado import locale print locale.get() # print graph_info['links'] # print graph_info # from pymongo import MongoClient # mongo_db = MongoClient('172.29.152.151',27017).mal_domain_profile # collection = mongo_db['domain_conn_dm_test'] # domains = list(collection.find({},{'_id':False,'source_domain':True}).limit(100)) # for domain in domains: # domain = domain['source_domain'] # relative_domain_getter = Relative_domain_getter(domain) # graph_info,show_info = relative_domain_getter.get_relative_data() # # relative_domain_getter.get_relative_data() # del relative_domain_getter # print graph_info # print show_info # print '\n'
def define_options(installed=True): """ Calls `tornado.options.define` for all of Gate One's command-line options. If *installed* is ``False`` the defaults will be set under the assumption that the user is non-root and running Gate One out of a download/cloned directory. """ # NOTE: To test this function interactively you must import tornado.options # and call tornado.options.parse_config_file(*some_config_path*). After you # do that the options will wind up in tornado.options.options global user_locale # Default to using the shell's LANG variable as the locale try: default_locale = os.environ['LANG'].split('.')[0] except KeyError: # $LANG isn't set default_locale = "en_US" user_locale = locale.get(default_locale) # NOTE: The locale setting above is only for the --help messages. # Simplify the auth option help message auths = "none, api, google, ssl" from gateone.auth.authentication import PAMAuthHandler, KerberosAuthHandler if KerberosAuthHandler: auths += ", kerberos" if PAMAuthHandler: auths += ", pam" # Simplify the syslog_facility option help message facilities = list(FACILITIES.keys()) facilities.sort() # Figure out the default origins default_origins = [ 'localhost', '127.0.0.1', ] # Used both http and https above to demonstrate that both are acceptable try: additional_origins = socket.gethostbyname_ex(socket.gethostname()) except socket.gaierror: # Couldn't get any IPs from the hostname additional_origins = [] for host in additional_origins: if isinstance(host, str): default_origins.append('%s' % host) else: # It's a list for _host in host: default_origins.append('%s' % _host) default_origins = ";".join(default_origins) config_default = os.path.join(os.path.sep, "opt", "gateone", "server.conf") # NOTE: --settings_dir deprecates --config settings_base = os.path.join(os.path.sep, 'etc', 'gateone') settings_default = os.path.join(settings_base, 'conf.d') port_default = 443 log_default = os.path.join( os.path.sep, "var", "log", 'gateone', 'gateone.log') user_dir_default = os.path.join( os.path.sep, "var", "lib", "gateone", "users") pid_default = os.path.join(os.path.sep, "var", "run", 'gateone.pid') session_dir_default = os.path.join(tempfile.gettempdir(), 'gateone') cache_dir_default = os.path.join(tempfile.gettempdir(), 'gateone_cache') if os.getuid() != 0: # Not root? Use $HOME/.gateone/ for everything home = os.path.expanduser('~') user_dir_default = os.path.join(home, '.gateone') settings_default = os.path.join(user_dir_default, 'conf.d') port_default = 10443 log_default = os.path.join(user_dir_default, 'logs', 'gateone.log') pid_default = os.path.join(user_dir_default, 'gateone.pid') session_dir_default = os.path.join(user_dir_default, 'sessions') cache_dir_default = os.path.join(user_dir_default, 'cache') if not installed: # Running inside the download directory? Change various defaults to # work inside of this directory here = os.path.dirname(os.path.abspath(__file__)) settings_base = os.path.normpath(os.path.join(here, '..', '..')) settings_default = os.path.join(settings_base, 'conf.d') port_default = 10443 log_default = os.path.join(settings_base, 'logs', 'gateone.log') user_dir_default = os.path.join(settings_base, 'users') pid_default = os.path.join(settings_base, 'gateone.pid') session_dir_default = os.path.join(settings_base, 'sessions') cache_dir_default = os.path.join(settings_base, 'cache') options.log_file_prefix = log_default ssl_dir = os.path.join(settings_base, 'ssl') define("version", type=bool, group='gateone', help=_("Display version information."), ) define("config", default=config_default, group='gateone', help=_("DEPRECATED. Use --settings_dir."), type=basestring, ) define("settings_dir", default=settings_default, group='gateone', help=_("Path to the settings directory."), type=basestring ) define( "cache_dir", default=cache_dir_default, group='gateone', help=_( "Path where Gate One should store temporary global files (e.g. " "rendered templates, CSS, JS, etc)."), type=basestring ) define( "debug", default=False, group='gateone', help=_("Enable debugging features such as auto-restarting when files " "are modified.") ) define("cookie_secret", # 45 chars is, "Good enough for me" (cookie joke =) default=None, group='gateone', help=_("Use the given 45-character string for cookie encryption."), type=basestring ) define("command", default=None, group='gateone', help=_( "DEPRECATED: Use the 'commands' option in the terminal settings."), type=basestring ) define("address", default="", group='gateone', help=_("Run on the given address. Default is all addresses (IPv6 " "included). Multiple address can be specified using a semicolon" " as a separator (e.g. '127.0.0.1;::1;10.1.1.100')."), type=basestring) define("port", default=port_default, group='gateone', help=_("Run on the given port."), type=int) define( "enable_unix_socket", default=False, group='gateone', help=_("Enable Unix socket support."), type=bool) define( "unix_socket_path", default="/tmp/gateone.sock", group='gateone', help=_("Path to the Unix socket (if --enable_unix_socket=True)."), type=basestring) # Please only use this if Gate One is running behind something with SSL: define( "disable_ssl", default=False, group='gateone', help=_("If enabled, Gate One will run without SSL (generally not a " "good idea).") ) define( "certificate", default=os.path.join(ssl_dir, "certificate.pem"), group='gateone', help=_("Path to the SSL certificate. Will be auto-generated if none is" " provided."), type=basestring ) define( "keyfile", default=os.path.join(ssl_dir, "keyfile.pem"), group='gateone', help=_("Path to the SSL keyfile. Will be auto-generated if none is" " provided."), type=basestring ) define( "ca_certs", default=None, group='gateone', help=_("Path to a file containing any number of concatenated CA " "certificates in PEM format. They will be used to authenticate " "clients if the 'ssl_auth' option is set to 'optional' or " "'required'."), type=basestring ) define( "ssl_auth", default='none', group='gateone', help=_("Enable the use of client SSL (X.509) certificates as a " "secondary authentication factor (the configured 'auth' type " "will come after SSL auth). May be one of 'none', 'optional', " "or 'required'. NOTE: Only works if the 'ca_certs' option is " "configured."), type=basestring ) define( "user_dir", default=user_dir_default, group='gateone', help=_("Path to the location where user files will be stored."), type=basestring ) define( "user_logs_max_age", default="30d", group='gateone', help=_("Maximum amount of length of time to keep any given user log " "before it is removed."), type=basestring ) define( "session_dir", default=session_dir_default, group='gateone', help=_( "Path to the location where session information will be stored."), type=basestring ) define( "syslog_facility", default="daemon", group='gateone', help=_("Syslog facility to use when logging to syslog (if " "syslog_session_logging is enabled). Must be one of: %s." % ", ".join(facilities)), type=basestring ) define( "session_timeout", default="5d", group='gateone', help=_("Amount of time that a session is allowed to idle before it is " "killed. Accepts <num>X where X could be one of s, m, h, or d for " "seconds, minutes, hours, and days. Set to '0' to disable the ability " "to resume sessions."), type=basestring ) define( "new_api_key", default=False, group='gateone', help=_("Generate a new API key that an external application can use to " "embed Gate One."), ) define( "auth", default="none", group='gateone', help=_("Authentication method to use. Valid options are: %s" % auths), type=basestring ) # This is to prevent replay attacks. Gate One only keeps a "working memory" # of API auth objects for this amount of time. So if the Gate One server is # restarted we don't have to write them to disk as anything older than this # setting will be invalid (no need to check if it has already been used). define( "api_timestamp_window", default="30s", # 30 seconds group='gateone', help=_( "How long before an API authentication object becomes invalid. "), type=basestring ) define( "sso_realm", default=None, group='gateone', help=_("Kerberos REALM (aka DOMAIN) to use when authenticating clients." " Only relevant if Kerberos authentication is enabled."), type=basestring ) define( "sso_service", default='HTTP', group='gateone', help=_("Kerberos service (aka application) to use. Defaults to HTTP. " "Only relevant if Kerberos authentication is enabled."), type=basestring ) define( "pam_realm", default=os.uname()[1], group='gateone', help=_("Basic auth REALM to display when authenticating clients. " "Default: hostname. " "Only relevant if PAM authentication is enabled."), # NOTE: This is only used to show the user a REALM at the basic auth # prompt and as the name in the GATEONE_DIR+'/users' directory type=basestring ) define( "pam_service", default='login', group='gateone', help=_("PAM service to use. Defaults to 'login'. " "Only relevant if PAM authentication is enabled."), type=basestring ) define( "embedded", default=False, group='gateone', help=_( "When embedding Gate One, this option is available to templates.") ) define( "locale", default=default_locale, group='gateone', help=_("The locale (e.g. pt_PT) Gate One should use for translations." " If not provided, will default to $LANG (which is '%s' in your " "current shell), or en_US if not set." % os.environ.get('LANG', 'not set').split('.')[0]), type=basestring ) define("js_init", default="", group='gateone', help=_("A JavaScript object (string) that will be used when running " "GateOne.init() inside index.html. " "Example: --js_init=\"{scheme: 'white'}\" would result in " "GateOne.init({scheme: 'white'})"), type=basestring ) define( "https_redirect", default=False, group='gateone', help=_("If enabled, a separate listener will be started on port 80 that" " redirects users to the configured port using HTTPS.") ) define( "url_prefix", default="/", group='gateone', help=_("An optional prefix to place before all Gate One URLs. e.g. " "'/gateone/'. Use this if Gate One will be running behind a " "reverse proxy where you want it to be located at some sub-" "URL path."), type=basestring ) define( "origins", default=default_origins, group='gateone', help=_("A semicolon-separated list of origins you wish to allow access " "to your Gate One server over the WebSocket. This value must " "contain the hostnames and FQDNs (e.g. foo;foo.bar;) users will" " use to connect to your Gate One server as well as the " "hostnames/FQDNs of any sites that will be embedding Gate One. " "Alternatively, '*' may be specified to allow access from " "anywhere."), type=basestring ) define( "pid_file", default=pid_default, group='gateone', help=_( "Define the path to the pid file. Default: /var/run/gateone.pid"), type=basestring ) define( "uid", default=str(os.getuid()), group='gateone', help=_( "Drop privileges and run Gate One as this user/uid."), type=basestring ) define( "gid", default=str(os.getgid()), group='gateone', help=_( "Drop privileges and run Gate One as this group/gid."), type=basestring ) define( "api_keys", default="", group='gateone', help=_("The 'key:secret,...' API key pairs you wish to use (only " "applies if using API authentication)"), type=basestring ) define( "combine_js", default="", group='gateone', help=_( "Combines all of Gate One's JavaScript files into one big file and " "saves it at the given path (e.g. ./gateone.py " "--combine_js=/tmp/gateone.js)"), type=basestring ) define( "combine_css", default="", group='gateone', help=_( "Combines all of Gate One's CSS Template files into one big file " "and saves it at the given path (e.g. ./gateone.py " "--combine_css=/tmp/gateone.css)."), type=basestring ) define( "combine_css_container", default="gateone", group='gateone', help=_( "Use this setting in conjunction with --combine_css if the <div> " "where Gate One lives is named something other than #gateone"), type=basestring )
def get_user_locale(self): language = self.get_cookie("user_language") return locale.get("zh_CN") if language == None else locale.get(language)
def __init__(self, code): self.locale = locale.get(code)
def get_user_locale(self): return locale.get('zh_CN')
def locale(self): if not self._locale: self._locale = locale.get('en_US') return self._locale
def __init__(self, loc_str, timezone): self._lo = locale.get(loc_str) self._tznum = timezone self._tz = timedelta(hours=timezone)
def define_options(installed=True): """ Calls `tornado.options.define` for all of Gate One's command-line options. If *installed* is ``False`` the defaults will be set under the assumption that the user is non-root and running Gate One out of a download/cloned directory. """ # NOTE: To test this function interactively you must import tornado.options # and call tornado.options.parse_config_file(*some_config_path*). After you # do that the options will wind up in tornado.options.options global user_locale # Default to using the shell's LANG variable as the locale try: default_locale = os.environ['LANG'].split('.')[0] except KeyError: # $LANG isn't set default_locale = "en_US" user_locale = locale.get(default_locale) # NOTE: The locale setting above is only for the --help messages. # Simplify the auth option help message auths = "none, api, google, ssl" from gateone.auth.authentication import PAMAuthHandler, KerberosAuthHandler if KerberosAuthHandler: auths += ", kerberos" if PAMAuthHandler: auths += ", pam" # Simplify the syslog_facility option help message facilities = list(FACILITIES.keys()) facilities.sort() # Figure out the default origins default_origins = [ 'localhost', '127.0.0.1', ] # Used both http and https above to demonstrate that both are acceptable try: additional_origins = socket.gethostbyname_ex(socket.gethostname()) except socket.gaierror: # Couldn't get any IPs from the hostname additional_origins = [] for host in additional_origins: if isinstance(host, str): default_origins.append('%s' % host) else: # It's a list for _host in host: default_origins.append('%s' % _host) default_origins = ";".join(default_origins) config_default = os.path.join(os.path.sep, "opt", "gateone", "server.conf") # NOTE: --settings_dir deprecates --config settings_base = os.path.join(os.path.sep, 'etc', 'gateone') settings_default = os.path.join(settings_base, 'conf.d') port_default = 443 log_default = os.path.join(os.path.sep, "var", "log", 'gateone', 'gateone.log') user_dir_default = os.path.join(os.path.sep, "var", "lib", "gateone", "users") pid_default = os.path.join(os.path.sep, "var", "run", 'gateone.pid') session_dir_default = os.path.join(tempfile.gettempdir(), 'gateone') cache_dir_default = os.path.join(tempfile.gettempdir(), 'gateone_cache') if os.getuid() != 0: # Not root? Use $HOME/.gateone/ for everything home = os.path.expanduser('~') user_dir_default = os.path.join(home, '.gateone') settings_default = os.path.join(user_dir_default, 'conf.d') port_default = 10443 log_default = os.path.join(user_dir_default, 'logs', 'gateone.log') pid_default = os.path.join(user_dir_default, 'gateone.pid') session_dir_default = os.path.join(user_dir_default, 'sessions') cache_dir_default = os.path.join(user_dir_default, 'cache') if not installed: # Running inside the download directory? Change various defaults to # work inside of this directory here = os.path.dirname(os.path.abspath(__file__)) settings_base = os.path.normpath(os.path.join(here, '..', '..')) settings_default = os.path.join(settings_base, 'conf.d') port_default = 10443 log_default = os.path.join(settings_base, 'logs', 'gateone.log') user_dir_default = os.path.join(settings_base, 'users') pid_default = os.path.join(settings_base, 'gateone.pid') session_dir_default = os.path.join(settings_base, 'sessions') cache_dir_default = os.path.join(settings_base, 'cache') options.log_file_prefix = log_default ssl_dir = os.path.join(settings_base, 'ssl') define( "version", type=bool, group='gateone', help=_("Display version information."), ) define( "config", default=config_default, group='gateone', help=_("DEPRECATED. Use --settings_dir."), type=basestring, ) define("settings_dir", default=settings_default, group='gateone', help=_("Path to the settings directory."), type=basestring) define("cache_dir", default=cache_dir_default, group='gateone', help=_( "Path where Gate One should store temporary global files (e.g. " "rendered templates, CSS, JS, etc)."), type=basestring) define("debug", default=False, group='gateone', help=_( "Enable debugging features such as auto-restarting when files " "are modified.")) define( "cookie_secret", # 45 chars is, "Good enough for me" (cookie joke =) default=None, group='gateone', help=_("Use the given 45-character string for cookie encryption."), type=basestring) define( "command", default=None, group='gateone', help=_( "DEPRECATED: Use the 'commands' option in the terminal settings."), type=basestring) define( "address", default="", group='gateone', help=_( "Run on the given address. Default is all addresses (IPv6 " "included). Multiple address can be specified using a semicolon" " as a separator (e.g. '127.0.0.1;::1;10.1.1.100')."), type=basestring) define("port", default=port_default, group='gateone', help=_("Run on the given port."), type=int) define("enable_unix_socket", default=False, group='gateone', help=_("Enable Unix socket support."), type=bool) define("unix_socket_path", default="/tmp/gateone.sock", group='gateone', help=_("Path to the Unix socket (if --enable_unix_socket=True)."), type=basestring) # Please only use this if Gate One is running behind something with SSL: define("disable_ssl", default=False, group='gateone', help=_("If enabled, Gate One will run without SSL (generally not a " "good idea).")) define( "certificate", default=os.path.join(ssl_dir, "certificate.pem"), group='gateone', help=_( "Path to the SSL certificate. Will be auto-generated if none is" " provided."), type=basestring) define("keyfile", default=os.path.join(ssl_dir, "keyfile.pem"), group='gateone', help=_("Path to the SSL keyfile. Will be auto-generated if none is" " provided."), type=basestring) define( "ca_certs", default=None, group='gateone', help=_( "Path to a file containing any number of concatenated CA " "certificates in PEM format. They will be used to authenticate " "clients if the 'ssl_auth' option is set to 'optional' or " "'required'."), type=basestring) define("ssl_auth", default='none', group='gateone', help=_( "Enable the use of client SSL (X.509) certificates as a " "secondary authentication factor (the configured 'auth' type " "will come after SSL auth). May be one of 'none', 'optional', " "or 'required'. NOTE: Only works if the 'ca_certs' option is " "configured."), type=basestring) define("user_dir", default=user_dir_default, group='gateone', help=_("Path to the location where user files will be stored."), type=basestring) define("user_logs_max_age", default="30d", group='gateone', help=_( "Maximum amount of length of time to keep any given user log " "before it is removed."), type=basestring) define( "session_dir", default=session_dir_default, group='gateone', help=_( "Path to the location where session information will be stored."), type=basestring) define("syslog_facility", default="daemon", group='gateone', help=_("Syslog facility to use when logging to syslog (if " "syslog_session_logging is enabled). Must be one of: %s." % ", ".join(facilities)), type=basestring) define( "session_timeout", default="5d", group='gateone', help= _("Amount of time that a session is allowed to idle before it is " "killed. Accepts <num>X where X could be one of s, m, h, or d for " "seconds, minutes, hours, and days. Set to '0' to disable the ability " "to resume sessions."), type=basestring) define( "new_api_key", default=False, group='gateone', help=_( "Generate a new API key that an external application can use to " "embed Gate One."), ) define("auth", default="none", group='gateone', help=_("Authentication method to use. Valid options are: %s" % auths), type=basestring) # This is to prevent replay attacks. Gate One only keeps a "working memory" # of API auth objects for this amount of time. So if the Gate One server is # restarted we don't have to write them to disk as anything older than this # setting will be invalid (no need to check if it has already been used). define( "api_timestamp_window", default="30s", # 30 seconds group='gateone', help=_( "How long before an API authentication object becomes invalid. "), type=basestring) define( "sso_realm", default=None, group='gateone', help=_( "Kerberos REALM (aka DOMAIN) to use when authenticating clients." " Only relevant if Kerberos authentication is enabled."), type=basestring) define("sso_service", default='HTTP', group='gateone', help=_( "Kerberos service (aka application) to use. Defaults to HTTP. " "Only relevant if Kerberos authentication is enabled."), type=basestring) define( "pam_realm", default=os.uname()[1], group='gateone', help=_("Basic auth REALM to display when authenticating clients. " "Default: hostname. " "Only relevant if PAM authentication is enabled."), # NOTE: This is only used to show the user a REALM at the basic auth # prompt and as the name in the GATEONE_DIR+'/users' directory type=basestring) define("pam_service", default='login', group='gateone', help=_("PAM service to use. Defaults to 'login'. " "Only relevant if PAM authentication is enabled."), type=basestring) define( "embedded", default=False, group='gateone', help=_( "When embedding Gate One, this option is available to templates.")) define( "locale", default=default_locale, group='gateone', help=_( "The locale (e.g. pt_PT) Gate One should use for translations." " If not provided, will default to $LANG (which is '%s' in your " "current shell), or en_US if not set." % os.environ.get('LANG', 'not set').split('.')[0]), type=basestring) define("js_init", default="", group='gateone', help=_( "A JavaScript object (string) that will be used when running " "GateOne.init() inside index.html. " "Example: --js_init=\"{scheme: 'white'}\" would result in " "GateOne.init({scheme: 'white'})"), type=basestring) define( "https_redirect", default=False, group='gateone', help=_( "If enabled, a separate listener will be started on port 80 that" " redirects users to the configured port using HTTPS.")) define("url_prefix", default="/", group='gateone', help=_( "An optional prefix to place before all Gate One URLs. e.g. " "'/gateone/'. Use this if Gate One will be running behind a " "reverse proxy where you want it to be located at some sub-" "URL path."), type=basestring) define( "origins", default=default_origins, group='gateone', help=_( "A semicolon-separated list of origins you wish to allow access " "to your Gate One server over the WebSocket. This value must " "contain the hostnames and FQDNs (e.g. foo;foo.bar;) users will" " use to connect to your Gate One server as well as the " "hostnames/FQDNs of any sites that will be embedding Gate One. " "Alternatively, '*' may be specified to allow access from " "anywhere."), type=basestring) define( "pid_file", default=pid_default, group='gateone', help=_( "Define the path to the pid file. Default: /var/run/gateone.pid"), type=basestring) define("uid", default=str(os.getuid()), group='gateone', help=_("Drop privileges and run Gate One as this user/uid."), type=basestring) define("gid", default=str(os.getgid()), group='gateone', help=_("Drop privileges and run Gate One as this group/gid."), type=basestring) define("api_keys", default="", group='gateone', help=_("The 'key:secret,...' API key pairs you wish to use (only " "applies if using API authentication)"), type=basestring) define( "combine_js", default="", group='gateone', help=_( "Combines all of Gate One's JavaScript files into one big file and " "saves it at the given path (e.g. ./gateone.py " "--combine_js=/tmp/gateone.js)"), type=basestring) define( "combine_css", default="", group='gateone', help=_( "Combines all of Gate One's CSS Template files into one big file " "and saves it at the given path (e.g. ./gateone.py " "--combine_css=/tmp/gateone.css)."), type=basestring) define( "combine_css_container", default="gateone", group='gateone', help=_( "Use this setting in conjunction with --combine_css if the <div> " "where Gate One lives is named something other than #gateone"), type=basestring)
def create_application(): formencode.api.set_stdtranslation(languages=["en_US"]) settings = dict( debug=options['debug'], autoescape=options.autoescape, cookie_secret=options.cookie_secret, xsrf_cookies=True, login_url=options.login_url, template_path=options.template_path, static_path=options.static_path, static_url_prefix=options.static_url_prefix, ) #: init application application = DojangApplication(**settings) application.register_app('app.account.handlers.app') application.register_app('app.people.handlers.app') application.register_app('app.node.handlers.app') application.register_app('app.topic.handlers.app') application.register_app('app.shot.handlers.app') application.register_app('app.group.handlers.app') application.register_app('app.coins.handlers.app') application.register_app('app.admin.channel.handlers.app') application.register_app('app.admin.people.handlers.app') application.register_app('app.admin.topic.handlers.app') application.register_app('app.admin.handlers.app') application.register_app('app.about.handlers.app') application.register_app('app.wepusher.handlers.app') application.register_api('app.wepusher.api.app', options.api_domain) application.register_api('app.wepusher.api.wepusher_app', options.wepusher_api_domain) application.register_app('app.ohshit.handlers.app') application.register_api('app.ohshit.api.app', options.api_domain) #http://www.xxx.com/api/v1/account/xxx application.register_api('app.account.api.app', options.api_domain) #http://api.xxx.com/v1/people/xxx application.register_api('app.people.api.app', options.api_domain) #http://api.xxx.com/v1/topic/xxx application.register_api('app.topic.api.app', options.api_domain) application.register_api('app.thread.api.app', options.api_domain) application.register_app('app.front.handlers.app') for key in ['sitename', 'site_url', 'sitefeed', 'version', 'ga', 'gcse']: application.register_context(key, options[key]) import datetime application.register_context('now', datetime.datetime.utcnow) from app.lib.util import xmldatetime,xmlday, localtime, timesince, linkto, seconds_since from app.lib.urls import topic_url, build_url, build_image_url from app.lib.filters import markup from dojang.escape import simple_escape, html_escape, br_escape from urllib import urlencode from tornado import locale default_locale = locale.get('zh-CN') application.register_filter('locale', default_locale) # application.register_filter('markdown', markdown) application.register_filter('markup', markup) # application.register_filter('normal_markdown', normal_markdown) application.register_filter('xmldatetime', xmldatetime) application.register_filter('xmlday', xmlday) application.register_filter('localtime', localtime) application.register_filter('timesince', timesince) application.register_filter('seconds_since', seconds_since) application.register_filter('topic_url', topic_url) application.register_filter('url_encode', urlencode) application.register_filter('url', build_url) application.register_filter('image_url', build_image_url) # application.register_filter('movie_filter_url', movie_filter_url) application.register_filter('linkto', linkto) application.register_filter('simple_escape', simple_escape) application.register_filter('br_escape', br_escape) application.register_filter('html_escape', html_escape) return application
# -*- coding: utf-8 -*- from tornado import locale #国际化 locale.load_translations("./protected/translations") locale.set_default_locale("zh_CN") _locale = locale.get() class AdminErrorMessage(object): error_message = { '001': _locale.translate('admin_userinfo_incomplete').encode( "utf-8"), #填写信息不完整 '002': _locale.translate('admin_user_not_exist').encode("utf-8"), #'该用户不存在' '003': _locale.translate('admin_password_no_correct').encode( "utf-8"), #'密码错误' '004': _locale.translate('admin_session_had_expired').encode( "utf-8"), #'您的会话已经过期' '005': _locale.translate('admin_delete_error').encode("utf-8"), #'删除失败' '006': _locale.translate('admin_add_error').encode("utf-8"), #'添加失败' '007': _locale.translate('admin_update_error').encode("utf-8"), #'修改失败' '008': _locale.translate('admin_same_error').encode("utf-8"), #'存在相同记录' } class ErrorMessage(object): error_message = { '001': _locale.translate('login_fail').encode("utf-8"), #登录失败
def get_user_locale(self): if "webtools_locale" in self.session: return locale.get(self.session["webtools_locale"]) return None
def ready(MainApp, port, addr=None, family=None, backlog=1048576, reuse_port=True, debug=False, mmfile=None, **kwargs): #import pymysql #pymysql.install_as_MySQLdb() global DEBUG import sys sys.argv.extend([ '--%s=%s' % (k, v) for k, v in { 'logging': 'debug' if DEBUG else 'error', 'log_rotate_mode': 'time', 'log_file_prefix': 'logs/server.%s.log' % port, 'log_file_num_backups': 30, 'log_rotate_interval': 1, 'log_file_max_size': 100 * 1000 * 1000, 'log_to_stderr': False }.items() ]) from tornado import options, locale, log import finup_model, handlers # options.parse_config_file("server.conf") options.define("port", default=finup_model.PORT, help="port to listen on") remain_args = options.parse_command_line() locale.get() settings = { 'gzip': True, 'static_url_prefix': "/yihao01-face-recognize/static/", 'template_path': os.path.join((os.path.dirname(__file__)), 'template'), 'static_path': os.path.join((os.path.dirname(__file__)), 'static'), 'websocket_ping_interval': 1, 'websocket_ping_timeout': 5, 'max_message_size': 16 * 1024 * 1024, 'cookie_secret': 'abaelhe.0easy.com', 'cookie_domain': '.0easy.com', 'token': True, 'debug': debug, 'autoreload': debug, } log.app_log.info( 'Listen:%s:%s\nConfigs:\n%s\nRunning.\n' % (addr, finup_model.PORTS, ''.join([ ' %s = %s\n' % (k, v) for k, v in reversed( sorted(options.options.items(), key=lambda i: i[0])) if k != 'help' ]))) web_handlers = [ (r'/finup', handlers.FinupHandler), (r'/sys', handlers.SysHandler), # (r'/sock', handlers.SockHandler), # (r'/yihao01-face-recognize/target', receiver.TargetHandler), ] sock_handlers = [] app = MainApp(handlers=web_handlers + sock_handlers, **settings) port = int(port) app.listen(port, addr=finup_model.ADDR, debug=debug, reuse_port=reuse_port, **kwargs)
============================ This module contains functions that deal with Gate One's options/settings """ import os, sys, io, re, socket, tempfile, logging from gateone import GATEONE_DIR from .log import FACILITIES from gateone.core.log import go_logger from tornado import locale from tornado.escape import json_decode from tornado.options import define, options, Error # Locale stuff (can't use .locale since .locale uses this module) # Default to using the environment's locale with en_US fallback temp_locale = locale.get(os.environ.get('LANG', 'en_US').split('.')[0]) _ = temp_locale.translate del temp_locale logger = go_logger(None) class SettingsError(Exception): """ Raised when we encounter an error parsing .conf files in the settings dir. """ pass class RUDict(dict): """ A dict that will recursively update keys and values in a safe manner so that sub-dicts will be merged without one clobbering the other.
def get_user_locale(self): return locale.get(self.cookie_data.get('locale', 'zh_CN'))
def locale(self): return locale.get(self.language)
def _get_translations(self): if self._handler.get_user_locale(): _locale = self._handler.get_user_locale() else: _locale = locale.get("en_US") return TornadoLocaleWrapper(_locale)
def define_current_locale(self, locale_code): self._current_locale = locale.get(locale_code)
def define_options(): """ Calls `tornado.options.define` for all of Gate One's command-line options. If *installed* is ``False`` the defaults will be set under the assumption that the user is non-root and running Gate One out of a download/cloned directory. """ # NOTE: To test this function interactively you must import tornado.options # and call tornado.options.parse_config_file(*some_config_path*). After you # do that the options will wind up in tornado.options.options # Simplify the auth option help message auths = "none, api, cas, google, ssl" #from applications.auth.authentication import PAMAuthHandler, KerberosAuthHandler #if KerberosAuthHandler: #auths += ", kerberos" #if PAMAuthHandler: #auths += ", pam" ## Simplify the syslog_facility option help message #facilities = list(FACILITIES.keys()) #facilities.sort() # Figure out the default origins default_origins = [ 'localhost', '127.0.0.1', ] # Used both http and https above to demonstrate that both are acceptable try: additional_origins = socket.gethostbyname_ex(socket.gethostname()) except socket.gaierror: # Couldn't get any IPs from the hostname additional_origins = [] for host in additional_origins: if isinstance(host, str): default_origins.append('%s' % host) else: # It's a list for _host in host: default_origins.append('%s' % _host) default_origins = ";".join(default_origins) settings_base = getsettings('BASE_DIR') settings_default = os.path.join(settings_base, 'conf.d') settings_dir = settings_default if not os.path.isdir(settings_dir): mkdir_p(settings_dir) port_default = 8000 log_default = os.path.join(settings_base, 'logs', 'gateone.log') user_dir_default = os.path.join(settings_base, 'users') pid_default = os.path.join(settings_base, 'pid', 'gateone.pid') session_dir_default = os.path.join(settings_base, 'sessions') cache_dir_default = os.path.join(settings_base, 'cache') ssl_dir = os.path.join(settings_base, 'ssl') debug = False cookie_secret = getsettings('SECRET_KEY') address = "" enable_unix_socket = False unix_socket_path = "/tmp/gateone.sock" unix_socket_mode = "0600" disable_ssl = False certificate = os.path.join(ssl_dir, "certificate.pem") keyfile = os.path.join(ssl_dir, "keyfile.pem") ca_certs = None ssl_auth = 'none' user_dir = user_dir_default uid = str(os.getuid()) gid = str(os.getgid()) if not os.path.exists(user_dir): mkdir_p(user_dir) os.chmod(user_dir, 0o770) #if uid == 0 and os.getuid() != 0: #if not check_write_permissions(uid, user_dir): #recursive_chown(user_dir, uid, gid) user_logs_max_age = "30d" session_dir = session_dir_default if not os.path.exists(session_dir): mkdir_p(session_dir) os.chmod(session_dir, 0o770) #if not check_write_permissions(uid, session_dir): #recursive_chown(session_dir, uid, gid) syslog_facility = "daemon" session_timeout = "5d" new_api_key = False auth = "none" api_timestamp_window ="30s" sso_realm = None sso_service = "HTTP" pam_realm = os.uname()[1] pam_service = "login" embedded = False js_init = "" https_redirect = False url_prefix = "/" origins = default_origins pid_file = pid_default api_keys = "" combine_js = "" combine_css = "" combine_css_container = "gateone" multiprocessing_workers = None configure = False login_url ='/auth' static_url_prefix = '/static/' log_rotate_mode = 'size' logging = 'info' static_url = os.path.join(settings_base, 'static') session_logging = True log_file_num_backups = 10 log_file_prefix = os.path.join(settings_base, 'log') if not os.path.exists(log_file_prefix): mkdir_p(log_file_prefix) os.chmod(log_file_prefix, 0o770) #if not check_write_permissions(uid, log_file_prefix): #recursive_chown(log_file_prefix, uid, gid) if not url_prefix.endswith('/'): url_prefix += '/' global TIMEOUT TIMEOUT = convert_to_timedelta(session_timeout) api_timestamp_window = convert_to_timedelta(api_timestamp_window) auth = none_fix(auth) # Check to make sure we have a certificate and keyfile and generate fresh # ones if not. if not disable_ssl: if not os.path.exists(keyfile): ssl_base = os.path.dirname(keyfile) if not os.path.exists(ssl_base): mkdir_p(ssl_base) gen_self_signed_ssl(path=ssl_base) if not os.path.exists(certificate): ssl_base = os.path.dirname(certificate) gen_self_signed_ssl(path=ssl_base) ssl_auth = ssl_auth.lower() log_file_max_size = 100000000 global _ global PLUGINS global APPLICATIONS cli_commands = {'gateone': {}} # CLI commands provided by plugins/apps settings = {} global user_locale # Default to using the shell's LANG variable as the locale try: default_locale = os.environ['LANG'].split('.')[0] except KeyError: # $LANG isn't set default_locale = "en_US" #from django.utils.translation import ugettext as _ #from django.utils.translation import ugettext_lazy as _ #from django.utils.translation import activate, get_language_info #from django.utils.translation import activate #from django.utils import translation #user_language = 'fr' #translation.activate(user_language) #activate('fr') #i = get_language_info('de') locales = default_locale user_locale = getsettings('LANGUAGE_CODE', 'en_US') # NOTE: The locale setting above is only for the --help messages. # Re-do the locale in case the user supplied something as --locale server_locale = locale.get(user_locale) _ = server_locale.translate # Also replaces our wrapper so no more .encode() # Set our global session timeout https_redirect = False syslog_session_logging = False sso_keytab = None configure = False settings.update({ u'dtach': True, 'version': None, u'locale': locales, u'address': address, u'pam_service': pam_service, u'syslog_facility': syslog_facility, 'cookie_secret': cookie_secret, u'enable_unix_socket': enable_unix_socket, u'port': port_default, u'uid': str(uid), u'url_prefix': url_prefix, u'user_dir': user_dir, 'settings_dir': settings_dir, u'unix_socket_mode': unix_socket_mode, u'multiprocessing_workers': multiprocessing_workers, u'certificate': certificate, u'log_rotate_interval': 1, u'log_to_stderr': None, u'log_rotate_when': u'midnight', u'gid': str(gid), u'pid_file': pid_file, 'command': None, 'gzip': True, u'pam_realm': pam_realm, 'login_url': login_url, 'configure': configure, u'sso_service': sso_service, 'cli_overrides': [], u'https_redirect': https_redirect, u'auth': auth, 'api_keys': api_keys, u'disable_ssl': disable_ssl, u'ca_certs': ca_certs, u'cache_dir': cache_dir_default, u'syslog_session_logging': syslog_session_logging, u'user_logs_max_age': user_logs_max_age, u'sso_keytab': sso_keytab, u'api_timestamp_window': api_timestamp_window, 'static_url_prefix': static_url_prefix, u'log_rotate_mode': log_rotate_mode, u'log_file_num_backups': log_file_num_backups, u'logging': logging, u'embedded': embedded, u'origins': default_origins, u'session_logging': session_logging, u'keyfile': keyfile, u'session_dir': session_dir, 'static_url': static_url, u'ssl_auth': ssl_auth, u'log_file_max_size': log_file_max_size, u'session_timeout': TIMEOUT, u'sso_realm': sso_realm, u'debug': debug, u'js_init': js_init, u'unix_socket_path': unix_socket_path, u'log_file_prefix': os.path.join(log_file_prefix,'django-gateone.log'), u'kill': False,#new variable u'use_client_cache': True }) return settings
def get_user_locale(self): local_code = self.get_secure_cookie('local_code') if not local_code: local_code = "zh_CN" self.set_secure_cookie('local_code', local_code) return locale.get(local_code)
============================ This module contains functions that deal with Gate One's options/settings """ import os, sys, io, re, socket, tempfile, logging from gateone import GATEONE_DIR from .log import FACILITIES from gateone.core.log import go_logger from tornado import locale from tornado.escape import json_decode from tornado.options import define, options, Error # Locale stuff (can't use .locale since .locale uses this module) # Default to using the environment's locale with en_US fallback temp_locale = locale.get(os.environ.get('LANG', 'en_US').split('.')[0]) _ = temp_locale.translate del temp_locale logger = go_logger(None) comments_re = re.compile( r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE) trailing_commas_re = re.compile( r'(,)\s*}(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)') class SettingsError(Exception): """ Raised when we encounter an error parsing .conf files in the settings dir. """
def get_user_locale(self): preferred_lang = self.get_cookie("lang", None) if preferred_lang not in locale.get_supported_locales(): return None return locale.get(preferred_lang)
def get_user_locale(self): return locale.get(self.get_argument('locale', 'en_US'))
def activate_locale(self, locale_name): """ Activate a specific locale for current user. """ self.session["webtools_locale"] = locale_name self._locale = locale.get(locale_name)
def get_user_locale(self): return locale.get(sickrage.app.config.gui_lang)