예제 #1
0
        protected virtual async Task RegisterExternalUserAsync(ExternalLoginInfo externalLoginInfo, string emailAddress)
        {
            await IdentityOptions.SetAsync();

            var user = new IdentityUser(GuidGenerator.Create(), emailAddress, emailAddress, CurrentTenant.Id);

            (await UserManager.CreateAsync(user)).CheckErrors();
            (await UserManager.AddDefaultRolesAsync(user)).CheckErrors();

            var userLoginAlreadyExists = user.Logins.Any(x =>
                                                         x.TenantId == user.TenantId &&
                                                         x.LoginProvider == externalLoginInfo.LoginProvider &&
                                                         x.ProviderKey == externalLoginInfo.ProviderKey);

            if (!userLoginAlreadyExists)
            {
                (await UserManager.AddLoginAsync(user, new UserLoginInfo(
                                                     externalLoginInfo.LoginProvider,
                                                     externalLoginInfo.ProviderKey,
                                                     externalLoginInfo.ProviderDisplayName
                                                     ))).CheckErrors();
            }

            await SignInManager.SignInAsync(user, isPersistent : true);
        }
        private async Task CreateUserAsync(string userName, string name, string surname, DataSeedContext context)
        {
            await _identityOptions.SetAsync();

            if ((await _identityUserRepository.FindByNormalizedUserNameAsync(_lookupNormalizer.NormalizeName(userName))) != null)
            {
                return;
            }

            var user = new IdentityUser(
                _guidGenerator.Create(),
                userName,
                userName + "@abp.io",
                context.TenantId
                );

            user.Name    = name;
            user.Surname = surname;

            await _identityUserManager.CreateAsync(user,
                                                   "1q2w3E*"
                                                   );

            await _identityUserManager.AddToRoleAsync(user, "admin");
        }
예제 #3
0
        protected virtual async Task RemoveWeChatAppUserAsync(IdentityUser identityUser, WeChatApp miniProgram)
        {
            var mpUserMapping = await _weChatAppUserRepository.GetAsync(x =>
                                                                        x.WeChatAppId == miniProgram.Id && x.UserId == identityUser.Id);

            await _weChatAppUserRepository.DeleteAsync(mpUserMapping, true);
        }
예제 #4
0
        protected virtual async Task RemoveMiniProgramUserAsync(IdentityUser identityUser, MiniProgram miniProgram)
        {
            var mpUserMapping = await _miniProgramUserRepository.GetAsync(x =>
                                                                          x.MiniProgramId == miniProgram.Id && x.UserId == identityUser.Id);

            await _miniProgramUserRepository.DeleteAsync(mpUserMapping, true);
        }
예제 #5
0
    protected virtual async Task <IdentityUser> CreateExternalUserAsync(ExternalLoginInfo info)
    {
        await IdentityOptions.SetAsync();

        var emailAddress = info.Principal.FindFirstValue(AbpClaimTypes.Email);

        var user = new IdentityUser(GuidGenerator.Create(), emailAddress, emailAddress, CurrentTenant.Id);

        CheckIdentityErrors(await UserManager.CreateAsync(user));
        CheckIdentityErrors(await UserManager.SetEmailAsync(user, emailAddress));
        CheckIdentityErrors(await UserManager.AddLoginAsync(user, info));
        CheckIdentityErrors(await UserManager.AddDefaultRolesAsync(user));

        user.Name    = info.Principal.FindFirstValue(AbpClaimTypes.Name);
        user.Surname = info.Principal.FindFirstValue(AbpClaimTypes.SurName);

        var phoneNumber = info.Principal.FindFirstValue(AbpClaimTypes.PhoneNumber);

        if (!phoneNumber.IsNullOrWhiteSpace())
        {
            var phoneNumberConfirmed = string.Equals(info.Principal.FindFirstValue(AbpClaimTypes.PhoneNumberVerified), "true", StringComparison.InvariantCultureIgnoreCase);
            user.SetPhoneNumber(phoneNumber, phoneNumberConfirmed);
        }

        await UserManager.UpdateAsync(user);

        return(user);
    }
        public override async Task <IdentityResult> CreateAsync(IdentityUser user)
        {
            /* We want to update a customized user property after a user created.
             * But we lack with this code. I tried many UOW combination without luck.
             * Maybe you can help us.
             * You have to uncomment below codes.. */

            IdentityResult identityResult;

            try
            {
                // Create a user.
                identityResult = await base.CreateAsync(user);

                user.SetProperty("DisplayName", user.UserName);
            }
            // Can not catch any exception like this!
            catch (Exception e)
            {
                Console.WriteLine(e);
                identityResult = IdentityResult.Failed();
            }

            return(identityResult);
        }
예제 #7
0
        protected virtual async Task RemoveUserInfoAsync(IdentityUser identityUser)
        {
            var userInfo = await _userInfoRepository.FindAsync(x => x.UserId == identityUser.Id);

            if (userInfo != null)
            {
                await _userInfoRepository.DeleteAsync(userInfo, true);
            }
        }
        protected virtual Task AddCustomClaimsAsync(List <Claim> customClaims, IdentityUser user, ExtensionGrantValidationContext context)
        {
            if (user.TenantId.HasValue)
            {
                customClaims.Add(new Claim(AbpClaimTypes.TenantId, user.TenantId?.ToString()));
            }

            return(Task.CompletedTask);
        }
        public override async Task <ClaimsPrincipal> CreateAsync(Volo.Abp.Identity.IdentityUser user)
        {
            ClaimsPrincipal principal = await base.CreateAsync(user);

            principal.Identities
            .First()
            .AddClaim(new Claim("merchant", "Angkor"));
            return(principal);
        }
예제 #10
0
    private async Task AddUsers()
    {
        var john = new IdentityUser(_testData.UserJohnId, "john.nash", "*****@*****.**");

        john.AddLogin(new UserLoginInfo("github", "john", "John Nash"));
        john.AddLogin(new UserLoginInfo("twitter", "johnx", "John Nash"));
        john.AddClaim(_guidGenerator, new Claim("TestClaimType", "42"));
        john.SetToken("test-provider", "test-name", "test-value");
        await _userRepository.InsertAsync(john);
    }
예제 #11
0
        protected override async Task <string> GetCacheKeyAsync(string purpose, UserManager <IdentityUser> manager,
                                                                IdentityUser user)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }

            var phoneNumber = await manager.GetPhoneNumberAsync(user);

            return("PhoneNumber:" + purpose + ":" + phoneNumber);
        }
예제 #12
0
        protected virtual async Task <IdentityUser> CreateExternalUserAsync(ExternalLoginInfo info)
        {
            var emailAddress = info.Principal.FindFirstValue(AbpClaimTypes.Email);

            var user = new IdentityUser(GuidGenerator.Create(), emailAddress, emailAddress, CurrentTenant.Id);

            CheckIdentityErrors(await UserManager.CreateAsync(user));
            CheckIdentityErrors(await UserManager.SetEmailAsync(user, emailAddress));
            CheckIdentityErrors(await UserManager.AddLoginAsync(user, info));

            return(user);
        }
예제 #13
0
        public virtual async Task <IdentityUser> CreateAsync(UserInfoModel userInfoModel, string loginProvider, string providerKey)
        {
            var identityUser = new IdentityUser(_guidGenerator.Create(), await GenerateUserNameAsync(userInfoModel),
                                                await GenerateEmailAsync(userInfoModel), _currentTenant.Id);

            CheckIdentityResult(await _identityUserManager.CreateAsync(identityUser));

            CheckIdentityResult(await _identityUserManager.AddDefaultRolesAsync(identityUser));

            CheckIdentityResult(await _identityUserManager.AddLoginAsync(identityUser,
                                                                         new UserLoginInfo(loginProvider, providerKey, "微信用户")));

            return(identityUser);
        }
예제 #14
0
        protected virtual async Task <IdentityUser> CreateExternalUserAsync(ExternalLoginInfo info)
        {
            var emailAddress = info.Principal.FindFirstValue(AbpClaimTypes.Email);

            var user = new IdentityUser(GuidGenerator.Create(), emailAddress, emailAddress, CurrentTenant.Id);

            CheckIdentityErrors(await UserManager.CreateAsync(user));
            CheckIdentityErrors(await UserManager.SetEmailAsync(user, emailAddress));
            CheckIdentityErrors(await UserManager.AddLoginAsync(user, info));
            //CheckIdentityErrors(await UserManager.AddClaimAsync(user, info.Principal.Claims.FirstOrDefault(x => x.Type == "http://schemas.microsoft.com/identity/claims/tenantid")));
            //CheckIdentityErrors(await UserManager.AddClaimAsync(user, info.Principal.Claims.FirstOrDefault(x => x.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")));

            return(user);
        }
예제 #15
0
        public async Task HandleEventAsync(CreateEventData eventData)
        {
            using (CurrentTenant.Change(eventData.Id, eventData.Name))
            {
                const string tenantAdminRoleName = "admin";
                var          tenantAdminRoleId   = Guid.Empty;;

                if (!await IdentityRoleManager.RoleExistsAsync(tenantAdminRoleName))
                {
                    tenantAdminRoleId = GuidGenerator.Create();
                    var tenantAdminRole = new IdentityRole(tenantAdminRoleId, tenantAdminRoleName, eventData.Id)
                    {
                        IsStatic = true,
                        IsPublic = true
                    };
                    (await IdentityRoleManager.CreateAsync(tenantAdminRole)).CheckErrors();
                }
                else
                {
                    var tenantAdminRole = await IdentityRoleManager.FindByNameAsync(tenantAdminRoleName);

                    tenantAdminRoleId = tenantAdminRole.Id;
                }

                var tenantAdminUser = await IdentityUserManager.FindByNameAsync(eventData.AdminEmailAddress);

                if (tenantAdminUser == null)
                {
                    tenantAdminUser = new IdentityUser(eventData.AdminUserId, eventData.AdminEmailAddress,
                                                       eventData.AdminEmailAddress, eventData.Id);

                    tenantAdminUser.AddRole(tenantAdminRoleId);

                    // 创建租户管理用户
                    (await IdentityUserManager.CreateAsync(tenantAdminUser)).CheckErrors();
                    (await IdentityUserManager.AddPasswordAsync(tenantAdminUser, eventData.AdminPassword)).CheckErrors();
                }
                //var identitySeedResult = await IdentityDataSeeder
                //   .SeedAsync(eventData.AdminEmailAddress, eventData.AdminPassword, eventData.Id);
                //if (!identitySeedResult.CreatedAdminUser)
                //{
                //    Logger.LogWarning("Tenant {0} admin user {1} not created!", eventData.Name, eventData.AdminEmailAddress);
                //}
                //if (!identitySeedResult.CreatedAdminRole)
                //{
                //    Logger.LogWarning("Tenant {0} admin role not created!", eventData.Name);
                //}
            }
        }
예제 #16
0
파일: Register.cshtml.cs 프로젝트: zxbe/abp
        [UnitOfWork] //TODO: Will be removed when we implement action filter
        public virtual async Task <IActionResult> OnPostAsync()
        {
            ValidateModel();

            await CheckSelfRegistrationAsync().ConfigureAwait(false);

            var user = new IdentityUser(GuidGenerator.Create(), Input.UserName, Input.EmailAddress, CurrentTenant.Id);

            (await UserManager.CreateAsync(user, Input.Password).ConfigureAwait(false)).CheckErrors();

            await UserManager.SetEmailAsync(user, Input.EmailAddress).ConfigureAwait(false);

            await SignInManager.SignInAsync(user, isPersistent : false).ConfigureAwait(false);

            return(Redirect(ReturnUrl ?? "/")); //TODO: How to ensure safety? IdentityServer requires it however it should be checked somehow!
        }
예제 #17
0
        protected virtual async Task TryCreateUserInfoAsync(IdentityUser identityUser, UserInfoModel userInfoModel)
        {
            var userInfo = await _userInfoRepository.FindAsync(x => x.UserId == identityUser.Id);

            if (userInfo == null)
            {
                userInfo = new UserInfo(GuidGenerator.Create(), CurrentTenant.Id, identityUser.Id, userInfoModel);

                await _userInfoRepository.InsertAsync(userInfo, true);
            }
            else
            {
                // 注意:2021年4月13日后,登录时获得的UserInfo将是匿名信息,非真实用户信息,因此不再覆盖更新
                // https://github.com/EasyAbp/WeChatManagement/issues/20
                // https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468bc52801
            }
        }
예제 #18
0
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public virtual async Task <IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
        {
            var user = new IdentityUser(
                GuidGenerator.Create(),
                input.UserName,
                input.Email,
                CurrentTenant.Id
                );

            input.MapExtraPropertiesTo(user);

            (await _userManager.CreateAsync(user, input.Password)).CheckErrors();

            await UpdateUserByInput(user, input);

            return(ObjectMapper.Map <IdentityUser, IdentityUserDto>(user));
        }
예제 #19
0
        public virtual async Task <IdentityUser> CreateAsync(string loginProvider, string providerKey)
        {
            await _identityOptions.SetAsync();

            var identityUser = new IdentityUser(_guidGenerator.Create(), await GenerateUserNameAsync(),
                                                await GenerateEmailAsync(), _currentTenant.Id);

            (await _identityUserManager.CreateAsync(identityUser)).CheckErrors();

            (await _identityUserManager.AddDefaultRolesAsync(identityUser)).CheckErrors();

            (await _identityUserManager.AddLoginAsync(identityUser,
                                                      new UserLoginInfo(loginProvider, providerKey,
                                                                        WeChatManagementCommonConsts.WeChatUserLoginInfoDisplayName))).CheckErrors();

            return(identityUser);
        }
예제 #20
0
        protected virtual async Task UpdateUserInfoAsync(IdentityUser identityUser, UserInfoModel userInfoModel)
        {
            var userInfo = await _userInfoRepository.FindAsync(x => x.UserId == identityUser.Id);

            if (userInfo == null)
            {
                userInfo = new UserInfo(GuidGenerator.Create(), CurrentTenant.Id, identityUser.Id, userInfoModel);

                await _userInfoRepository.InsertAsync(userInfo, true);
            }
            else
            {
                userInfo.UpdateInfo(userInfoModel);

                await _userInfoRepository.UpdateAsync(userInfo, true);
            }
        }
        public override async Task <IdentityResult> CreateAsync(IdentityUser user)
        {
            if (user.Email.IsNullOrWhiteSpace())
            {
                throw new AbpValidationException(
                          "Email is required for new users!",
                          new List <ValidationResult>
                {
                    new ValidationResult(
                        "Email can not be empty!",
                        new [] { "Email" }
                        )
                }
                          );
            }

            return(await base.CreateAsync(user));
        }
예제 #22
0
        public override async Task <ClaimsPrincipal> CreateAsync(IdentityUser _user)
        {
            var principal = await base.CreateAsync(_user);

            var identity = principal.Identities.First();

            var user = await MyUserManager.GetByIdAsync(_user.Id);

            if (user.Roles != null)
            {
                foreach (var item in user.Roles)
                {
                    identity.AddClaim(new Claim(JhJwtClaimTypes.RoleId, item.RoleId.ToString()));
                }
            }
            //identity.AddIfNotContains(new Claim(IdentityRoleExtension.PlatformType, platformType.ToString()));
            return(principal);
        }
예제 #23
0
        protected virtual async Task AddToUserLogins(IdentityUser user)
        {
            var externalLoginInfo = await SignInManager.GetExternalLoginInfoAsync();

            var userLoginAlreadyExists = user.Logins.Any(x =>
                                                         x.TenantId == user.TenantId &&
                                                         x.LoginProvider == externalLoginInfo.LoginProvider &&
                                                         x.ProviderKey == externalLoginInfo.ProviderKey);

            if (!userLoginAlreadyExists)
            {
                user.AddLogin(new UserLoginInfo(
                                  externalLoginInfo.LoginProvider,
                                  externalLoginInfo.ProviderKey,
                                  externalLoginInfo.ProviderDisplayName
                                  )
                              );
            }
        }
예제 #24
0
        public async Task SeedAsync(DataSeedContext context)
        {
            var admnistrator = UserManager.FindByNameAsync("admin");

            if (admnistrator != null)
            {
                return;
            }

            var user = new Volo.Abp.Identity.IdentityUser(
                _guidGenerator.Create(),
                "admin",
                "*****@*****.**"
                );

            user.Name = "administrator";
            await UserRepository.InsertAsync(user);

            return;
        }
예제 #25
0
        public virtual async Task <AppUser_Dto> RegisterAsync(RegisterDto input)
        {
            await CheckSelfRegistrationAsync();

            var user = new IdentityUser(GuidGenerator.Create(), input.UserName, input.EmailAddress, CurrentTenant.Id);

            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();

            await UserManager.SetEmailAsync(user, input.EmailAddress);

            await UserManager.AddDefaultRolesAsync(user);

            var appUser = await AppUserRepo.GetAsync(x => x.Id == user.Id);

            appUser.EmployeeId = input.EmployeeId;

            var result = await AppUserRepo.UpdateAsync(appUser);

            return(ObjectMapper.Map <AppUser, AppUser_Dto>(result));
        }
예제 #26
0
        protected override async Task <ClaimsPrincipal> GetUserClaimsAsync(IdentityUser user)
        {
            var claimsPrincipal = await base.GetUserClaimsAsync(user);

            var claims = new List <Claim>();

            claims.Add(new Claim(Volo.Abp.Security.Claims.AbpClaimTypes.PhoneNumber, user.PhoneNumber ?? ""));
            if (user.Roles != null)
            {
                foreach (var item in user.Roles)
                {
                    claims.Add(new Claim(JhJwtClaimTypes.RoleId, item.RoleId.ToString()));
                }
            }
            claims.Add(new Claim(Volo.Abp.Security.Claims.AbpClaimTypes.Name, user.Name ?? ""));
            claims.Add(new Claim(Volo.Abp.Security.Claims.AbpClaimTypes.SurName, user.Surname ?? ""));

            claimsPrincipal.Identities.First().AddClaims(claims);
            return(claimsPrincipal);
        }
예제 #27
0
        public virtual async Task <AppUserDto> RegisterAsync(UserCreateDto input)
        {
            //await CheckSelfRegistrationAsync();

            var user = new Volo.Abp.Identity.IdentityUser(GuidGenerator.Create(), input.UserName, input.EmailAddress, CurrentTenant.Id)
            {
                Name    = input.Name,
                Surname = input.Surname
            };

            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();

            await UserManager.SetEmailAsync(user, input.EmailAddress);

            await UserManager.SetPhoneNumberAsync(user, input.PhoneNumber);

            await UserManager.AddClaimAsync(user, new System.Security.Claims.Claim("sub", user.Id.ToString()));

            return(ObjectMapper.Map <Volo.Abp.Identity.IdentityUser, AppUserDto>(user));
        }
        public async Task <AuthenticationResult> ExternalLogin(FacebookUserInfoResult userInfo)
        {
            var user = await UserManager.FindByEmailAsync(userInfo.Email);

            var input = new LoginDto
            {
                userName = userInfo.Email,
                passWord = null
            };

            if (user == null)
            {
                var newuser = new Volo.Abp.Identity.IdentityUser(GuidGenerator.Create(), input.userName, input.userName);
                await UserManager.CreateAsync(newuser, input.passWord);

                return(await LoginAsync(input));
            }
            else
            {
                return(await GenerateAuthenticationResultForUserAsync(user));
            }
        }
예제 #29
0
        protected virtual async Task UpdateMiniProgramUserAsync(IdentityUser identityUser, MiniProgram miniProgram, string unionId, string openId, string sessionKey)
        {
            var mpUserMapping = await _miniProgramUserRepository.FindAsync(x =>
                                                                           x.MiniProgramId == miniProgram.Id && x.UserId == identityUser.Id);

            if (mpUserMapping == null)
            {
                mpUserMapping = new MiniProgramUser(GuidGenerator.Create(), CurrentTenant.Id, miniProgram.Id,
                                                    identityUser.Id, unionId, openId);

                await _miniProgramUserRepository.InsertAsync(mpUserMapping, true);
            }
            else
            {
                mpUserMapping.SetOpenId(openId);
                mpUserMapping.SetUnionId(unionId);

                mpUserMapping.UpdateSessionKey(sessionKey, Clock);

                await _miniProgramUserRepository.UpdateAsync(mpUserMapping, true);
            }
        }
        private async Task CreateUserWithExtraProperty()
        {
            //"test" user
            const string userName = "******";
            var          user     = await UserRepository.FindByNormalizedUserNameAsync(LookupNormalizer.NormalizeName(userName));

            if (user != null)
            {
                return;
            }

            user = new Volo.Abp.Identity.IdentityUser(
                GuidGenerator.Create(),
                userName,
                "*****@*****.**"
                )
            {
                Name = userName
            };
            user.SetProperty("WarehouseId", GuidGenerator.Create());
            (await UserManager.CreateAsync(user, "1q2w3E*")).CheckErrors();
        }