示例#1
0
        private Guid SaveNewsInSomeWay(News news)
        {
            var guid = Guid.NewGuid();

            news.NewsId = guid;
            return(guid);
        }
 public ThumbnailEntry()
 {
     if (UniqueId == Guid.Empty)
     {
         UniqueId = Guid.NewGuid();
     }
 }
示例#3
0
    public static BasicObjectProgram Generator(WorldController controller)
    {
        var id          = ObjectId.NewGuid();
        var metadata    = new MetaData(null, null, 0, 0);
        var resources   = new Resources(100);
        var eigenvalue  = new Eigenvalue();
        var transform   = new Transform();
        var parameter   = new Parameter(metadata, eigenvalue, transform, resources);
        var maskedParam = new MaskedParameter(parameter, MaskedParameter.Mask.EIGENVALUE | MaskedParameter.Mask.TRANSFORM);
        var knowledge   = new Knowledge(id, maskedParam);

        controller.credentialTable.Add(id, Credential.HashPassword(id.ToString(), Credential.HashAlgorithm.NOOP));

        var data = new BasicObjectProgram();

        data.controller = controller;
        data.knowledge  = knowledge;

        controller.objectList.Add(id, parameter);

        var objectIdPair = new ObjectIdPair();

        objectIdPair.Add(id, id);
        controller.maskedObjectList.Add(objectIdPair, maskedParam);

        return(data);
    }
示例#4
0
        public void FailedTenantDiscoveryMissingEndpointsTest()
        {
            using (var harness = CreateTestHarness())
            {
                // add mock response for tenant endpoint discovery
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ExpectedUrl     = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("OpenidConfiguration-MissingFields-OnPremise.json")))
                });

                Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Adfs);
                try
                {
                    var resolver  = new AuthorityEndpointResolutionManager(harness.ServiceBundle);
                    var endpoints = resolver.ResolveEndpointsAsync(
                        instance.AuthorityInfo,
                        TestConstants.FabrikamDisplayableId,
                        new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                    .GetAwaiter().GetResult();
                    Assert.Fail("validation should have failed here");
                }
                catch (MsalServiceException exc)
                {
                    Assert.AreEqual(MsalError.TenantDiscoveryFailedError, exc.ErrorCode);
                }
            }
        }
示例#5
0
        public void ValidationOffSuccessTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    Url             = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("OpenidConfiguration-OnPremise.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, false);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                Task.Run(
                    async() =>
                {
                    await instance.ResolveEndpointsAsync(
                        CoreTestConstants.FabrikamDisplayableId,
                        new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                }).GetAwaiter().GetResult();

                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", instance.AuthorizationEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", instance.TokenEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs", instance.SelfSignedJwtAudience);
            }
        }
示例#6
0
        public async Task Users_Create()
        {
            var username  = Guid.NewGuid().ToString();
            var nickname  = $"Nickname{username}";
            var email     = $"{username}@test.com";
            var firstname = $"Firstname{username}";
            var lastname  = $"Lastname{username}";
            var password  = $"testpassword{username}";
            var name      = $"{firstname} {lastname}";

            var user = await _clientAuth.Users.Create(new User(username, email, password)
            {
                NickName  = nickname,
                Name      = name,
                FirstName = firstname,
                LastName  = lastname
            });

            Assert.IsNotNull(user);
            Assert.AreEqual(nickname, user.NickName);
            Assert.AreEqual(name, user.Name);
            Assert.AreEqual(firstname, user.FirstName);
            Assert.AreEqual(lastname, user.LastName);
            Assert.AreEqual(username, user.UserName);
            Assert.AreEqual(email, user.Email);
        }
示例#7
0
        public void ValidationOffSuccessTest()
        {
            using (var harness = CreateTestHarness())
            {
                // add mock response for tenant endpoint discovery
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod  = HttpMethod.Get,
                    ExpectedUrl     = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("OpenidConfiguration-OnPremise.json")))
                });

                Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Adfs);
                var resolver  = new AuthorityEndpointResolutionManager(harness.ServiceBundle);
                var endpoints = resolver.ResolveEndpointsAsync(
                    instance.AuthorityInfo,
                    TestConstants.FabrikamDisplayableId,
                    new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                .GetAwaiter().GetResult();

                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", endpoints.AuthorizationEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", endpoints.TokenEndpoint);
                Assert.AreEqual("https://fs.contoso.com/adfs", endpoints.SelfSignedJwtAudience);
            }
        }
示例#8
0
 public void PostTodo(Todo todo)
 {
     todo.Id           = Guid.NewGuid();
     todo.CreationDate = DateTime.Now;
     _db.Todos.Add(todo);
     _db.SaveChanges();
 }
示例#9
0
        private Task <User> CreateRandomUser()
        {
            var username = Guid.NewGuid().ToString();
            var email    = $"{username}@test.com";
            var password = $"testpassword{username}";

            return(_clientAuth.Users.Create(new User(username, email, password)));
        }
示例#10
0
 /// <summary>
 /// 初始化Entity Framework工作单元
 /// </summary>
 /// <param name="options">配置</param>
 /// <param name="serviceProvider">服务提供器</param>
 protected UnitOfWorkBase(DbContextOptions options, IServiceProvider serviceProvider)
     : base(options)
 {
     TraceId          = Guid.NewGuid().ToString();
     Session          = Meow.Auth.Session.Session.Instance;
     DatabaseType     = DbContextHelper.GetDatabaseType(options);
     _serviceProvider = serviceProvider ?? Ioc.Create <IServiceProvider>();
     RegisterToManager();
 }
        public void STPActionT4()
        {
            IntPtr p    = new IntPtr(int.MaxValue);
            Guid   guid = Guid.NewGuid();

            IPAddress       ip  = IPAddress.Parse("1.2.3.4");
            IWorkItemResult wir = _stp.QueueWorkItem(Action4, long.MinValue, p, ip, guid);

            Assert.IsNull(wir.State);
        }
        public void WIGFuncT4()
        {
            IntPtr p    = new IntPtr(int.MaxValue);
            Guid   guid = Guid.NewGuid();

            IPAddress ip = IPAddress.Parse("1.2.3.4");
            IWorkItemResult <IPAddress> wir = _wig.QueueWorkItem(new Func <long, IntPtr, IPAddress, Guid, IPAddress>(Func4), long.MinValue, p, ip, guid);

            Assert.IsNull(wir.State);
        }
示例#13
0
        public void FailedValidationResourceNotInTrustedRealmTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock response for on-premise DRS request
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("drs-response.json")))
                });


                //add mock response for on-premise webfinger request
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method      = HttpMethod.Get,
                    Url         = "https://fs.fabrikam.com/adfs/.well-known/webfinger",
                    QueryParams = new Dictionary <string, string>
                    {
                        { "resource", "https://fs.contoso.com" },
                        { "rel", "http://schemas.microsoft.com/rel/trusted-realm" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessWebFingerResponseMessage("https://fs.some-other-sts.com")
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, true);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            CoreTestConstants.FabrikamDisplayableId,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("ResolveEndpointsAsync should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
示例#14
0
        public async Task <(RustCategory, RustEditCategoryResult)> UpdateCategoryAsync(RustShopViewModel model)
        {
            var userForLog = await _userManager.FindByEmailAsync(_httpContextAccessor.HttpContext.User.Identity.Name);

            if (model.RustCategoryEditViewModel.Category.Id is null)
            {
                var shop = GetShopById(Guid.Parse(model.Id));

                if (shop is null)
                {
                    return(null, RustEditCategoryResult.Failed);
                }

                RustCategory newCategory = new RustCategory
                {
                    Id      = Guid.NewGuid(),
                    Index   = 1,
                    Name    = model.RustCategoryEditViewModel.Category.Name,
                    AppUser = await _userManager.FindByEmailAsync(_httpContextAccessor.HttpContext.User.Identity.Name),
                    Shop    = shop
                };

                _easyShopContext.RustCategories.Add(newCategory);
                await _easyShopContext.SaveChangesAsync();

                _logger.LogInformation("UserName: {0} | UserId: {1} | Request: {2} | Message: {3}",
                                       userForLog.UserName,
                                       userForLog.Id,
                                       _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                       $"Description was successfully created. CategoryId: {newCategory.Id}");

                return(newCategory, RustEditCategoryResult.Created);
            }

            var category = GetCategoryById(Guid.Parse(model.RustCategoryEditViewModel.Category.Id));

            if (category is null)
            {
                return(null, RustEditCategoryResult.Failed);
            }

            category.Index = model.RustCategoryEditViewModel.Category.Index;
            category.Name  = model.RustCategoryEditViewModel.Category.Name;

            _easyShopContext.RustCategories.Update(category);
            await _easyShopContext.SaveChangesAsync();

            _logger.LogInformation("UserName: {0} | UserId: {1} | Request: {2} | Message: {3}",
                                   userForLog.UserName,
                                   userForLog.Id,
                                   _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                   $"Description was successfully updated. CategoryId: {category.Id}");

            return(category, RustEditCategoryResult.Success);
        }
        public static void CreateCourse(string coursesDirectory, CourseData courseData)
        {
            var tempFilePath = "~" + FileName(courseData) + ".temp." + Guid.NewGuid();

            tempFilePath = Path.Combine(coursesDirectory, tempFilePath);
            Write2Disk(tempFilePath, courseData);
            var coursePath = Path.Combine(coursesDirectory, FileName(courseData));

            File.Delete(coursePath);
            File.Move(tempFilePath, coursePath);
        }
示例#16
0
        public void FailedValidationTest()
        {
            using (var harness = CreateTestHarness())
            {
                // add mock response for on-premise DRS request
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod      = HttpMethod.Get,
                    ExpectedUrl         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                    ExpectedQueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" }
                    },
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("drs-response.json")))
                });


                // add mock response for on-premise webfinger request
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod      = HttpMethod.Get,
                    ExpectedUrl         = "https://fs.fabrikam.com/adfs/.well-known/webfinger",
                    ExpectedQueryParams = new Dictionary <string, string>
                    {
                        { "resource", "https://fs.contoso.com" },
                        { "rel", "http://schemas.microsoft.com/rel/trusted-realm" }
                    },
                    ResponseMessage = MockHelpers.CreateFailureMessage(HttpStatusCode.NotFound, "not-found")
                });

                Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Adfs);

                try
                {
                    var resolver  = new AuthorityEndpointResolutionManager(harness.ServiceBundle);
                    var endpoints = resolver.ResolveEndpointsAsync(
                        instance.AuthorityInfo,
                        TestConstants.FabrikamDisplayableId,
                        new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                    .GetAwaiter().GetResult();
                    Assert.Fail("ResolveEndpointsAsync should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
示例#17
0
        /// <summary>
        /// Serialization constructor that initializes the properties from the serialization data.
        /// </summary>
        /// <param name="info">Serialization data to read from.</param>
        /// <param name="context">Streaming context to use during deserialization.</param>
        protected BaseConnection(SerializationInfo info, StreamingContext context)
        {
            IsBookmark = info.GetBoolean("IsBookmark");
            Name = info.GetString("Name");
            Host = info.GetString("Host");
            Guid = new Guid(info.GetString("Guid"));
            Username = info.GetString("Username");
            string encryptedPassword = info.GetString("Password");

            if (!String.IsNullOrEmpty(encryptedPassword))
                EncryptedPassword = encryptedPassword;

            if (Guid == Guid.Empty)
                Guid = Guid.NewGuid();
        }
        public void ActionT4()
        {
            IntPtr p    = new IntPtr(int.MaxValue);
            Guid   guid = Guid.NewGuid();

            IPAddress       ip  = IPAddress.Parse("1.2.3.4");
            IWorkItemResult wir = _stp.QueueWorkItem(Action4, long.MinValue, p, ip, guid);

            object[] args = wir.State as object[];

            Assert.IsNotNull(args);
            Assert.AreEqual(args.Length, 4);
            Assert.AreEqual(args[0], long.MinValue);
            Assert.AreEqual(args[1], p);
            Assert.AreEqual(args[2], ip);
            Assert.AreEqual(args[3], guid);
        }
示例#19
0
        public void FuncT4()
        {
            IntPtr p    = new IntPtr(int.MaxValue);
            Guid   guid = Guid.NewGuid();

            IPAddress ip = IPAddress.Parse("1.2.3.4");
            IWorkItemResult <IPAddress> wir = _wig.QueueWorkItem(new Func <long, IntPtr, IPAddress, Guid, IPAddress>(Func4), long.MinValue, p, ip, guid);

            object[] args = wir.State as object[];

            Assert.IsNotNull(args);
            Assert.AreEqual(args.Length, 4);
            Assert.AreEqual(args[0], long.MinValue);
            Assert.AreEqual(args[1], p);
            Assert.AreEqual(args[2], ip);
            Assert.AreEqual(args[3], guid);
        }
示例#20
0
        public NatPunchId Punch(IPEndPoint remoteEndpoint, OnNatPunchSuccess onSuccess = null, OnNatPunchFailure onFailure = null)
        {
            onSuccess = onSuccess ?? EmptyOnSuccess;
            onFailure = onFailure ?? EmptyOnFailure;

            var attempt = new PunchAttempt();

            attempt.Timestamp = DateTime.Now;
            attempt.EndPoint  = remoteEndpoint;
            // TODO Recycle tokens
            attempt.PunchId    = new NatPunchId(Guid.NewGuid().ToString());
            attempt.OnSuccess += onSuccess;
            attempt.OnFailure += onFailure;
            AddNatPunchAttempt(attempt);

            _facilitatorConnection.SendIntroduction(remoteEndpoint, attempt.PunchId);

            return(attempt.PunchId);
        }
        public LidgrenNatPunchClient(ICoroutineScheduler coroutineScheduler, LidgrenNatFacilitatorConnection facilitatorConnection)
        {
            _facilitatorConnection = facilitatorConnection;

            _punchAttemptPool = new ObjectPool <PunchAttempt>(() => new PunchAttempt());

            {
                const int natpunchIdCount = 256;
                var       punchIds        = new NatPunchId[natpunchIdCount];
                for (int i = 0; i < natpunchIdCount; i++)
                {
                    punchIds[i] = new NatPunchId(Guid.NewGuid().ToString());
                }
                _natPunchIds = CollectionUtil.LoopingEnumerator(punchIds);
            }

            _natPunchAttempts      = new Dictionary <NatPunchId, IPooledObject <PunchAttempt> >();
            _natPunchRegistrations = new List <IPooledObject <PunchAttempt> >();
            _facilitatorConnection.OnNatPunchSuccess += OnNatPunchSuccess;
            _facilitatorConnection.OnNatPunchFailure += OnNatPunchFailure;
            _cleanupRoutine = coroutineScheduler.Run(ConnectionTimeoutCleanup());
        }
        private void DoNewSaveFromPlayerClass(PlayerClassDefinition playerClass)
        {
            var saveFile = new SaveFile()
            {
                Platform = Platform.PC,
                SaveGame = new ProtoBufFormats.WillowTwoSave.WillowTwoPlayerSaveGame()
                {
                    SaveGameId    = 1,
                    SaveGuid      = (GameGuid)SystemGuid.NewGuid(),
                    PlayerClass   = playerClass.ResourcePath,
                    UIPreferences = new ProtoBufFormats.WillowTwoSave.UIPreferencesData()
                    {
                        CharacterName = Encoding.UTF8.GetBytes(playerClass.Name),
                    },
                    AppliedCustomizations = new List <string>()
                    {
                        "None",
                        "",
                        "",
                        "",
                        "None",
                    },
                },
            };

            FileFormats.SaveExpansion.ExtractExpansionSavedataFromUnloadableItemData(saveFile.SaveGame);

            this.General.ImportData(saveFile.SaveGame, saveFile.Platform);
            this.Character.ImportData(saveFile.SaveGame);
            this.Vehicle.ImportData(saveFile.SaveGame);
            this.CurrencyOnHand.ImportData(saveFile.SaveGame);
            this.Backpack.ImportData(saveFile.SaveGame, saveFile.Platform);
            this.Bank.ImportData(saveFile.SaveGame, saveFile.Platform);
            this.FastTravel.ImportData(saveFile.SaveGame);
            this.SavePath = null;
            this.SaveFile = saveFile;
            this.MaybeSwitchToGeneral();
        }
        public void FailedValidationMissingFieldsInDrsResponseTest()
        {
            using (var harness = CreateTestHarness())
            {
                // add mock failure response for on-premise DRS request
                harness.HttpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    ExpectedMethod      = HttpMethod.Get,
                    ExpectedUrl         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                    ExpectedQueryParams = new Dictionary <string, string>
                    {
                        { "api-version", "1.0" }
                    },
                    ResponseMessage =
                        MockHelpers.CreateSuccessResponseMessage(
                            ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("drs-response-missing-field.json")))
                });

                Authority instance = Authority.CreateAuthority(harness.ServiceBundle, TestConstants.OnPremiseAuthority);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Adfs);
                try
                {
                    var resolver  = new AuthorityEndpointResolutionManager(harness.ServiceBundle);
                    var endpoints = resolver.ResolveEndpointsAsync(
                        instance.AuthorityInfo,
                        TestConstants.FabrikamDisplayableId,
                        new RequestContext(harness.ServiceBundle, Guid.NewGuid()))
                                    .GetAwaiter().GetResult();
                    Assert.Fail("ResolveEndpointsAsync should have failed here");
                }
                catch (Exception exc)
                {
                    Assert.IsNotNull(exc);
                }
            }
        }
示例#24
0
        public void FailedTenantDiscoveryMissingEndpointsTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager);

                //add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    Url             = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("OpenidConfiguration-MissingFields-OnPremise.json")))
                });

                Authority instance = Authority.CreateAuthority(serviceBundle, CoreTestConstants.OnPremiseAuthority, false);
                Assert.IsNotNull(instance);
                Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
                try
                {
                    Task.Run(
                        async() =>
                    {
                        await instance.ResolveEndpointsAsync(
                            CoreTestConstants.FabrikamDisplayableId,
                            new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false);
                    }).GetAwaiter().GetResult();
                    Assert.Fail("validation should have failed here");
                }
                catch (MsalServiceException exc)
                {
                    Assert.AreEqual(CoreErrorCodes.TenantDiscoveryFailedError, exc.ErrorCode);
                }
            }
        }
示例#25
0
 public void RandomizeSaveGuid()
 {
     this.SaveGuid = SystemGuid.NewGuid();
 }
示例#26
0
 public static CourseData CreateNew()
 {
     return(new CourseData {
         Id = Guid.NewGuid().ToString(), Name = "", Props = ImmutableList <Prop> .Empty
     });
 }
示例#27
0
        public async Task <RustCreateShopResult> CreateShopAsync(CreateShopViewModel model)
        {
            var user = await _userManager.FindByEmailAsync(_httpContextAccessor.HttpContext.User.Identity.Name);

            var userShops = await UserShopsByUserEmailAsync(user.Email);

            var userAllowedShops = int.Parse(_configuration["ShopsAllowed"]);

            if (userShops.Count() < userAllowedShops)
            {
                Guid secret;
                do
                {
                    secret = Guid.NewGuid();
                } while (_easyShopContext.Shops.FirstOrDefault(x => x.Secret == secret) != null);

                var gameType = _easyShopContext.GameTypes.First(x => x.Type == model.GameType);

                Guid newShopId;
                do
                {
                    newShopId = Guid.NewGuid();
                } while (_easyShopContext.UserShops.FirstOrDefault(x => x.ShopId == newShopId) != null);

                var newShop = new Shop
                {
                    Id           = newShopId,
                    ShopName     = model.ShopName,
                    GameType     = gameType,
                    ShopTitle    = model.ShopTitle,
                    StartBalance = model.StartBalance,
                    Secret       = secret
                };

                var userShop = new UserShop
                {
                    ShopId    = newShopId,
                    Shop      = newShop,
                    AppUserId = user.Id,
                    AppUser   = user,
                };

                var addNewTenant = await _tenancyStoreService.TryAddAsync(
                    newShopId.ToString(),
                    newShopId.ToString(),
                    model.ShopName,
                    null);

                if (!addNewTenant)
                {
                    return(RustCreateShopResult.SomethingWentWrong);
                }

                _easyShopContext.Shops.Add(newShop);
                _easyShopContext.UserShops.Add(userShop);
                await _easyShopContext.SaveChangesAsync();

                if (model.AddDefaultItems)
                {
                    try
                    {
                        await SetDefaultProductsAsync(user, newShop);

                        await _easyShopContext.SaveChangesAsync();

                        _logger.LogInformation("UserName: {0} | UserId: {1} | Request: {2} | Message: {3}",
                                               user.UserName,
                                               user.Id,
                                               _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                               $"Rust shop has been successfully created! ShopId: {newShopId}");

                        return(RustCreateShopResult.Success);
                    }
                    catch (Exception e)
                    {
                        _easyShopContext.Shops.Remove(newShop);
                        _easyShopContext.UserShops.Remove(userShop);
                        await RemoveAllCategoriesAndItemsInShopAsync(newShop);

                        await _easyShopContext.SaveChangesAsync();

                        _logger.LogError("UserName: {0} | UserId: {1} | Request: {2} | Message: {3}",
                                         user.UserName,
                                         user.Id,
                                         _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                         $"Error on adding default products and categories. Error message: {e.Message}; Inner exception: {e.InnerException?.Message}; Stacktrace: {e.StackTrace};");

                        return(RustCreateShopResult.SomethingWentWrong);
                    }
                }

                _logger.LogInformation("UserName: {0} | UserId: {1} | Request: {2} | Message: {3}",
                                       user.UserName,
                                       user.Id,
                                       _httpContextAccessor.HttpContext.Request.GetRawTarget(),
                                       $"Rust shop has been successfully created! ShopId: {newShop.Id}");

                return(RustCreateShopResult.Success);
            }

            return(RustCreateShopResult.MaxShopLimitIsReached);
        }
示例#28
0
        public void SuccessfulValidationUsingOnPremiseDrsTest()
        {
            //add mock response for on-premise DRS request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" }
                },
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("drs-response.json"))
            });


            //add mock response for on-premise webfinger request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://fs.fabrikam.com/adfs/.well-known/webfinger",
                QueryParams = new Dictionary <string, string>
                {
                    { "resource", "https://fs.contoso.com" },
                    { "rel", "http://schemas.microsoft.com/rel/trusted-realm" }
                },
                ResponseMessage = MockHelpers.CreateSuccessWebFingerResponseMessage()
            });

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                Url             = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("OpenidConfiguration-OnPremise.json"))
            });

            Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority, true);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
            Task.Run(async() =>
            {
                await instance.ResolveEndpointsAsync(TestConstants.FabrikamDisplayableId, new RequestContext(Guid.NewGuid(), null));
            }).GetAwaiter().GetResult();

            Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/",
                            instance.AuthorizationEndpoint);
            Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/",
                            instance.TokenEndpoint);
            Assert.AreEqual("https://fs.contoso.com/adfs",
                            instance.SelfSignedJwtAudience);
            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
            Assert.AreEqual(1, Authority.ValidatedAuthorities.Count);

            //attempt to do authority validation again. NO network call should be made
            instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority, true);
            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
            Task.Run(async() =>
            {
                await instance.ResolveEndpointsAsync(TestConstants.FabrikamDisplayableId, new RequestContext(Guid.NewGuid(), null));
            }).GetAwaiter().GetResult();

            Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/",
                            instance.AuthorizationEndpoint);
            Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/",
                            instance.TokenEndpoint);
            Assert.AreEqual("https://fs.contoso.com/adfs",
                            instance.SelfSignedJwtAudience);
        }
示例#29
0
        public void FailedTenantDiscoveryMissingEndpointsTest()
        {
            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                Url             = "https://fs.contoso.com/adfs/.well-known/openid-configuration",
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("OpenidConfiguration-MissingFields-OnPremise.json"))
            });

            Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority, false);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
            try
            {
                Task.Run(async() =>
                {
                    await instance.ResolveEndpointsAsync(TestConstants.FabrikamDisplayableId, new RequestContext(Guid.NewGuid(), null));
                }).GetAwaiter().GetResult();
                Assert.Fail("validation should have failed here");
            }
            catch (MsalClientException exc)
            {
                Assert.AreEqual(MsalClientException.TenantDiscoveryFailedError, exc.ErrorCode);
            }

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
        }
示例#30
0
        public void FailedValidationMissingFieldsInDrsResponseTest()
        {
            //add mock failure response for on-premise DRS request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" }
                },
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("drs-response-missing-field.json"))
            });

            Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority, true);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
            try
            {
                Task.Run(async() =>
                {
                    await instance.ResolveEndpointsAsync(TestConstants.FabrikamDisplayableId, new RequestContext(Guid.NewGuid(), null));
                }).GetAwaiter().GetResult();
                Assert.Fail("ResolveEndpointsAsync should have failed here");
            }
            catch (Exception exc)
            {
                Assert.IsNotNull(exc);
            }

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
        }
示例#31
0
        public void FailedValidationTest()
        {
            //add mock response for on-premise DRS request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract",
                QueryParams = new Dictionary <string, string>
                {
                    { "api-version", "1.0" }
                },
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText("drs-response.json"))
            });


            //add mock response for on-premise webfinger request
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method      = HttpMethod.Get,
                Url         = "https://fs.fabrikam.com/adfs/.well-known/webfinger",
                QueryParams = new Dictionary <string, string>
                {
                    { "resource", "https://fs.contoso.com" },
                    { "rel", "http://schemas.microsoft.com/rel/trusted-realm" }
                },
                ResponseMessage = MockHelpers.CreateFailureMessage(HttpStatusCode.NotFound, "not-found")
            });

            Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority, true);

            Assert.IsNotNull(instance);
            Assert.AreEqual(instance.AuthorityType, AuthorityType.Adfs);
            try
            {
                Task.Run(async() =>
                {
                    await instance.ResolveEndpointsAsync(TestConstants.FabrikamDisplayableId, new RequestContext(Guid.NewGuid(), null));
                }).GetAwaiter().GetResult();
                Assert.Fail("ResolveEndpointsAsync should have failed here");
            }
            catch (Exception exc)
            {
                Assert.IsNotNull(exc);
            }

            Assert.AreEqual(0, HttpMessageHandlerFactory.MockCount);
        }
示例#32
0
 internal RegisteredMod(Guid guid, IContentEngineContent mod, IModS modScript) {
     Guid = guid;
     Mod = mod;
     ModScript = modScript;
     AccessToken = Convert.ToBase64String(Guid.NewGuid().ToByteArray().Combine(guid.ToByteArray()));
     ModScript.setToken(AccessToken);
 }