def show(): if authenticated(): userID = session["userID"] user = User.get(userID) return render_template("index.html", menu="home", login=True, user=user) return render_template("index.html", menu="home")
def process_unfollows(): print("Process unfollows") if auth.authenticated(): print("User is authenticated. Unfollows will be processed...") list_members = get_list_members(MNG_MAIN, auth.get_user_id()) print_list_stats(list_members) u = 0 following = 0 not_following_dict = {} unfollowed_dict = {} for m in list_members: u = u + 1 print("#### User %d ####" % u) user_dict = m.AsDict() m_id = user_dict["id"] m_screename = user_dict["screen_name"] # TODO: LookupFriendship() should be a bit more efficient friendship_data = auth.api.ShowFriendship(auth.get_user_id(),None,m_id,None) # Check friendship between the two users (the authenticated user and the one on the list) src_tar = friendship_data["relationship"] src = src_tar["source"] if src["followed_by"]: print("%s IS following!" % m_screename) following += 1 if not src["following"]: # Remove user from this list and pass it to the following list in the pipeline auth.api.DestroyListsMember(None,MNG_MAIN,None,auth.get_user_id(),m_id,None) auth.api.CreateListsMember(None,MNG_UNFOLLOWED,m_id,None,None,auth.get_user_id()) print("User %s deleted from %s list and added to %s" % (m_screename,MNG_MAIN,MNG_UNFOLLOWED)) unfollowed_dict[m_id] = m_screename else: print("%s IS NOT following!" % m_screename) not_following_dict[m_id] = m_screename # Unfriend user auth.api.DestroyFriendship(m_id,None) print("User %s unfriended" % m_screename) # Remove user from this list and pass it to the following list in the pipeline auth.api.DestroyListsMember(None,MNG_MAIN,None,auth.get_user_id(),m_id,None) auth.api.CreateListsMember(None,MNG_UNFOLLOWED_ME,m_id,None,None,auth.get_user_id()) print("User %s deleted from %s list and added to %s" % (m_screename,MNG_MAIN,MNG_UNFOLLOWED_ME)) print("Total users following: %s" % following) print("Total users NOT following (unfriended and moved): %s %s" % (len(not_following_dict), not_following_dict)) print("Total users unfollowed: %s %s" % (len(unfollowed_dict), unfollowed_dict)) else: print("Please, check authentication tokens")
def process_unfollowed_me(): print("Unfollowed stats") if auth.authenticated(): print("User is authenticated. Unfollowed stats will be listed...") list_members = get_list_members(MNG_UNFOLLOWED_ME, auth.get_user_id()) print_list_stats(list_members) else: print("Please, check authentication tokens")
def show(): if authenticated(): userID = session['userID'] user = User.get(userID) return render_template('index.html', menu="home", login=True, user=user) return render_template('index.html', menu="home")
def user_login(): if authenticated(): return redirect(session['last_url']) elif request.method == 'GET': return render_template('login.html', isConsultant = False) if request.method == 'POST': logging_user = validate_login(request.form['username'], request.form['password']) if logging_user is not None: session.permanent = True session['user'] = {'username':logging_user.name, 'uid':logging_user.id, 'roles':[role.name for role in logging_user.roles]} return redirect('/user/home') else: return 'login failed'
def register(): if authenticated() and (not has_role(['admin'])): return '请先注销当前登录' if request.method == 'GET': return render_template('register.html') else: registering_user = register_user(request.form['username'],request.form['password']) if registering_user is not None: if not 'user' in session: session.permanent = True session['user'] = {'username':registering_user.name, 'uid':registering_user.id, 'roles':[role.name for role in registering_user.roles]} return redirect('/user/home') elif has_role(['admin']): return redirect('/user/register') else: return redirect('/user/register')
def consultant_login(): if authenticated(): return redirect(session["last_url"]) if request.method == "GET": return render_template("login.html", isConsultant=True) if request.method == "POST": logging_user = validate_login(request.form["username"], request.form["password"]) if logging_user is not None: session.permanent = True session["user"] = { "username": logging_user.name, "uid": logging_user.id, "roles": [role.name for role in logging_user.roles], } if has_role(["consultant", "admin"]): return redirect("/consultant/home") else: return redirect("/user/home") else: abort(401)
def query_lists(): print("User lists stats") if auth.authenticated(): print("User is authenticated. User lists stats will be listed...") lists = auth.api.GetLists() i = 0 for l in lists: i = i + 1 list_dict = l.AsDict() print("##### List %d #####" % i) print("Name: %s (slug: %s)" % (list_dict["name"], list_dict["slug"])) if "description" in list_dict: print("Description: %s" % list_dict["description"]) else: print("Description: -") print("Member count: %s" % list_dict["member_count"]) else: print("Please, check authentication tokens")
def main(): try: shortflags = '-h' longflags = [ 'help', 'generate-access-token', 'consumer-key=', 'consumer-secret=', 'access-key=', 'access-secret=' ] opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags) except getopt.GetoptError: print_usage_and_exit() #print("Options: {opt}".format(opt=opts)) #print("Args: {args}".format(args=args)) consumer_keyflag = None consumer_secretflag = None access_keyflag = None access_secretflag = None generate_token = False for o, a in opts: if o in ("-h", "--help"): print_usage_and_exit() if o in ("--generate-access-token"): generate_token = True if o in ("--consumer-key"): consumer_keyflag = a if o in ("--consumer-secret"): consumer_secretflag = a if o in ("--access-key"): access_keyflag = a if o in ("--access-secret"): access_secretflag = a #print_tokens(consumer_keyflag,consumer_secretflag,access_keyflag,access_secretflag) consumer_key = consumer_keyflag or auth.GetConsumerKeyEnv( ) or auth.GetConsumerKeyHardcoded() consumer_secret = consumer_secretflag or auth.GetConsumerSecretEnv( ) or auth.GetConsumerSecretHardcoded() access_key = access_keyflag or auth.GetAccessKeyEnv( ) or auth.GetAccessKeyHardcoded() access_secret = access_secretflag or auth.GetAccessSecretEnv( ) or auth.GetAccessSecretHardcoded() #print_tokens(consumer_key,consumer_secret,access_key,access_secret) # if we want the program to generate the token for us, we try to generate them based # on the consumer tokens and override the access key values if generate_token: print("An access token will be generated") if not consumer_key or not consumer_secret: print_usage_and_exit() else: try: tmp_access_key, tmp_access_secret = get_access_token.get_access_token( consumer_key, consumer_secret) except ValueError as e: print( "Access token couldn't be generated. Please check the correctness of the provided consumer token: {0}" .format(e)) sys.exit(2) if not tmp_access_key and not tmp_access_secret: print( "Access token couldn't be generated. The given access keys (environment's or hardcoded) will be used instead..." ) else: # override the already read access keys access_key = tmp_access_key access_secret = tmp_access_secret else: print( "An access token won't be generated. The given access keys (environment's or hardcoded) will be used instead..." ) if not consumer_key or not consumer_secret or not access_key or not access_secret: print( "At least one of the tokens is missing. Please check and try again" ) print_usage_and_exit() auth.authenticate(consumer_key, consumer_secret, access_key, access_secret) if not auth.authenticated(): print( "Authentication failed, please check authentication tokens and try again" ) sys.exit(2) else: print("User correctly authenticated, starting program...\n") while True: menu.print_menu() m = user_input.read_selection() process(m)
def index(): if authenticated(): return redirect(url_for('dashboard')) else: return redirect(url_for('login'))
class ExampleApplication(GOApplication): """ A Gate One Application (`GOApplication`) that serves as an example of how to write a Gate One application. """ info = { 'name': "Example", # A user-friendly name for your app # A description of what your app does: 'description': "An example of how to write a Gate One Application.", 'hidden': HIDDEN } def __init__(self, ws): example_log.debug("ExampleApplication.__init__(%s)" % ws) # Having your app's policies handy is a good idea. However, you can't # get them until you've got a user to pass to applicable_policies(). # For this reason we'll place a `self.policy` placeholder here and # assign it after the user authenticates (successfully)... self.policy = {} # Gets set in authenticate() below # If you override __init__() (like we are here) don't forget to call # the parent __init__(): GOApplication.__init__(self, ws) def initialize(self): """ Called when the WebSocket is instantiated, sets up our WebSocket actions, security policies, and attaches all of our plugin hooks/events. """ example_log.debug("ExampleApplication.initialize()") # Register our security policy function in the 'security' dict self.ws.security.update({'example': example_policies}) # Register some WebSocket actions... # These can be called from the client like so: # GateOne.ws.send(JSON.stringify({'example:test_example': whatever})); self.ws.actions.update({ 'example:test_example': self.test_example, }) # Gate One provides a location where you can store information that you # want to be persistent across user sesions/connections and whatnot: if 'example' not in self.ws.persist: # If it doesn't belong in SESSIONS but you still need it to stick # around after the user disconnects put it here: self.ws.persist['example'] = {} # NOTE: If you don't care about your app having its own plugins you can # delete everything from here until the end of this function. # -- BEGIN PLUGIN CODE -- # If you want your app to support plugins here's how you do it: # First let's check if someone has explicitly given us a list of plugins # that should be enabled (so we can exclude the others): enabled_plugins = self.ws.prefs['*']['example'].get( 'enabled_plugins', []) # Now we'll use Gate One's utils.get_plugins() function to fetch a dict # containing all our Python, JavaScript, and CSS plugin files. This is # really only so we can log which plugins are enabled because the # process of importing Python plugins happens inside of init() and # JS/CSS plugin files get sent via the send_plugin_static_files() # function inside of authenticate(). self.plugins = get_plugins( # Get everything in example/plugins/ os.path.join(APPLICATION_PATH, 'plugins'), enabled_plugins) # Now let's separate the plugins by type (to save some typing) js_plugins = [] for js_path in self.plugins['js']: name = js_path.split(os.path.sep)[-2] name = os.path.splitext(name)[0] js_plugins.append(name) css_plugins = [] for css_path in css_plugins: name = css_path.split(os.path.sep)[-2] css_plugins.append(name) plugin_list = list(set(self.plugins['py'] + js_plugins + css_plugins)) plugin_list.sort() # So there's consistent ordering example_log.info( _("Active Example Plugins: %s" % ", ".join(plugin_list))) # Now let's attach plugin hooks. Plugin hooks can be whatever you like # and called from anywhere in your application. There's three types of # hooks you'll definitely want though: initialize(), 'WebSocket' and # 'Events' # # The initialize() hook just calls a given plugin's "initializ()" # function if it has one. The function will be passed `self` (the # current instance of your app). This allows plugins to take care of # any initialization stuff that needs to happen before anything else. # # 'WebSocket' hooks are what allow plugins to add their own WebSocket # actions such as, "myplugin:do_something" which is a very important # part of Gate One. # # 'Events' hooks allow plugins to attach functions to `OnOff` events # such as 'self.on("example:some_event", handle_some_event)' # # With those three kinds of hooks plugins can add or override pretty # much anything. # # NOTE: All GOApplication instances include the OnOff mixin class so # they can use self.on(), self.off, self.trigger(), and self.once() # # How do plugins assign these hooks? They simply include a 'hooks' dict # somewhere in the global scope of their .py files. Example: # hooks = { # 'WebSocket': {'myplugin:some_func': some_func} # 'Events': {'example:authenticate': auth_func} # } self.plugin_hooks = {} # We'll store our plugin hooks here imported = load_modules(self.plugins['py']) for plugin in imported: try: # Add the plugin's hooks dict to self.plugin_hooks: self.plugin_hooks.update({plugin.__name__: plugin.hooks}) # Now we'll call the plugin's initialize() function: if hasattr(plugin, 'initialize'): plugin.initialize(self) except AttributeError: pass # No hooks--probably just a supporting .py file. # Now we hook up the hooks: for plugin_name, hooks in self.plugin_hooks.items(): if 'WebSocket' in hooks: # Apply the plugin's WebSocket actions to ApplicationWebSocket for ws_command, func in hooks['WebSocket'].items(): self.ws.actions.update({ws_command: bind(func, self)}) # Attach the plugin's event hooks to their respective events: if 'Events' in hooks: for event, callback in hooks['Events'].items(): self.on(event, bind(callback, self)) # -- END PLUGIN CODE -- def open(self): """ This gets called at the end of :meth:`ApplicationWebSocket.open` when the WebSocket is opened. It just triggers the "example:open" event. .. note:: The authenticate() method is usually a better place to call stuff that needs to happen after the user loads the page. """ example_log.debug('ExampleApplication.open()') self.trigger("example:open") def authenticate(self): """ This gets called immediately after the user is authenticated successfully at the end of :meth:`ApplicationWebSocket.authenticate`. Sends all plugin JavaScript files to the client and triggers the 'example:authenticate' event. """ example_log.debug('ExampleApplication.authenticate()') # This is the log metadata that was mentioned near the top of this file. # This log_metadata will be JSON-encoded and included in all log # messages that use `self.example_log` which is super useful when # you need to parse logs at some later date and want to know the # circumstances surrounding any given message. self.log_metadata = { 'upn': self.current_user['upn'], 'ip_address': self.ws.request.remote_ip, # If your app uses the location feature make sure to include it: 'location': self.ws.location } self.example_log = go_logger("gateone.example", **self.log_metadata) # NOTE: To include even *more* metadata in a log message on a one-time # basis simply pass the metadata to the logger like so: # self.example_log("Some log message", metadata={'foo': 'bar'}) # That will ensure that {'foo': 'bar'} is included in the JSON portion # Assign our user-specific settings/policies for quick reference self.policy = applicable_policies('example', self.current_user, self.ws.prefs) # NOTE: The applicable_policies() function *is* memoized but the above # is still much faster. # Start by determining if the user can even use this app if 'allow' in self.policy: # This is the same check inside example_policies(). Why put it here # too? So we can skip sending the client JS/CSS that they won't be # able to use. if not self.policy['allow']: # User is not allowed to access this application. Don't # bother sending them any static files and whatnot... self.example_log.debug( _("User is not allowed to use the Example application. " "Skipping post-authentication functions.")) return # Render and send the client our example.css example_css = os.path.join(APPLICATION_PATH, 'templates', 'example.css') self.render_and_send_css(example_css, element_id="example.css") # NOTE: See the Gate One docs for gateone.py to see how # render_and_send_css() works. It auto-minifies and caches! # Send the client our application's static JavaScript files static_dir = os.path.join(APPLICATION_PATH, 'static') js_files = [] if os.path.isdir(static_dir): js_files = os.listdir(static_dir) # Everything in static/*.js js_files.sort() for fname in js_files: if fname.endswith('.js'): js_file_path = os.path.join(static_dir, fname) # This is notable: To ensure that all your JavaScript files # get loaded *after* example.js we add 'example.js' as a # dependency for all JS files we send to the client. if fname == 'example.js': # Adding CSS as a dependency to your app's JS is also a # good idea. You could also put 'theme.css' if you want to # ensure that the theme gets loaded before your JavaScript # init() function is called. self.send_js(js_file_path, requires=["example.css"]) else: # Send any other discovered JS files to the client with # example.js as the only dependency. self.send_js(js_file_path, requires='example.js') # If you're not using plugins you can disregard this: # The send_plugin_static_files() function will locate any JS/CSS files # in your plugins' respective static directories and send them to the # client. It is also smart enough to know which plugins are enabled # or disabled. self.ws.send_plugin_static_files(os.path.join(APPLICATION_PATH, 'plugins'), application="example", requires=["example.js"]) sess = SESSIONS[self.ws.session] # A shortcut to save some typing # Create a place to store app-specific stuff related to this session # (but not necessarily this 'location') if "example" not in sess: sess['example'] = {} # A mostly persistent place to store info # If you want to call a function whenever Gate One exits just add it # to SESSIONS[self.ws.session]["kill_session_callbacks"] like so: #if kill_session_func not in sess["kill_session_callbacks"]: #sess["kill_session_callbacks"].append(kill_session_func) # If you want to call a function whenever a user's session times out # just attach it to SESSIONS[self.ws.session]["timeout_callbacks"] # like so: #if timeout_session_func not in sess["timeout_callbacks"]: #sess["timeout_callbacks"].append(timeout_session_func) # NOTE: The user will often be authenticated before example.js is # loaded. In fact, the only time this won't be the case is when the # user is disconnected (e.g. server restart) and then reconnects. self.trigger("example:authenticate") def on_close(self): """ This method gets called when the WebSocket connection closes (disconnected). Triggers the `example:on_close` event. """ # This is a nice little check to prevent you from calling all sorts # of uninitialization/teardown stuff when you don't need to: if not hasattr(self.ws, 'location'): return # Connection closed before authentication completed # Here's where you'd deal with any uninitialization/teardown stuff self.trigger("example:on_close") @require(authenticated(), policies('example')) def test_example(self, settings): """ This is an example WebSocket action that sends a message to the client indicating that it was called successfully. Calls the `example:test_example` event when complete. """ self.ws.send_message( _("The test_example WebSocket action was called successfully!")) self.ws.send_message( _("Here's what was recieved: %s") % repr(settings)) self.trigger("example:test_example", settings)