Пример #1
0
        public virtual void TestInit()
        {
            this.SetupScope();
            AutoMapperConfig.Configure();

            this.TestData = new TestData(this.Context, this.Scope, new GameService(this.Scope, this.UnitOfWork));

            // Ensure a user does exist
            this.TestUser = new User
            {
                Id = Guid.NewGuid().ToString(),
                UserName = "******"
            };
            this.Context.Users.Add(this.TestUser);

            this.BotUser = new User
            {
                Id = Guid.NewGuid().ToString(),
                UserName = "******"
            };
            this.Context.Users.Add(this.BotUser);

            this.Context.SaveChanges();

            TestUserProvider.User = this.TestUser;

            DomainDepsResolver.ScopeGen = () => this.Container;
        }
        public async Task<IActionResult> RegisterExternal([FromBody] RegisterExternalBindingModel model)
        {
            var externalLoginInfo = await this._signInManager.GetExternalLoginInfoAsync();
            if (externalLoginInfo == null)
            {
                return this.BadRequest();
            }

            var user = new User
            {
                UserName = model.UserName,
                Email = "", // TOOD: CS: Get email from claims
                EmailConfirmed = true // External accounts are trusted by default
            };

            var result = await this._userManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await this._userManager.AddLoginAsync(user, externalLoginInfo);
                if (result.Succeeded)
                {
                    await this._signInManager.SignInAsync(user, isPersistent: false);
                    return this.Ok();
                }
            }

            return this.CheckResult(result);
        }
        private async Task sendEmailConfirmation(User user, string code, string language, string callbackUrl)
        {
            // Create email confirmation link
            callbackUrl = callbackUrl.Replace("userId", user.Id);
            callbackUrl = callbackUrl.Replace("code", WebUtility.UrlEncode(code));

            this.SetCulture(language);

            string body = string.Format(Resources.EmailConfirmationBody, callbackUrl);
            await this._emailSender.SendMail(user.Email, Resources.EmailConfirmationSubject, body, body);
        }
        public async Task<IActionResult> Register([FromBody] RegisterBindingModel model)
        {
            var user = new User
            {
                UserName = model.UserName,
                Email = model.Email,
                Language = model.Language
            };

            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                if (Startup.RequireUserConfirmation)
                {
                    var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);

                    // TODO: CS: Send email
                }
            }

            return this.CheckResult(result);
        }
        private async Task<AuthenticationTicket> CreateTicketAsync(OpenIdConnectRequest request, User user)
        {
            // Set the list of scopes granted to the client application.
            // Note: the offline_access scope must be granted
            // to allow OpenIddict to return a refresh token.
            var scopes = new[] {
                OpenIdConnectConstants.Scopes.OpenId,
                OpenIdConnectConstants.Scopes.Email,
                OpenIdConnectConstants.Scopes.Profile,
                OpenIdConnectConstants.Scopes.OfflineAccess,
                OpenIdConnectConstants.Scopes.Profile,
                OpenIddictConstants.Scopes.Roles
            }.Intersect(request.GetScopes());

            // Create a new ClaimsPrincipal containing the claims that
            // will be used to create an id_token, a token or a code.
            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            principal.AddIdentity(new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, user.UserName)
            }));
            
            // Note: by default, claims are NOT automatically included in the access and identity tokens.
            // To allow OpenIddict to serialize them, you must attach them a destination, that specifies
            // whether they should be included in access tokens, in identity tokens or in both.
            foreach (var claim in principal.Claims)
            {
                // Always include the user identifier in the
                // access token and the identity token.
                if (claim.Type == ClaimTypes.NameIdentifier)
                {
                    claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                          OpenIdConnectConstants.Destinations.IdentityToken);
                }

                // Include the name claim, but only if the "profile" scope was requested.
                else if (claim.Type == ClaimTypes.Name && scopes.Contains(OpenIdConnectConstants.Scopes.Profile))
                {
                    claim.SetDestinations(OpenIdConnectConstants.Destinations.IdentityToken);
                }

                // Include the role claims, but only if the "roles" scope was requested.
                else if (claim.Type == ClaimTypes.Role && scopes.Contains(OpenIddictConstants.Scopes.Roles))
                {
                    claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                          OpenIdConnectConstants.Destinations.IdentityToken);
                }

                // The other claims won't be added to the access
                // and identity tokens and will be kept private.
            }            

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(
                principal, 
                new AuthenticationProperties(),
                OpenIdConnectServerDefaults.AuthenticationScheme);

            ticket.SetScopes(scopes);
            
            return ticket;
        }    
Пример #6
0
        public User CreateUser(string name)
        {
            var user = new User()
            {
                UserName = name
            };

            this.context.Users.Add(user);

            this.SaveChanges();

            return user;
        }
        public virtual async Task Seed(ImperaContext context)
        {
            // Enable if seed should be debugged locally
            // if (System.Diagnostics.Debugger.IsAttached == false)
            //     System.Diagnostics.Debugger.Launch();

            // Insert roles            
            if (await this.roleManager.FindByNameAsync("admin") == null)
            {
                await this.roleManager.CreateAsync(new IdentityRole("admin"));
            }

            if (await this.roleManager.FindByNameAsync("system") == null)
            {
                await this.roleManager.CreateAsync(new IdentityRole("system"));
            }

            // Insert technical user
            User systemUser = await this.userManager.FindByNameAsync("System");
            if (systemUser == null)
            {
                systemUser = new User
                {                    
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    GameSlots = int.MaxValue
                };
                var result = await this.userManager.CreateAsync(systemUser, Guid.NewGuid().ToString());
                if (!result.Succeeded)
                {
                    throw new Exception();
                }
            }

            await userManager.AddToRolesAsync(systemUser, new[] { "admin", "system" });

            // Insert bot user
            User botUser = await this.userManager.FindByNameAsync("Bot");
            if (botUser == null)
            {
                botUser = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true,
                    GameSlots = int.MaxValue
                };
                await this.userManager.CreateAsync(botUser, Guid.NewGuid().ToString());
            }

            await this.userManager.AddToRoleAsync(botUser, "system");

#if DEBUG
            // Insert test user
            User testUser = context.Users.FirstOrDefault(x => x.UserName == "digitald");
            if (testUser == null)
            {
                testUser = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true
                };
                await this.userManager.CreateAsync(testUser, "impera1234");
            }

            await this.userManager.AddToRoleAsync(testUser, "admin");

            User testUser2 = context.Users.FirstOrDefault(x => x.UserName == "ddtest");
            if (testUser2 == null)
            {
                testUser2 = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    EmailConfirmed = true
                };
                await this.userManager.CreateAsync(testUser2, "impera1234");
            }

            // News
            var newsEntry = Domain.News.NewsEntry.Create();
            newsEntry.CreatedBy = newsEntry.CreatedBy = testUser;
            newsEntry.LastModifiedAt =newsEntry.CreatedAt = newsEntry.CreatedAt = DateTime.UtcNow;
            newsEntry.AddContent("en", "Title", "This is a news entry.");            
            context.NewsEntries.Add(newsEntry);
#endif

            context.SaveChanges();

            this.InitChannels(context, systemUser);

            this.InitLadder(context, systemUser);

            // Default set of maps
            var mapType = typeof(Maps);
            foreach (var mapMethod in mapType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
            {
                var mapName = mapMethod.Name;
                var mapTemplateDescriptor = new MapTemplateDescriptor
                {
                    Name = mapName
                };

                mapTemplateDescriptor.LastModifiedAt = mapTemplateDescriptor.CreatedAt = DateTime.UtcNow;

                if (context.MapTemplates.FirstOrDefault(mt => mt.Name == mapTemplateDescriptor.Name) == null)
                {
                    context.MapTemplates.Add(mapTemplateDescriptor);
                }
            }

            context.SaveChanges();
        }
        private void InitLadder(ImperaContext context, User systemUser)
        {
            if (context.Ladders.FirstOrDefault(l => l.Name == "Default") == null)
            {
                var ladder = new Ladder("Default", 2, 2);

                ladder.MapTemplates.Add("WorldDeluxe");

                ladder.Options.MapDistribution = MapDistribution.Default;
                ladder.Options.VisibilityModifier.Add(VisibilityModifierType.None);
                ladder.Options.VictoryConditions.Add(VictoryConditionType.Survival);

                ladder.Options.AttacksPerTurn = 3;
                ladder.Options.InitialCountryUnits = 3;
                ladder.Options.MapDistribution = MapDistribution.Default;
                ladder.Options.MaximumNumberOfCards = 5;
                ladder.Options.MaximumTimeoutsPerPlayer = 1;
                ladder.Options.MinUnitsPerCountry = 1;
                ladder.Options.MovesPerTurn = 3;
                ladder.Options.NewUnitsPerTurn = 3;
                ladder.Options.TimeoutInSeconds = (int)TimeSpan.FromDays(1).TotalSeconds;

                ladder.ToggleActive(true);

                context.Ladders.Add(ladder);

                context.SaveChanges();
            }
        }
        private void InitChannels(ImperaContext context, User systemUser)
        {
            // Insert default chat channels
            if (context.Channels.FirstOrDefault(c => c.Name == "General") == null)
            {
                context.Channels.Add(new Channel
                {
                    Name = "General",
                    Type = ChannelType.General,
                    CreatedBy = systemUser
                });

                context.Channels.Add(new Channel
                {
                    Name = "Admin",
                    Type = ChannelType.Admin,
                    CreatedBy = systemUser
                });
            }

            context.SaveChanges();
        }