public void Should_CheckTokenIsRevoked_ReturnFalse()
        {
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);

            // create test token
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, "*****@*****.**"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var token = new JwtSecurityToken
                        (
                issuer: _configuration["JWT_ISSUER"],
                audience: _configuration["JWT_AUDIENCE"],
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(10),
                notBefore: DateTime.UtcNow,
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT_KEY"])),
                    SecurityAlgorithms.HmacSha256)
                        );

            // token not yet added, and so should return false
            Assert.False(jwtManager.IsRevoked(token));
        }
        public void Should_RevokeStringToken()
        {
            // mock user manager
            Mock <IUserStore <User> > userStore = new Mock <IUserStore <User> >();

            // create test token
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, "*****@*****.**"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var token = new JwtSecurityToken
                        (
                issuer: _configuration["JWT_ISSUER"],
                audience: _configuration["JWT_AUDIENCE"],
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(10),
                notBefore: DateTime.UtcNow,
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT_KEY"])),
                    SecurityAlgorithms.HmacSha256)
                        );
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            string stringToken = handler.WriteToken(token);

            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);

            Assert.True(jwtManager.RevokeToken(stringToken));
        }
        public async Task ShouldNot_ConfirmUserIsAuthorized_InvalidToken()
        {
            var client = _factory.CreateClient();

            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);

            JwtSecurityToken token = await jwtManager.GenerateJwtAsync("*****@*****.**", new List <Claim>());

            token.Payload["exp"] = DateTimeOffset.Now.ToUnixTimeSeconds();
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            string testToken = handler.WriteToken(token);

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token
            var aftResponse = await client.GetAsync("api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            var response = await client.GetAsync("/api/account/isAuth");

            string content = await response.Content.ReadAsStringAsync();

            Assert.Equal("false", content);
        }
        public async void Should_GetFeatures_FilterName(string filter)
        {
            // add seed data for features
            var client = _factory.CreateClient();

            List <Feature> features = new List <Feature>
            {
                new Feature {
                    Id = 1, Title = "Title", Name = "test a", Detail = "Feature Details", Link = "www.something.com", Image = "Image Data", Order = 1
                },
                new Feature {
                    Id = 2, Title = "Title", Name = "test b", Detail = "Feature Details", Link = "www.something.com", Image = "Image Data", Order = 2
                },
                new Feature {
                    Id = 3, Title = "Title", Name = "test c", Detail = "Feature Details", Link = "www.something.com", Image = "Image Data", Order = 3
                },
                new Feature {
                    Id = 4, Title = "Title", Name = "test d", Detail = "Feature Details", Link = "www.something.com", Image = "Image Data", Order = 4
                }
            };

            // spoof admin access
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);
            string      testToken  = await jwtManager.GenerateJwtStringAsync("*****@*****.**", new List <Claim> {
                new Claim(ClaimTypes.Role, "admin")
            });

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token, and add to header
            var aftResponse = await client.GetAsync("/api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            foreach (Feature feature in features)
            {
                string json         = JsonConvert.SerializeObject(feature);
                var    content      = new StringContent(json, Encoding.UTF8, "application/json");
                var    postResponse = await client.PostAsync("api/features", content);
            }

            // ignore response
            var filterResponse = await client.GetAsync($"/api/features?$filter=Name eq '{filter}'");

            string data = await filterResponse.Content.ReadAsStringAsync();

            List <Feature> getFeatures = await filterResponse.Content.ReadAsAsync <List <Feature> >();

            if (getFeatures != null)
            {
                Assert.Single(getFeatures);
            }
            else
            {
                Assert.NotNull(getFeatures);
            }
        }
        public async void Should_GetEvents_FilterName(string filter)
        {
            // add seed data for events
            var client = _factory.CreateClient();

            List <Event> events = new List <Event>
            {
                new Event {
                    Name = "test a", Description = "desc", Image = "", Duration = 100, AgeRating = AgeRatingType.BBFC_12A
                },
                new Event {
                    Name = "test b", Description = "desc", Image = "", Duration = 90, AgeRating = AgeRatingType.BBFC_PG
                },
                new Event {
                    Name = "test c", Description = "desc", Image = "", Duration = 130, AgeRating = AgeRatingType.BBFC_U
                },
                new Event {
                    Name = "test d", Description = "desc", Image = "", Duration = 240, AgeRating = AgeRatingType.PEGI_12A
                }
            };

            // spoof admin access
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);
            string      testToken  = await jwtManager.GenerateJwtStringAsync("*****@*****.**", new List <Claim> {
                new Claim(ClaimTypes.Role, "admin")
            });

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token, and add to header
            var aftResponse = await client.GetAsync("/api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            foreach (Event @event in events)
            {
                string json         = JsonConvert.SerializeObject(@event);
                var    content      = new StringContent(json, Encoding.UTF8, "application/json");
                var    postResponse = await client.PostAsync("api/events", content);
            }

            // ignore response
            var filterResponse = await client.GetAsync($"/api/events?$filter=Name eq '{filter}'");

            string data = await filterResponse.Content.ReadAsStringAsync();

            List <Event> getEvents = await filterResponse.Content.ReadAsAsync <List <Event> >();

            if (getEvents != null)
            {
                Assert.Single(getEvents);
            }
            else
            {
                Assert.NotNull(getEvents);
            }
        }
        public async void Should_CreateJwtToken()
        {
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);

            JwtSecurityToken token = await jwtManager.GenerateJwtAsync("*****@*****.**", new List <Claim>());

            if (token != null)
            {
                Assert.Equal("*****@*****.**", token.Subject);
            }
            else
            {
                Assert.True(false);
            }
        }
        public async Task Should_ConfirmUserIsAuthorized()
        {
            var client = _factory.CreateClient();

            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);

            string testToken = await jwtManager.GenerateJwtStringAsync("*****@*****.**", new List <Claim>());

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token
            var aftResponse = await client.GetAsync("api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            var response = await client.GetAsync("/api/account/isAuth");

            string content = await response.Content.ReadAsStringAsync();

            Assert.Equal("true", content);
        }
Exemplo n.º 8
0
        public async void Should_GetShowingAllocations()
        {
            // add seed data for showing & foreign dependencies
            var client = _factory.CreateClient();

            // spoof admin access
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);
            string      testToken  = await jwtManager.GenerateJwtStringAsync("*****@*****.**", new List <Claim> {
                new Claim(ClaimTypes.Role, "admin")
            });

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token, and add to header
            var aftResponse = await client.GetAsync("/api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            Event @event = new Event
            {
                Name        = "Test Event",
                Description = "Event Desc",
                Image       = "",
                Duration    = 120,
                AgeRating   = AgeRatingType.BBFC_PG
            };

            string json         = JsonConvert.SerializeObject(@event);
            var    content      = new StringContent(json, Encoding.UTF8, "application/json");
            var    postResponse = await client.PostAsync("api/events", content);

            Venue venue = new Venue
            {
                Name         = "Test Venue",
                Description  = "Venue Desc",
                Address1     = "Addr1",
                Address2     = "Addr2",
                Address3     = "Addr3",
                Address4     = "Addr4",
                Address5     = "Addr5",
                ContactPhone = "",
                Image        = "",
                Website      = "",
                Instagram    = "",
                Facebook     = "",
                Twitter      = "",
                Facilities   = FacilityFlags.Bar | FacilityFlags.GuideDogsPermitted,
                LatLong      = ""
            };

            json         = JsonConvert.SerializeObject(venue);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/venues", content);

            Room room = new Room
            {
                Name        = "Test Room",
                Description = "Room Desc",
                Columns     = 10,
                Rows        = 10,
                Isles       = "",
                VenueId     = 1
            };

            json         = JsonConvert.SerializeObject(room);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/rooms", content);

            PricingStrategy strategy = new PricingStrategy
            {
                Name        = "Test Strategy",
                Description = "Strategy Desc"
            };

            json         = JsonConvert.SerializeObject(strategy);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/pricingstrategies", content);

            Showing showing = new Showing
            {
                Id                = 0,
                StartTime         = DateTime.Now,
                EndTime           = DateTime.Now.AddMinutes(120),
                PricingStrategyId = 1,
                EventId           = 1,
                RoomId            = 1
            };

            json         = JsonConvert.SerializeObject(showing);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/showings", content);

            Customer customer = new Customer
            {
                Address1     = "",
                Address2     = "",
                Address3     = "",
                Address4     = "",
                Address5     = "",
                ContactEmail = "",
                ContactPhone = "",
                FirstName    = "",
                LastName     = ""
            };

            json         = JsonConvert.SerializeObject(customer);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/customers", content);

            Booking booking = new Booking
            {
                Id         = 0,
                BookedDate = DateTime.Now,
                ShowingId  = 1,
                CustomerId = 1,
                Status     = BookingStatus.PaymentComplete
            };

            json         = JsonConvert.SerializeObject(booking);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/bookings", content);

            for (int i = 0; i < 5; i++)
            {
                BookingItem bookingItem = new BookingItem
                {
                    Id              = 0,
                    AgreedPrice     = 4.2f,
                    AgreedPriceName = "",
                    BookingId       = 1,
                    Location        = i
                };

                json         = JsonConvert.SerializeObject(bookingItem);
                content      = new StringContent(json, Encoding.UTF8, "application/json");
                postResponse = await client.PostAsync("api/bookingitems", content);
            }

            var availabilityResponse = await client.GetAsync("api/showings/allocations/1");

            if (availabilityResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Assert.True(false);
            }

            string data = await availabilityResponse.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(data))
            {
                Assert.True(false);
            }
        }
Exemplo n.º 9
0
        public async void Should_GetShowings_IncludeEventRoomVenue(string name)
        {
            // add seed data for showing & foreign dependencies
            var client = _factory.CreateClient();

            // spoof admin access
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);
            string      testToken  = await jwtManager.GenerateJwtStringAsync("*****@*****.**", new List <Claim> {
                new Claim(ClaimTypes.Role, "admin")
            });

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token, and add to header
            var aftResponse = await client.GetAsync("/api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            Event @event = new Event
            {
                Name        = "Test Event",
                Description = "Event Desc",
                Image       = "",
                Duration    = 120,
                AgeRating   = AgeRatingType.BBFC_PG
            };

            string json         = JsonConvert.SerializeObject(@event);
            var    content      = new StringContent(json, Encoding.UTF8, "application/json");
            var    postResponse = await client.PostAsync("api/events", content);

            Venue venue = new Venue
            {
                Name         = name,
                Description  = "Venue Desc",
                Address1     = "Addr1",
                Address2     = "Addr2",
                Address3     = "Addr3",
                Address4     = "Addr4",
                Address5     = "Addr5",
                ContactPhone = "",
                Image        = "",
                Website      = "",
                Instagram    = "",
                Facebook     = "",
                Twitter      = "",
                Facilities   = FacilityFlags.Bar | FacilityFlags.GuideDogsPermitted,
                LatLong      = ""
            };

            json         = JsonConvert.SerializeObject(venue);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/venues", content);

            Room room = new Room
            {
                Name        = "Test Room",
                Description = "Room Desc",
                Columns     = 10,
                Rows        = 10,
                Isles       = "",
                VenueId     = 1
            };

            json         = JsonConvert.SerializeObject(room);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/rooms", content);

            PricingStrategy strategy = new PricingStrategy
            {
                Name        = "Test Strategy",
                Description = "Strategy Desc"
            };

            json         = JsonConvert.SerializeObject(strategy);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/pricingstrategies", content);

            Showing showing = new Showing
            {
                Id                = 0,
                StartTime         = DateTime.Now,
                EndTime           = DateTime.Now.AddMinutes(120),
                PricingStrategyId = 1,
                EventId           = 1,
                RoomId            = 1
            };

            json         = JsonConvert.SerializeObject(showing);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/showings", content);

            // get response, included expanded foreign records
            var filterResponse = await client.GetAsync($"/api/showings?$expand=Event,Room($expand=Venue)&$filter=Room/Venue/Name eq '{name}'");

            string data = await filterResponse.Content.ReadAsStringAsync();

            List <Showing> getShowings = await filterResponse.Content.ReadAsAsync <List <Showing> >();

            if (getShowings != null && getShowings.Count() > 0)
            {
                Assert.True(getShowings[0].Event != null && getShowings[0].Room != null && getShowings[0].Room.Venue != null);
            }
            else
            {
                if (getShowings.Count == 0)
                {
                    Assert.NotEmpty(getShowings);
                }

                Assert.NotNull(getShowings);
            }
        }
        public async void Should_GetRoom_WithShowingOnSpecifiedDate()
        {
            var client = _factory.CreateClient();

            // spoof admin access
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);
            string      testToken  = await jwtManager.GenerateJwtStringAsync("*****@*****.**", new List <Claim> {
                new Claim(ClaimTypes.Role, "admin")
            });

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + testToken);

            // get antiforgery token, and add to header
            var aftResponse = await client.GetAsync("/api/account/getCSRFToken");

            var tokenData = JsonConvert.DeserializeAnonymousType(aftResponse.Content.ReadAsStringAsync().Result, new { Token = "", TokenName = "" });

            client.DefaultRequestHeaders.Add(tokenData.TokenName, tokenData.Token);

            // add seed data for dependencies
            Event @event = new Event
            {
                Name        = "Test Event",
                Description = "Event Desc",
                Image       = "",
                Duration    = 120,
                AgeRating   = AgeRatingType.BBFC_PG
            };

            string json         = JsonConvert.SerializeObject(@event);
            var    content      = new StringContent(json, Encoding.UTF8, "application/json");
            var    postResponse = await client.PostAsync("api/events", content);

            Venue venue = new Venue
            {
                Name         = "Test Venue",
                Description  = "Venue Desc",
                Address1     = "Addr1",
                Address2     = "Addr2",
                Address3     = "Addr3",
                Address4     = "Addr4",
                Address5     = "Addr5",
                ContactPhone = "",
                Image        = "",
                Website      = "",
                Instagram    = "",
                Facebook     = "",
                Twitter      = "",
                Facilities   = FacilityFlags.Bar | FacilityFlags.GuideDogsPermitted,
                LatLong      = ""
            };

            json         = JsonConvert.SerializeObject(venue);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/venues", content);

            Room room = new Room
            {
                Name        = "Test Room",
                Description = "Room Desc",
                Columns     = 10,
                Rows        = 10,
                Isles       = "",
                VenueId     = 1
            };

            json         = JsonConvert.SerializeObject(room);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/rooms", content);

            PricingStrategy strategy = new PricingStrategy
            {
                Name        = "Test Strategy",
                Description = "Strategy Desc"
            };

            json         = JsonConvert.SerializeObject(strategy);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/pricingstrategies", content);

            Showing showing = new Showing
            {
                Id                = 0,
                StartTime         = new DateTime(2018, 12, 1),
                EndTime           = new DateTime(2018, 12, 2),
                PricingStrategyId = 1,
                EventId           = 1,
                RoomId            = 1
            };

            json         = JsonConvert.SerializeObject(showing);
            content      = new StringContent(json, Encoding.UTF8, "application/json");
            postResponse = await client.PostAsync("api/showings", content);

            var filterResponse = await client.GetAsync($"api/rooms?$expand=Showings&$filter=Showings/any(s : date(s/StartTime) ge 2018-12-1 and date(s/StartTime) lt 2018-12-2 and s/EventId eq 1)&$select=Id,Name,Showings");

            string data = await filterResponse.Content.ReadAsStringAsync();

            List <Room> getRooms = await filterResponse.Content.ReadAsAsync <List <Room> >();

            if (getRooms != null && getRooms.Count() > 0)
            {
                Assert.True(getRooms[0].Showings != null);
            }
            else
            {
                if (getRooms.Count == 0)
                {
                    Assert.NotEmpty(getRooms);
                }

                Assert.NotNull(getRooms);
            }
        }
        public void Should_ReturnSpecifiedTokenDuration(int minutes)
        {
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration, TimeSpan.FromMinutes(minutes));

            Assert.Equal(TimeSpan.FromMinutes(minutes), jwtManager.TokenDuration);
        }
        public void Should_ReturnDefaultTokenDuration()
        {
            IJwtManager jwtManager = new InMemoryJwtManager(_configuration);

            Assert.Equal(TimeSpan.FromMinutes(10), jwtManager.TokenDuration);
        }