Esempio n. 1
0
        public void GetMembershipsForUser_InvalidAccessToken_ShouldThrowApiExceptionUnauthorized()
        {
            IConfiguration config = Mock.Of <IConfiguration>(m => m["Bungie:ApiKey"] == "dummy-api-key");
            // arrange
            Uri uri = new Uri("https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser/");
            // just an old example access token
            string accessToken             = "invalid.access.token";
            string responseString          = TestUtils.ReadFile("GetMembershipsForCurrentUser-invalid-access-token.html");
            Mock <HttpMessageHandler> mock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            mock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.Is <HttpRequestMessage>(
                    req =>
                    req.Method == HttpMethod.Get &&
                    req.RequestUri == uri &&
                    req.Headers.Any(h => h.Key == "X-API-KEY" && !string.IsNullOrEmpty(h.Value.FirstOrDefault())) &&
                    req.Headers.Any(h => h.Key == "Authorization" && h.Value.FirstOrDefault() == $"Bearer {accessToken}")),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.Unauthorized,      // 401 Unauthorized
                Content    = new StringContent(responseString)
            })
            .Verifiable();
            HttpClient             httpClient       = new HttpClient(mock.Object);
            BungieApiService       bungieApiService = new BungieApiService(config, httpClient);
            UserMembershipsRequest request          = new UserMembershipsRequest(accessToken);
            // act (and assert)
            var exception = Assert.ThrowsException <BungieApiException>(() => bungieApiService.GetMembershipsForUser(request));

            Assert.IsTrue(exception.Message.Contains("Unauthorized"));
        }
Esempio n. 2
0
        public void GetMembershipsForUser_PersonalAccount_ShouldReturnAllDestinyMemberships()
        {
            IConfiguration config = Mock.Of <IConfiguration>(m => m["Bungie:ApiKey"] == "dummy-api-key");
            // arrange
            Uri uri = new Uri("https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser/");
            // just an old example access token
            string accessToken             = "CLDjARKGAgAgVJDu+K+f85W6S6eJJi+s7U9tXkxDzInlc8I78HfgcabgAAAATOBrgq37w0FGjQ6XoVCLI4Mntf9IjfT91ByO4T59755lmaJvWMdnNpm4YcKglZiJN9IT0lLuZNifSUZRtWl1Xi+m83Eoh6VBMxRaec9Feeu4Coa53XzEAVr/BadPeaugfqB8A5jgEcRdQrnSH092D1h1ntzLpm0cOUttRGqMFpw/nR9Sm0vF1i4kdrq8F9gx+PQ6fJvbBxOKYZRSnQUgr3WjSSgWGmOvAu778Ikf/0tN7dmgpX6JFHcb2U1fcvSprnbb0qcqsGB71KsSvRqgJ5T9/LswkBT9TIHbrtS/cPg=";
            string responseString          = TestUtils.ReadFile("GetMembershipsForCurrentUser-valid-personal-account.json");
            Mock <HttpMessageHandler> mock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            mock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.Is <HttpRequestMessage>(
                    req =>
                    req.Method == HttpMethod.Get &&
                    req.RequestUri == uri &&
                    req.Headers.Any(h => h.Key == "X-API-KEY" && !string.IsNullOrEmpty(h.Value.FirstOrDefault())) &&
                    req.Headers.Any(h => h.Key == "Authorization" && h.Value.FirstOrDefault() == $"Bearer {accessToken}")),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(responseString)
            })
            .Verifiable();
            HttpClient             httpClient       = new HttpClient(mock.Object);
            BungieApiService       bungieApiService = new BungieApiService(config, httpClient);
            UserMembershipsRequest request          = new UserMembershipsRequest(accessToken);
            // act
            UserMembershipsResponse actual = bungieApiService.GetMembershipsForUser(request);

            // assert
            Assert.AreEqual(2, actual.DestinyMemberships.Count);
            Assert.AreEqual("anime8094", actual.DestinyMemberships[0].DisplayName);
            Assert.AreEqual(4611686018497175745, actual.DestinyMemberships[0].DestinyProfileId);
            Assert.AreEqual(1, actual.DestinyMemberships[0].MembershipType);
            Assert.AreEqual(3, actual.DestinyMemberships[0].CrossSaveOverride);
            Assert.AreEqual("pimpdaddy", actual.DestinyMemberships[1].DisplayName);
            Assert.AreEqual(4611686018467260757, actual.DestinyMemberships[1].DestinyProfileId);
            Assert.AreEqual(3, actual.DestinyMemberships[1].MembershipType);
            Assert.AreEqual(3, actual.DestinyMemberships[1].CrossSaveOverride);
        }
        public async Task <MembershipResponse> GetUserSegment([FromBody] UserMembershipsRequest request)
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                if (request == null)
                {
                    return(_responseGenerator.EmptyResponse(ResponseStatus.Error, ResponseMessage.InvalidData));
                }
                if (request.PartnerHashCode == null || (request.PartnerUserId == null && request.StickyUserId == null))
                {
                    return(_responseGenerator.EmptyResponse(ResponseStatus.Error, ResponseMessage.RequiredUserIdAndPartnerHashCode));
                }
                var partner = await _partnersManager.FindPartner(request.PartnerHashCode);

                if (partner.Id == 0)
                {
                    return(_responseGenerator.EmptyResponse(ResponseStatus.Error, ResponseMessage.NotRegisteredPartner));
                }

                MembershipData userMembershipResult = new MembershipData();
                if (request.StickyUserId == null)
                {
                    userMembershipResult = await _userMembershipFinder.FindMembershipByPartnerUserIdAsync(partner.Id, request.PartnerUserId);
                }
                else if (request.PartnerUserId == null)
                {
                    userMembershipResult = await _userMembershipFinder.FindMembershipByStickyIdAsync(request.StickyUserId ?? 0);
                }
                var response = await _responseGenerator.CreateResponseAsync(userMembershipResult.StickyUserId, partner.Id, userMembershipResult.Segments);

                stopwatch.Stop();
                await _responseTimeLogger.LogResponseTime(stopwatch.ElapsedMilliseconds, 1);

                return(response);
            }
            catch (Exception ex)
            {
                return(_responseGenerator.EmptyResponse(ResponseStatus.Error, ex.Message));
            }
        }