def oauth_twitter_authenticate(uuid=None): """ This is the callback URL to which the user is redirected after successfully authenticating against Facebook. """ if uuid == None or len(uuid) is not 36: return app.abort(401) _session = current_session() _uuid, redirect = login_sequence_retrieve() if not uuid == _uuid: return app.abort(401) _twitter = twitter() resp = _twitter.authorized_response() if resp is None: return login_sequence_complete(False) if isinstance(resp, OAuthException): return app.abort(503) session['twitter_oauth_token'] = resp flash(_("Login successful"), 'success') return login_sequence_account_get_or_create('twitter', resp['user_id'], resp['screen_name'])
def oauth_facebook_authenticate(uuid=None): """ This is the callback URL to which the user is redirected after successfully authenticating against Facebook. """ if uuid == None or len(uuid) is not 36: return app.abort(401) _session = current_session() _uuid, redirect = login_sequence_retrieve() if not uuid == _uuid: return app.abort(401) _facebook = facebook() resp = _facebook.authorized_response() if resp is None: return login_sequence_complete(False) if isinstance(resp, OAuthException): return app.abort(503) session['facebook_oauth_token'] = (resp['access_token'], '') flash(_("Login successful"), 'success') me = _facebook.get('/me') return login_sequence_account_get_or_create('facebook', me.data['id'], me.data['name'])
def __init__(self): import commands commands.__init__() to_execute = [] arg_num = 0 for arg in sys.argv[1:]: arg_num += 1 if not arg.startswith('-') and len(sys.argv) >= arg_num: if commands.commands.has_key(sys.argv[arg_num].replace( '-', '_')): to_execute.append(sys.argv[arg_num].replace('-', '_')) if commands.commands.has_key( "%s_%s" % ('_'.join(to_execute), sys.argv[arg_num].replace('-', '_'))): to_execute.append(sys.argv[arg_num].replace('-', '_')) for cmd_component in to_execute: sys.argv.pop(sys.argv.index(cmd_component.replace('_', '-'))) # wrap sys.stdout in a locale-aware StreamWriter (#3983) sys.stdout = codecs.getwriter(locale.getpreferredencoding())( sys.stdout) try: commands.execute('_'.join(to_execute)) except KeyboardInterrupt, err: print >> sys.stderr, _("Interrupted") pass
def register(cmd_name, func, group=None, description=None, aliases=[]): if not group == None: command = "%s_%s" % (group, cmd_name) else: command = cmd_name if isinstance(aliases, basestring): aliases = [aliases] if commands.has_key(command): log.fatal(_("Command '%s' already registered") % (command)) sys.exit(1) if callable(func): if group == None: commands[cmd_name] = { 'cmd_name': cmd_name, 'function': func, 'description': description } else: commands[group][cmd_name] = { 'cmd_name': cmd_name, 'function': func, 'description': description } commands[command] = commands[group][cmd_name] commands[command]['group'] = group commands[command]['cmd_name'] = cmd_name for alias in aliases: commands[alias] = { 'cmd_name': cmd_name, 'function': func, 'description': _("Alias for %s") % (cmd_name.replace('_', '-')) }
def execute(cmd_name, *args, **kw): if cmd_name == "": execute("help") sys.exit(0) if not commands.has_key(cmd_name): log.error(_("No such command.")) sys.exit(1) if not commands[cmd_name].has_key('function') and \ not commands[cmd_name].has_key('group'): log.error(_("No such command.")) sys.exit(1) if commands[cmd_name].has_key('group'): group = commands[cmd_name]['group'] command_name = commands[cmd_name]['cmd_name'] try: exec("from %s.cmd_%s import cli_options as %s_%s_cli_options" % (group, command_name, group, command_name)) exec("%s_%s_cli_options()" % (group, command_name)) except ImportError, errmsg: import traceback log.error((traceback.format_exc()))
def login_complete(): """ A login sequence is completed. """ from piko.db import db from piko.db.model import Person _session = current_session() if _session.person_id is None: return app.abort(403) person = db.session.query(Person).filter_by( uuid=_session.person_id).first() if person is None: return app.abort(500, _("Invalid Person.")) task_id = _session.transactions[0].task_id if task_id is None: return app.abort(500, "Invalid Task.") task = check_password_hash.AsyncResult(task_id) if task is None: return app.abort(403, "Access Denied") if task.info is True: # We need not to. # session['person_id'] = person.uuid if _session.redirect: _redirect = redirect(_session.redirect) else: _redirect = redirect(url_for('piko.index')) login_sequence_complete(True) return _redirect else: login_sequence_complete(False) return app.abort(500)
def list_commands(*args, **kw): """ List commands """ __commands = {} for command in commands.keys(): if isinstance(command, tuple): command_group, command = command __commands[command_group] = { command: commands[(command_group, command)] } else: __commands[command] = commands[command] _commands = __commands.keys() _commands.sort() for _command in _commands: if __commands[_command].has_key('group'): continue if __commands[_command].has_key('function'): # This is a top-level command if not __commands[_command]['description'] == None: print "%-25s - %s" % (_command.replace( '_', '-'), __commands[_command]['description']) else: print "%-25s" % (_command.replace('_', '-')) for _command in _commands: if not __commands[_command].has_key('function'): # This is a nested command print "\n" + _("Command Group: %s") % (_command) + "\n" ___commands = __commands[_command].keys() ___commands.sort() for __command in ___commands: if not __commands[_command][__command]['description'] == None: print "%-4s%-21s - %s" % ('', __command.replace( '_', '-'), __commands[_command][__command]['description']) else: print "%-4s%-21s" % ('', __command.replace('_', '-'))
def logout(): """ Logout a user. .. TODO:: Doesn't seem to actually do too much. """ from piko.db import db _session = current_session() db.session.delete(_session) session.clear() db.session.commit() flash(_("You are now logged out.")) return redirect(url_for('piko.logout_ok'))
def description(): return _("Set an item in the piko configuration.")
def not_yet_implemented(*args, **kw): print _("Not yet implemented") sys.exit(1)
def description(): return _("Dump your effective piko configuration.")
def login_otp(): """ Continue a login sequence by requesting an OTP be entered in to a form. """ from piko.forms import LoginOTPForm from piko.db import db from piko.db.model import Person _session = current_session() if _session.person_id is None: return redirect(url_for('piko.login')) if _session.person_id == session.get('person_id', False): if _session.uuid == session.get('uuid'): return redirect(url_for('piko.login')) form = LoginOTPForm(request.form, uuid=_session.transactions[1].transaction_id) if request.method == 'GET': return app.render_template('login/otp.html', form=form) elif request.method == "POST": assert len(_session.transactions) > 1 transaction_id = _session.transactions[1].transaction_id uuid = request.form.get('uuid') if not uuid == transaction_id: app.logger.error("form's uuid is not session transaction id") return app.abort(500, "Invalid transaction UUID") if form.validate(): person = db.session.query(Person).get(_session.person_id) if person is None: app.logger.error("no person for _session.person_id: %r" % (_session.person_id)) return app.abort(500) else: app.logger.info("person ID %r" % (_session.person_id)) result = person.validate_token(form.otp.data) if result: app.logger.info("token validated") else: app.logger.error("token invalid") if not result: flash(_("Login failed"), 'danger') login_sequence_complete(False) return redirect(url_for('piko.login')) else: flash(_("Login successful"), 'success') task_id = _session.transactions[0].task_id if not task_id: app.logger.info("setting session['person_id'] to %r" % (person.id)) session['person_id'] = person.id app.logger.info("using session's redirect %r" % (_session.redirect)) _redirect = redirect(_session.redirect) _session.redirect = None login_sequence_complete(True) return _redirect task = check_password_hash.AsyncResult(task_id) task.wait() if task.info is True: session['person_id'] = person.id if _session.redirect: _redirect = redirect(_session.redirect) else: _redirect = redirect(url_for('piko.index')) login_sequence_complete(True) return _redirect else: login_sequence_complete(False) return app.abort(500) else: person = db.session.query(Person).get(_session.person_id) if person is None: return app.abort(500) login_sequence_complete(False) return app.render_template('login/otp.html', form=form) else: return app.abort(405)
def login_email(): """ Login with an email address and a password. #. Accepts GET and POST requests. #. Continues an existing login sequence. #. Verifies the user is not already logged in, or redirects to profile (with a flash). """ from piko.forms import LoginEmailForm _session = current_session() # Already logged in. if _session.person_id is not None: if _session.person_id == session.get('person_id', False): if _session.uuid == session.get('uuid'): flash(_("Already logged in."), 'danger') return redirect(url_for('piko.profile')) if request.method == 'GET': uuid, _redirect = login_sequence_start() form = LoginEmailForm(request.form, uuid=uuid) return app.render_template('login/email.html', form=form) elif request.method == 'POST': uuid, _redirect = login_sequence_retrieve() if not request.form.get('uuid') == uuid: return app.abort(403, _("Invalid submission.")) form = LoginEmailForm(request.form, uuid=uuid) if form.validate(): from piko.db import db from piko.db.model import Account account = db.session.query(Account).filter_by( _name=form.email_address.data, type_name='email').first() # No such account could be found. if account is None: flash(_("Login failed."), 'danger') return login_sequence_complete(False) login_sequence_associate_account(account.uuid) # This account is not a personal account. if account.person_id is None: flash(_("Login failed."), 'danger') return login_sequence_complete(False) # Associate the account we've just attempted to login # with. # # This does not set any validity. login_sequence_associate_person(account.person_id) # Associate a translaction uuid with the current state # of progress. transaction, uuid = login_sequence_continue() account.person.verify_password(form.password.data, transaction=transaction) if len(account.second_factors) > 0: return redirect(url_for('piko.login_otp')) elif len(account.person.second_factors) > 0: return redirect(url_for('piko.login_otp')) else: return redirect(url_for('piko.login_wait')) else: flash(_("Login failed"), 'danger') return redirect(url_for('piko.login')) return app.render_template('login/email.html', form=form) else: return app.abort(405) return redirect(url_for('piko.login'))
def description(): return _("Information about your account.")
def ask_question(question, default="", password=False, confirm=False): """ Ask a question on stderr. Since the answer to the question may actually be a password, cover that case with a getpass.getpass() prompt. Accepts a default value, but ignores defaults for password prompts. .. rubric:: Usage >>> piko.utils.ask_question( "What is the server?", default="localhost" ) """ if not empty(default) and conf.cli_keywords.answer_default: if not conf.cli_keywords.quiet: # pylint: disable=superfluous-parens print("%s [%s]: " % (question, default)) return default if password: if empty(default): answer = getpass.getpass("%s: " % (question)) else: answer = getpass.getpass("%s [%s]: " % (question, default)) else: if empty(default): answer = raw_input("%s: " % (question)) else: answer = raw_input("%s [%s]: " % (question, default)) # pylint: disable=too-many-nested-blocks if answer != "": if confirm: answer_confirm = None answer_confirmed = False while not answer_confirmed: if password: answer_confirm = getpass.getpass( _("Confirm %s: ") % (question)) else: answer_confirm = raw_input(_("Confirm %s: ") % (question)) if answer_confirm != answer: print >> sys.stderr, _("Incorrect confirmation. " + "Please try again.") if password: if empty(default): answer = getpass.getpass(_("%s: ") % (question)) else: answer = getpass.getpass( _("%s [%s]: ") % (question, default)) else: if empty(default): answer = raw_input(_("%s: ") % (question)) else: answer = raw_input( _("%s [%s]: ") % (question, default)) else: answer_confirmed = True if answer == "": return default else: return answer
def description(): return _("Register with your favorite piko.")
def description(): return _("Check whether the server believes you are you.")