コード例 #1
0
 def testGetAccessToken_NotLoggedIn(self):
     subprocess2.check_call_out.side_effect = [
         subprocess2.CalledProcessError(1, ['cmd'], 'cwd', 'stdout',
                                        'stderr')
     ]
     self.assertRaises(auth.LoginRequiredError,
                       auth.Authenticator().get_access_token)
コード例 #2
0
ファイル: client.py プロジェクト: Team-Codelab/airypi-rpi
def run(cmd_app_name=None, url=None):
    _ROOT = os.path.abspath(os.path.dirname(__file__))
    cert_path = os.path.join(_ROOT, 'websocket', 'cacert.pem')
    os.environ['REQUESTS_CA_BUNDLE'] = cert_path

    app_greenlet = None
    server_greenlet = None
    try:
        login = auth.Authenticator()
        login.login()

        app_name = get_app_name(login, cmd_app_name=cmd_app_name, url=url)

        while True:
            try:
                server_client, server_namespace = login.connect_to_server()
                app_client, app_namespace = login.connect_to_app(app_name,
                                                                 url=url)
            except Exception, e:
                print traceback.format_exc()
                print e
                continue
            break

        server_namespace.app_namespace = app_namespace
        app_namespace.server_namespace = server_namespace

        app_greenlet = gevent.spawn(wait_forever_app, app_client)

        server_namespace.app_greenlet = app_greenlet

        server_greenlet = gevent.spawn(wait_forever_server, server_client)

        while True:
            gevent.sleep(0.1)
コード例 #3
0
 def testHasCachedCredentials_LoggedIn(self):
     subprocess2.check_call_out.return_value = (json.dumps({
         'token':
         'token',
         'expiry':
         12345678
     }), '')
     self.assertTrue(auth.Authenticator().has_cached_credentials())
コード例 #4
0
def Start():
    #Init variables
    variables.init()

    #Create the window
    variables.window = gui.Window()

    #Get songs
    variables.songs = network.GetSongs()

    #Authenticate
    auth.Authenticator(StartGame)
コード例 #5
0
 def testGetAccesstoken_LoggedIn(self):
     expiry = calendar.timegm(VALID_EXPIRY.timetuple())
     subprocess2.check_call_out.return_value = (json.dumps({
         'token': 'token',
         'expiry': expiry
     }), '')
     self.assertEqual(auth.AccessToken('token', VALID_EXPIRY),
                      auth.Authenticator().get_access_token())
     subprocess2.check_call_out.assert_called_with([
         'luci-auth', 'token', '-scopes', auth.OAUTH_SCOPE_EMAIL,
         '-json-output', '-'
     ],
                                                   stdout=subprocess2.PIPE,
                                                   stderr=subprocess2.PIPE)
コード例 #6
0
def dispatch_request(path_info, args, req, env, database=None):
    import Wiki

    if not database:
        database = env.get_db_cnx()

    # Let the wiki module build a dictionary of all page names
    Wiki.populate_page_dict(database, env)

    authenticator = auth.Authenticator(database, req)
    if path_info == '/logout':
        authenticator.logout()
        referer = req.get_header('Referer')
        if referer and referer[0:len(req.base_url)] != req.base_url:
            # only redirect to referer if the latter is from the same instance
            referer = None
        try:
            req.redirect(referer or env.href.wiki())
        except RedirectException:
            pass
    elif req.remote_user and authenticator.authname == 'anonymous':
        auth_cookie = authenticator.login(req)
    if path_info == '/login':
        referer = req.get_header('Referer')
        if referer and referer[0:len(req.base_url)] != req.base_url:
            # only redirect to referer if the latter is from the same instance
            referer = None
        try:
            req.redirect(referer or env.href.wiki())
        except RedirectException:
            pass
    req.authname = authenticator.authname

    newsession = args.has_key('newsession') and args['newsession']
    req.session = Session.Session(env, req, newsession)

    add_args_to_hdf(args, req.hdf)
    try:
        pool = None
        # Load the selected module
        module = module_factory(args, env, database, req)
        pool = module.pool
        module.run()
    finally:
        # We do this even if the cgi will terminate directly after. A pool
        # destruction might trigger important clean-up functions.
        if pool:
            import svn.core
            svn.core.svn_pool_destroy(pool)
コード例 #7
0
def main():
  metrics = input()
  try:
    headers = {}
    if 'bot_metrics' in metrics:
      token = auth.Authenticator().get_access_token().token
      headers = {'Authorization': 'Bearer ' + token}
    urllib.request.urlopen(urllib.request.Request(
        url=metrics_utils.APP_URL + '/upload',
        data=metrics.encode('utf-8'),
        headers=headers))
  except (urllib.error.HTTPError, urllib.error.URLError):
    pass

  return 0
コード例 #8
0
    def testAuthorize(self):
        http = mock.Mock()
        http_request = http.request
        http_request.__name__ = '__name__'

        authenticator = auth.Authenticator()
        authenticator._access_token = auth.AccessToken('token', None)

        authorized = authenticator.authorize(http)
        authorized.request('https://example.com',
                           method='POST',
                           body='body',
                           headers={'header': 'value'})
        http_request.assert_called_once_with(
            'https://example.com', 'POST', 'body', {
                'header': 'value',
                'Authorization': 'Bearer token'
            }, mock.ANY, mock.ANY)
コード例 #9
0
    def get(self):

        f = urllib2.urlopen(
            'http://img1.cache.netease.com/cnews/2011/5/6/20110506083751ebe4c.jpg'
        )
        image = methods.addImage("11111", f.read(), "http://1111")

        config = auth.Authenticator.load_config("config/dropbox.ini")
        dba = auth.Authenticator(config)
        #access_token = dba.obtain_trusted_access_token(config['testing_user'], config['testing_password'])
        access_token = oauth.OAuthToken.from_string(
            "oauth_token_secret=f16we6l2pn4mkx5&oauth_token=299vslb2j8xg8ns")
        db_client = client.DropboxClient(config['server'],
                                         config['content_server'],
                                         config['port'], dba, access_token)
        root = config['root']

        image.name = "20110506083751ebe4c.jpg"

        resp = db_client.put_file(root, "/", image)
        print resp
コード例 #10
0
ファイル: interface.py プロジェクト: ulfaQ/JobFlow
def start(input_list):

    global per_man
    global RUNNING_LIST

    RUNNING_LIST = input_list

    try:
        with open("permissions.txt", "rb") as f:
            per_man = pickle.load(f,
                                  fix_imports=False,
                                  encoding="ASCII",
                                  errors="strict")

    except FileNotFoundError:

        authenticator = auth.Authenticator()
        authorizor = auth.Authorizor(authenticator)
        per_man = PermissionManager(authenticator, authorizor)

        per_man.authenticator.add_user("alfa", "alllfa")
        per_man.authorizor.add_permission("use")
        per_man.authorizor.add_permission("admin")
        per_man.authorizor.permit_user("use", "alfa")
        per_man.authorizor.permit_user("admin", "alfa")

        per_man.write_perm_file()

    # Pistetään ohjelma pyörimään

    try:
        login_or_view = tools.get_valid_input("\n   (l)ogin or (v)iew?",
                                              ("l", "v"))
        if login_or_view == "l":
            per_man.login(RUNNING_LIST)
        elif login_or_view == "v":
            interface(RUNNING_LIST)

    except ActionCancelledError:
        start(RUNNING_LIST)
コード例 #11
0
 def __init__(self):
   self._authenticator = auth.Authenticator(
       ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
コード例 #12
0
            operation = input(
                'Choose an operation: login, check building, add classroom, add user, add permition\n'
            )
            if operation in type_operation:
                try:
                    eval('self.{}()'.format('_'.join(operation.split())))
                except auth.NotLoggedInError:
                    print('Sorry:( You\'re not logged in')
                except auth.UsernameAlreadyExists:
                    print('This username already exists.')
                except auth.PasswordTooShort:
                    print('Short password => short....... memory?')
                except (auth.InvalidUsername):
                    print('Wrong username bro')
                except (auth.InvalidPassword):
                    print('Is it just me or your password is wrong?')
                except auth.NotPermittedError:
                    print('You have no power here!')
                except auth.PermissionError:
                    print('What if I told you there is no such permission')
            elif operation.lower() == 'exit':
                break
            else:
                print('Wrong operation. Enter again.')


authenticator = auth.Authenticator()
authorizor = auth.Authorizor(authenticator)
checker = BuildingChecker(authorizor)
checker.auth_system()
コード例 #13
0
 def monorail_get_auth_http(self):
     # Manually use a long timeout (10m); for some users who have a
     # long history on the issue tracker, whatever the default timeout
     # is is reached.
     return auth.Authenticator().authorize(httplib2.Http(timeout=600))
コード例 #14
0
 def testGetAccessToken_CachedToken(self):
     authenticator = auth.Authenticator()
     authenticator._access_token = auth.AccessToken('token', None)
     self.assertEqual(auth.AccessToken('token', None),
                      authenticator.get_access_token())
     subprocess2.check_call_out.assert_not_called()
コード例 #15
0
 def testHasCachedCredentials_NotLoggedIn(self):
     subprocess2.check_call_out.side_effect = [
         subprocess2.CalledProcessError(1, ['cmd'], 'cwd', 'stdout',
                                        'stderr')
     ]
     self.assertFalse(auth.Authenticator().has_cached_credentials())