Exemple #1
0
    def __init__(self, tokenfile_path):
        self.tokenfile_path = tokenfile_path

        self.auth_mgr = AuthenticationManager()
        self.two_factor_auth = None

        # 2FA cache
        self.index = None
        self.proof = None
        self.otc = None

        self.loop = None
        self.log = LogListBox(self)

        self.view_stack = []

        try:
            self.auth_mgr.load(self.tokenfile_path)
        except Exception as e:
            logging.debug('Tokens failed to load from file, Error: {}'.format(e))

        '''
        self.need_refresh = self.auth_mgr.refresh_token and \
            self.auth_mgr.refresh_token.is_valid and \
            self.auth_mgr.refresh_token.date_valid < (datetime.now(tzutc()) + timedelta(days=7))
        '''
        self.need_full_auth = not self.auth_mgr.refresh_token or not self.auth_mgr.refresh_token.is_valid
Exemple #2
0
async def test():
    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(session, args.client_id,
                                         args.client_secret, "")

        with open(args.tokens, mode="r") as f:
            tokens = f.read()
        auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        try:
            auth_mgr.refresh_tokens()
        except ClientResponseError:
            print("Could not refresh tokens")
            sys.exit(-1)

        with open(args.tokens, mode="w") as f:
            f.write(auth_mgr.oauth.json())

        xbl_client = XboxLiveClient(auth_mgr)

        # Some example API calls

        # Get friendslist
        friendslist = await xbl_client.people.get_friends_own()

        # Get presence status (by list of XUID)
        presence = await xbl_client.presence.get_presence_batch(
            ["12344567687845", "453486346235151"])

        # Get messages
        messages = await xbl_client.message.get_inbox()

        # Get profile by GT
        profile = await xbl_client.profile.get_profile_by_gamertag(
            "SomeGamertag")
Exemple #3
0
def test_extract_js_node(windows_live_authenticate_response):
    auth_manager = AuthenticationManager()
    js_node = auth_manager.extract_js_object(windows_live_authenticate_response, 'ServerData')

    assert js_node is not None
    assert js_node['sFTTag'] == "<input name=\"PPFT\" value=\"normally_base64_encoded_string_here+\"/>"
    assert js_node['urlPost'] == "https://login.live.com/ppsecure/post.srf?response_type=token"
Exemple #4
0
    async def on_startup(self):
        await Tortoise.init(db_url=os.environ.get("DB_URL"),
                            modules={"models": ["common.models"]})
        self.redis = aioredis.from_url(os.environ.get("REDIS_URL"),
                                       decode_responses=True)

        self.session = aiohttp.ClientSession()
        auth_mgr = AuthenticationManager(
            self.session,
            os.environ["XBOX_CLIENT_ID"],
            os.environ["XBOX_CLIENT_SECRET"],
            "",
        )
        auth_mgr.oauth = OAuth2TokenResponse.parse_file(
            os.environ["XAPI_TOKENS_LOCATION"])
        await auth_mgr.refresh_tokens()
        xbl_client = XboxLiveClient(auth_mgr)
        self.profile = ProfileProvider(xbl_client)
        self.club = ClubProvider(xbl_client)

        self.realms = RealmsAPI(aiohttp.ClientSession())

        headers = {
            "X-Authorization": os.environ["OPENXBL_KEY"],
            "Accept": "application/json",
            "Accept-Language": "en-US",
        }
        self.openxbl_session = aiohttp.ClientSession(headers=headers)
async def auth_mgr(event_loop):
    mgr = AuthenticationManager(
        ClientSession(loop=event_loop), "abc", "123", "http://localhost"
    )
    mgr.oauth = OAuth2TokenResponse.parse_raw(get_response("auth_oauth2_token"))
    mgr.user_token = XAUResponse.parse_raw(get_response("auth_user_token"))
    mgr.xsts_token = XSTSResponse.parse_raw(get_response("auth_xsts_token"))
    return mgr
async def auth_mgr(event_loop):
    session = ClientSession(loop=event_loop)
    mgr = AuthenticationManager(session, "abc", "123", "http://localhost")
    mgr.oauth = OAuth2TokenResponse.parse_raw(get_response("auth_oauth2_token"))
    mgr.user_token = XAUResponse.parse_raw(get_response("auth_user_token"))
    mgr.xsts_token = XSTSResponse.parse_raw(get_response("auth_xsts_token"))
    yield mgr
    await session.close()
async def async_main():
    parser = argparse.ArgumentParser(description="Change your gamertag")
    parser.add_argument(
        "--tokens",
        "-t",
        default=TOKENS_FILE,
        help=f"Token filepath. Default: '{TOKENS_FILE}'",
    )
    parser.add_argument(
        "--client-id",
        "-cid",
        default=os.environ.get("CLIENT_ID", CLIENT_ID),
        help="OAuth2 Client ID",
    )
    parser.add_argument(
        "--client-secret",
        "-cs",
        default=os.environ.get("CLIENT_SECRET", CLIENT_SECRET),
        help="OAuth2 Client Secret",
    )

    args = parser.parse_args()

    if not os.path.exists(args.tokens):
        print("No token file found, run xbox-authenticate")
        sys.exit(-1)

    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(
            session, args.client_id, args.client_secret, ""
        )

        with open(args.tokens, mode="r") as f:
            tokens = f.read()
        auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        try:
            await auth_mgr.refresh_tokens()
        except ClientResponseError:
            print("Could not refresh tokens")
            sys.exit(-1)

        with open(args.tokens, mode="w") as f:
            f.write(auth_mgr.oauth.json())

        xbl_client = XboxLiveClient(auth_mgr)

        try:
            resp = await xbl_client.people.get_friends_own()
        except ClientResponseError:
            print("Invalid HTTP response")
            sys.exit(-1)

        pprint(resp.dict())
def main():
    parser = argparse.ArgumentParser(
        description="Authenticate with xbox live, manual webbrowser way")
    parser.add_argument('url',
                        nargs='?',
                        default=None,
                        help="Redirect URL of successful authentication")
    parser.add_argument(
        '--tokens',
        '-t',
        default=TOKENS_FILE,
        help=
        "Token filepath, file gets created if nonexistent and auth is successful."
        " Default: {}".format(TOKENS_FILE))

    args = parser.parse_args()

    if not args.url:
        print(
            'Visit following URL in your webbrowser and authenticate yourself, then restart'
            ' this script with \'<redirect url>\' argument\n\n'
            '{}'.format(AuthenticationManager.generate_authorization_url()))
        sys.exit(0)

    url_begin = 'https://login.live.com/oauth20_desktop.srf?'
    if not args.url.startswith(url_begin):
        print('Wrong redirect url, expected url like: \'{}...\''.format(
            url_begin))
        sys.exit(1)

    try:
        print('Extracting tokens from URL')
        auth_mgr = AuthenticationManager.from_redirect_url(args.url)
    except Exception as e:
        print(
            'Failed to get tokens from supplied redirect URL, err: {}'.format(
                e))
        sys.exit(2)

    try:
        print('Authenticating with Xbox Live')
        auth_mgr.authenticate(do_refresh=False)
    except AuthenticationException as e:
        print('Authentication failed! err: {}'.format(e))
        sys.exit(3)

    auth_mgr.dump(args.tokens)
    print('Success, tokens are stored at \'{}\''.format(args.tokens))
Exemple #9
0
def authentication_oauth_post():
    is_webview = request.form.get('webview')
    app.reset_authentication()
    redirect_uri = request.form.get('redirect_uri')
    if not redirect_uri:
        return app.error('Please provide redirect_url', HTTPStatus.BAD_REQUEST)

    try:
        access, refresh = AuthenticationManager.parse_redirect_url(redirect_uri)
        app.authentication_mgr.access_token = access
        app.authentication_mgr.refresh_token = refresh
        app.authentication_mgr.authenticate(do_refresh=False)
        app.authentication_mgr.dump(app.token_file)
    except Exception as e:
        if is_webview:
            return render_template('auth_result.html',
                                   title='Login fail',
                                   result='Login failed',
                                   message='Error message: {0}'.format(str(e)),
                                   link_path='/auth/login',
                                   link_title='Try again')
        else:
            return app.error('Login failed, error: {0}'.format(str(e)))

    if is_webview:
        return render_template('auth_result.html',
                               title='Login success',
                               result='Login succeeded',
                               message='Welcome {}!'.format(app.logged_in_gamertag),
                               link_path='/auth/logout',
                               link_title='Logout')
    else:
        return app.success(message='Login success', gamertag=app.logged_in_gamertag)
Exemple #10
0
    async def xuid_from_gamertag(self, ctx, *, gamertag):
        if gamertag in self.bot.gamertags.values():
            xuid = next(e for e in self.bot.gamertags.keys()
                        if self.bot.gamertags[e] == gamertag)
            await ctx.send(f"XUID of `{gamertag}`: `{xuid}`")
        else:
            async with AuthenticationManager(
                    os.environ.get("XBOX_EMAIL"),
                    os.environ.get("XBOX_PASSWORD")) as auth_mgr:
                async with XboxLiveClient(auth_mgr.userinfo.userhash,
                                          auth_mgr.xsts_token.jwt,
                                          auth_mgr.userinfo.xuid) as xb_client:
                    profile = await xb_client.profile.get_profile_by_gamertag(
                        gamertag)

                    try:
                        resp_json = await profile.json()
                    except aiohttp.ContentTypeError:
                        await ctx.send(
                            f"ERROR: Unable to find XUID from gamertag `{gamertag}`! Make sure you have entered it in correctly."
                        )
                        return

            if "code" in resp_json.keys():
                await ctx.send(
                    f"ERROR: Unable to find XUID from gamertag `{gamertag}`! Make sure you have entered it in correctly."
                )
            else:
                xuid = resp_json["profileUsers"][0]["id"]
                self.bot.gamertags[str(xuid)] = gamertag
                await ctx.send(f"XUID of `{gamertag}`: `{xuid}`")
def test_parsing_redirect_url_success(redirect_url):
    access, refresh = AuthenticationManager().parse_redirect_url(redirect_url)

    assert access.is_valid
    assert refresh.is_valid
    assert len(refresh.jwt) == 12
    assert len(access.jwt) == 11
Exemple #12
0
 def onConnectBtn(self, e):
     e.EventObject.Label = "Connecting..."
     auth_mgr = AuthenticationManager.from_file(TOKENS_FILE)
     auth_mgr.authenticate()
     auth_mgr.dump(TOKENS_FILE)
     userhash = auth_mgr.userinfo.userhash
     token = auth_mgr.xsts_token.jwt
     # TODO: make a drop-down list of discovered xboxes
     if self.worker is None:
         self.discover(self.xbox_ip_address.GetValue())
         if len(self.discovered):
             c = self.discovered[0]
             self.worker = XboxThread(
                 self.GetStaticBox(),
                 c.address,
                 c.name,
                 c.uuid,
                 c.liveid,
                 c.protocol.crypto,
                 userhash,
                 token
             )
         else:
             print("Discover a console first")
     else:  # Kill worker if it's alive
         self.worker.abort()
         self.worker = None
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xbox One platform"""
    from xbox.webapi.authentication.manager import AuthenticationManager
    from xbox.sg.enum import ConnectionState
    from xbox.sg.console import Console
    hass.loop.set_debug(True)
    ip_address = config.get(CONF_IP_ADDRESS)
    live_id = config.get(CONF_LIVE_ID)
    name = config.get(CONF_NAME)
    tokens_file_name = hass.config.path(config.get(CONF_TOKEN_FILE))
    _LOGGER.debug('Trying to authenticate')
    try:
        auth_mgr = AuthenticationManager.from_file(tokens_file_name)
        auth_mgr.authenticate(do_refresh=False)
        auth_mgr.dump(tokens_file_name)
    except Exception as e:
        _LOGGER.error(e)

    _LOGGER.debug('Authenticated, starting discovery.')
    consoles = Console.discover(timeout=1, addr=ip_address)

    if not consoles:
        _LOGGER.debug('No consoles found, could be turned off')
        async_add_devices([XboxOne(auth_mgr, live_id, ip_address, name)])
    else:
        async_add_devices([
            XboxOne(auth_mgr, live_id, ip_address, name, console)
            for console in consoles if console.liveid == live_id
        ])
Exemple #14
0
 def on_connect_request(req: ConnectionRequest):
     auth_mgr = AuthenticationManager.from_file(TOKENS_FILE)
     auth_mgr.dump(TOKENS_FILE)
     userhash = auth_mgr.userinfo.userhash
     token = auth_mgr.xsts_token.jwt
     for c in Console.discovered():
         if str(c.uuid) == str(req.console_dict['uuid']):
             self._console = c
     if self._console is None:
         self.outq.put(
             XboxEvent(EVT_XBOX_DISCONNECT_ID, "Failed to connect"))
         return
     self._console.add_manager(TextManager)
     self._console.text.on_systemtext_input += on_text
     self._console.protocol.on_timeout += lambda: self._timedout.set()
     try:
         status = self._console.connect(userhash, token)
     except OSError as e:
         self.outq.put(
             XboxEvent(EVT_XBOX_DISCONNECT_ID,
                       f"Failed to connect {e}"))
         return
     self._console.wait(1)
     self.outq.put(XboxEvent(EVT_XBOX_CONNECT_ID,
                             self._console.address))
Exemple #15
0
    async def gamertag_from_xuid(self, ctx, xuid: int):
        if str(xuid) in self.bot.gamertags.keys():
            await ctx.send(
                f"Gamertag for `{xuid}`: {self.bot.gamertags[str(xuid)]}")
        else:
            async with AuthenticationManager(
                    os.environ.get("XBOX_EMAIL"),
                    os.environ.get("XBOX_PASSWORD")) as auth_mgr:
                async with XboxLiveClient(auth_mgr.userinfo.userhash,
                                          auth_mgr.xsts_token.jwt,
                                          auth_mgr.userinfo.xuid) as xb_client:
                    profile = await xb_client.profile.get_profile_by_xuid(xuid)

                    try:
                        resp_json = await profile.json()
                    except aiohttp.ContentTypeError:
                        await ctx.send(
                            f"ERROR: Unable to find gamertag from XUID `{xuid}`! Make sure you have entered it in correctly."
                        )
                        return

            if "code" in resp_json.keys():
                await ctx.send(
                    f"ERROR: Unable to find gamertag from XUID `{xuid}`! Make sure you have entered it in correctly."
                )
            else:
                settings = {}
                for setting in resp_json["profileUsers"][0]["settings"]:
                    settings[setting["id"]] = setting["value"]

                self.bot.gamertags[str(xuid)] = settings["Gamertag"]
                await ctx.send(f"Gamertag for `{xuid}`: {settings['Gamertag']}"
                               )
def main():
    parser = argparse.ArgumentParser(description="Change your gamertag")
    parser.add_argument(
        '--tokens',
        '-t',
        default=TOKENS_FILE,
        help="Token filepath. Default: \'{}\'".format(TOKENS_FILE))
    parser.add_argument('gamertag', help="Desired Gamertag")

    args = parser.parse_args()

    if len(args.gamertag) > 15:
        print('Desired gamertag exceedes limit of 15 chars')
        sys.exit(-1)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
    except FileNotFoundError as e:

        print('Failed to load tokens from \'{}\'.\n'
              'ERROR: {}'.format(e.filename, e.strerror))
        sys.exit(-1)

    try:
        auth_mgr.authenticate(do_refresh=True)
    except AuthenticationException as e:
        print('Authentication failed! Err: %s' % e)
        sys.exit(-1)

    xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash,
                                auth_mgr.xsts_token.jwt,
                                auth_mgr.userinfo.xuid)

    print(':: Trying to get recent clips for xuid \'%i\'...' % xbl_client.xuid)
    test_gameclips_recent_own(xbl_client)

    # print('Claiming gamertag...')
    # resp = xbl_client.account.claim_gamertag(xbl_client.xuid, args.gamertag)
    # if resp.status_code == 409:
    #     print('Claiming gamertag failed - Desired gamertag is unavailable')
    #     sys.exit(-1)
    # elif resp.status_code != 200:
    #     print('Invalid HTTP response from claim: %i' % resp.status_code)
    #     print('Headers: %s' % resp.headers)
    #     print('Response: %s' % resp.content)
    #     sys.exit(-1)
    #
    # print('Changing gamertag...')
    # resp = xbl_client.account.change_gamertag(xbl_client.xuid, args.gamertag)
    # if resp.status_code == 1020:
    #     print('Changing gamertag failed - You are out of free changes')
    #     sys.exit(-1)
    # elif resp.status_code != 200:
    #     print('Invalid HTTP response from change: %i' % resp.status_code)
    #     print('Headers: %s' % resp.headers)
    #     print('Response: %s' % resp.content)
    #     sys.exit(-1)
    #
    print('Clips successfully fetched' % args.gamertag)
Exemple #17
0
    def __init__(self, email, password):
        self.auth_mgr = AuthenticationManager()

        # set data for auth manager
        self.auth_mgr.email_address = email
        self.auth_mgr.password = password

        # authentication
        self.auth_mgr.authenticate(do_refresh=True)

        # set the new info to a xbl client
        self.xbl_client = XboxLiveClient(self.auth_mgr.userinfo.userhash,
                                         self.auth_mgr.xsts_token.jwt,
                                         self.auth_mgr.userinfo.xuid)
        # not currently used but could be useful later
        self.profile_provider = ProfileProvider(self.xbl_client)
        self.people_provider = PeopleProvider(self.xbl_client)
    def __init__(self, name):
        super(SmartGlassFlaskApp, self).__init__(name)

        self.console_cache = {}
        self.title_cache = {}
        self.authentication_mgr = AuthenticationManager()
        self.token_file = None
        self._xbl_client = None
def main():
    parser = argparse.ArgumentParser(description="Basic smartglass client")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")

    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt
    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        console = discovered[0]
        console.on_timeout += on_timeout
        console.add_manager(InputManager)
        state = console.connect(userhash, token)
        if state != ConnectionState.Connected:
            print("Connection failed")
            sys.exit(1)
        console.wait(1)

        getch = get_getch_func()
        while True:
            ch = getch()
            print(ch)
            if ord(ch) == 3:  # CTRL-C
                sys.exit(1)

            elif ch not in input_map:
                continue

            button = input_map[ch]
            console.gamepad_input(button)
            console.wait(0.1)
            console.gamepad_input(GamePadButton.Clear)

        signal.signal(signal.SIGINT, lambda *args: console.protocol.stop())
        console.protocol.serve_forever()
    else:
        print("No consoles discovered")
        sys.exit(1)
Exemple #20
0
    def check_status(cls):
        auth_mgr = AuthenticationManager.from_file(TOKEN_FILE)
        try:
            auth_mgr.authenticate(do_refresh=True)
        except AuthenticationException:
            cls.generate_token()

        xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash,
                                    auth_mgr.xsts_token.jwt,
                                    auth_mgr.userinfo.xuid)
        friendslist = xbl_client.people.get_friends_own().json()
        people = [o["xuid"] for o in friendslist["people"]]

        profiles_data = xbl_client.profile.get_profiles(people).json()
        profiles = profiles_data.get("profileUsers", [])
        if not profiles:
            print("Profile Users not found!!!")

        status = {}
        for profile in profiles:
            profile['presence'] = xbl_client.presence.get_presence(
                profile['id'], presence_level=PresenceLevel.ALL).json()
            print(profile['presence'])

            xf, created = XboxFriends.objects.get_or_create(xuid=profile["id"])
            changed = created

            xf.gamertag = cls._get_settings(profile["settings"], "Gamertag")
            xf.realname = cls._get_settings(profile["settings"], "RealName")
            xf.gamedisplayname = cls._get_settings(profile["settings"],
                                                   "GameDisplayName")

            new_state = profile["presence"]["state"]
            #new_state = "Online"
            if new_state != xf.state:
                changed = True
            xf.state = new_state

            if "lastSeen" in profile["presence"]:
                xf.lastseen_titlename = profile["presence"]["lastSeen"][
                    "titleName"]
                xf.lastseen_timestamp = datetime.datetime.strptime(
                    profile["presence"]["lastSeen"]["timestamp"].split(".")[0],
                    '%Y-%m-%dT%H:%M:%S')
            else:
                xf.lastseen_timestamp = timezone.now()

            xf.save()

            print("{} is {}".format(xf.gamertag, xf.state))
            status[xf] = {
                'state': xf.state,
                'changed': changed,
                'gamertag': xf.gamertag,
                'title': xf.lastseen_titlename,
            }

        return status
Exemple #21
0
def _do_2fa(cassette_name, strategy_index, proof=None, otc=None):
    auth_manager = AuthenticationManager()
    auth_manager.email_address = '*****@*****.**'
    auth_manager.password = '******'

    with Betamax(auth_manager.session).use_cassette(cassette_name):
        with pytest.raises(TwoFactorAuthRequired) as excinfo:
            auth_manager.authenticate()

        two_fa_auth = TwoFactorAuthentication(
            auth_manager.session, auth_manager.email_address, excinfo.value.server_data
        )
        two_fa_auth.check_otc(strategy_index, proof)
        access_token, refresh_token = two_fa_auth.authenticate(strategy_index, proof, otc)
        auth_manager.access_token = access_token
        auth_manager.refresh_token = refresh_token
        auth_manager.authenticate(do_refresh=False)
    return auth_manager
Exemple #22
0
def main():
    parser = argparse.ArgumentParser(description="Search for Content on XBL")
    parser.add_argument(
        '--tokens',
        '-t',
        default=TOKENS_FILE,
        help="Token filepath. Default: \'{}\'".format(TOKENS_FILE))
    parser.add_argument('--legacy',
                        '-l',
                        action='store_true',
                        help="Search for Xbox 360 content")
    parser.add_argument("--keys",
                        action='append',
                        type=lambda kv: kv.split("="),
                        dest='keyvalues')
    parser.add_argument('search_query', help="Name to search for")

    args = parser.parse_args()

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
    except FileNotFoundError as e:

        print('Failed to load tokens from \'{}\'.\n'
              'ERROR: {}'.format(e.filename, e.strerror))
        sys.exit(-1)

    try:
        auth_mgr.authenticate(do_refresh=True)
    except AuthenticationException as e:
        print('Authentication failed! Err: %s' % e)
        sys.exit(-1)

    xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash,
                                auth_mgr.xsts_token.jwt,
                                auth_mgr.userinfo.xuid)

    keys = dict(args.keyvalues) if args.keyvalues else dict()
    if not args.legacy:
        resp = xbl_client.eds.get_singlemediagroup_search(args.search_query,
                                                          10,
                                                          "DGame",
                                                          domain="Modern",
                                                          **keys)
    else:
        resp = xbl_client.eds.get_singlemediagroup_search(args.search_query,
                                                          10,
                                                          "Xbox360Game",
                                                          domain="Xbox360",
                                                          **keys)

    if resp.status_code != 200:
        print("Invalid EDS details response")
        sys.exit(-1)

    print(json.dumps(resp.json(), indent=2))
Exemple #23
0
 def __attrs_post_init__(self):
     self.auth_mgr = AuthenticationManager(
         self.session,
         os.environ["XBOX_CLIENT_ID"],
         os.environ["XBOX_CLIENT_SECRET"],
         "",
     )
     self.auth_mgr.oauth = OAuth2TokenResponse.parse_file(
         os.environ["XAPI_TOKENS_LOCATION"])
     asyncio.create_task(self.refresh_tokens())
def test_auth_refresh_token():
    auth_manager = AuthenticationManager()
    auth_manager.refresh_token = RefreshToken(
        "CuZ*4TX7!SAF33cW*kzdFmgCLPRcz0DtUHFqjQgF726!FG3ScC5yMiDLsJYJ03m4fURrzf3J7X8l6A8mJGhHoRf42aHeJLrtp6wS"
        "Jh*PudaQdPNGJZHD1CpU4diJJxz0zhrijFsaAYXMqf3mSU7EerR5RtdHOwbcrlRlj7TBQ9RdLqWpy9KWsNhyPrwOMDJnBfAf3xsZ"
        "3g3QkmMeKGil85*q*MV*YqMPZTa8UVLPfM!jJeHwOjVhWPaYVq4hf6zIAwSLJl1Reo6GbkkPktrK3laFBGeqSkq651YgdjwtepwC"
        "Ef7oMwzz8c8msv8l95RU*QmtIjdRFd!fYtQctiGLDGs$")

    with Betamax(auth_manager.session).use_cassette('token_refresh'):
        auth_manager.authenticate(do_refresh=True)

    assert auth_manager.authenticated is True
    assert auth_manager.xsts_token.is_valid is True
    assert auth_manager.access_token.is_valid is True
    assert auth_manager.refresh_token.is_valid is True
    assert auth_manager.user_token.is_valid is True
    assert auth_manager.userinfo.userhash == '1674471606081042789'
    assert auth_manager.userinfo.xuid == '2535428504476914'
    assert auth_manager.userinfo.gamertag == 'xboxWebapiGamertag'
Exemple #25
0
def main():
    parser = argparse.ArgumentParser(description="Basic smartglass client")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")
    parser.add_argument('--verbose',
                        '-v',
                        action='store_true',
                        help="Verbose flag, also log message content")

    args = parser.parse_args()

    if args.verbose:
        fmt = VerboseFormatter(logging.BASIC_FORMAT)
    else:
        fmt = logging.Formatter(logging.BASIC_FORMAT)

    handler = logging.StreamHandler()
    handler.setFormatter(fmt)
    logging.root.addHandler(handler)
    logging.root.setLevel(logging.DEBUG)

    # logging.basicConfig(level=logging.DEBUG, format=logfmt)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt
    discovered = Console.discover(timeout=1, addr=args.address)
    if len(discovered):
        console = discovered[0]
        console.on_timeout += on_timeout
        state = console.connect(userhash, token)
        if state != ConnectionState.Connected:
            logging.error("Connection failed")
            sys.exit(1)

        signal.signal(signal.SIGINT, lambda *args: console.protocol.stop())
        console.protocol.serve_forever()
    else:
        logging.error("No consoles discovered")
        sys.exit(1)
def main():
    parser = argparse.ArgumentParser(description="Power off xbox one console")
    parser.add_argument('--tokens',
                        '-t',
                        default=TOKENS_FILE,
                        help="Token file, created by xbox-authenticate script")
    parser.add_argument('--liveid', '-l', help="Console Live ID")
    parser.add_argument('--address', '-a', help="IP address of console")
    parser.add_argument('--all',
                        action='store_true',
                        help="Power off all consoles")
    parser.add_argument('--refresh',
                        '-r',
                        action='store_true',
                        help="Refresh xbox live tokens in provided token file")

    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    try:
        auth_mgr = AuthenticationManager.from_file(args.tokens)
        auth_mgr.authenticate(do_refresh=args.refresh)
        auth_mgr.dump(args.tokens)
    except Exception as e:
        print("Failed to authenticate with provided tokens, Error: %s" % e)
        print("Please re-run xbox-authenticate to get a fresh set")
        sys.exit(1)

    userhash = auth_mgr.userinfo.userhash
    token = auth_mgr.xsts_token.jwt

    if not args.liveid and not args.address and not args.all:
        print("No arguments supplied!")
        parser.print_help()
        sys.exit(1)

    consoles = Console.discover(timeout=1, addr=args.address)
    if not len(consoles):
        print("No consoles found!")
        sys.exit(1)

    if not args.all and args.liveid:
        consoles = [c for c in consoles if c.liveid == args.liveid]
    if not args.all and args.address:
        consoles = [c for c in consoles if c.address == args.address]

    for c in consoles:
        state = c.connect(userhash, token)
        if state != ConnectionState.Connected:
            print("Connecting to %s failed" % c)
            continue
        c.wait(1)
        print("Shutting down %s ..." % c)
        c.power_off()
def generate_authentication_manager(
    session_config: AuthSessionConfig,
    http_session: aiohttp.ClientSession = None
) -> AuthenticationManager:
    return AuthenticationManager(
        client_session=http_session,
        client_id=session_config.client_id,
        client_secret=session_config.client_secret,
        redirect_uri=session_config.redirect_uri,
        scopes=session_config.scopes
    )
Exemple #28
0
def authentication_oauth():
    if app.authentication_mgr.authenticated:
        return render_template('auth_result.html',
                               title='Already signed in',
                               result='Already signed in',
                               message='You are already signed in, please logout first!',
                               link_path='/auth/logout',
                               link_title='Logout')
    else:
        return render_template('login_oauth.html',
                               oauth_url=AuthenticationManager.generate_authorization_url())
Exemple #29
0
    def __init__(self, email, password, x_auth_key):
        self.x_auth_key = x_auth_key
        self.url = 'http://xapi.us/v2'
        self.client = Client(api_key=x_auth_key)

        # use the microsoft api to get the xuid info without using requests
        self.auth_mgr = AuthenticationManager()

        # set data for auth manager
        self.auth_mgr.email_address = email
        self.auth_mgr.password = password

        # authentication
        self.auth_mgr.authenticate(do_refresh=True)

        # set the new info to a xbl client
        self.xbl_client = XboxLiveClient(self.auth_mgr.userinfo.userhash,
                                         self.auth_mgr.xsts_token.jwt,
                                         self.auth_mgr.userinfo.xuid)
        self.profile_provider = ProfileProvider(self.xbl_client)
        self.people_provider = PeopleProvider(self.xbl_client)
def test_load_tokens_from_file(tokens_filepath):
    auth_manager = AuthenticationManager.from_file(tokens_filepath)

    assert auth_manager.userinfo is not None
    assert auth_manager.userinfo.userhash == '1674471606081042789'
    assert auth_manager.userinfo.xuid == '2535428504476914'
    assert auth_manager.userinfo.gamertag == 'xboxWebapiGamertag'

    assert auth_manager.access_token.is_valid is False
    assert auth_manager.refresh_token.is_valid is True
    assert auth_manager.user_token.is_valid is True
    assert auth_manager.xsts_token is None