Beispiel #1
0
        private void SetupCreation(IdentityUser identity, int numCurrentUsers)
        {
            var users = new List <IdentityUser>();

            for (var i = 0; i < numCurrentUsers; i++)
            {
                users.Add(CreatePendingUser(i.ToString()));
            }

            A.CallTo(() => userManager.Users)
            .Returns(users.AsQueryable());

            A.CallTo(() => userFactory.Create(identity.Email))
            .Returns(identity);
        }
Beispiel #2
0
        public static async Task <IUser> CreateAsync(this UserManager <IUser> userManager, IUserFactory factory, string email, string displayName, string password)
        {
            var user = factory.Create(email);

            user.UpdateDisplayName(displayName);
            user.SetPictureUrlFromGravatar(email);

            await DoChecked(() => userManager.CreateAsync(user), "Cannot create user.");

            if (!string.IsNullOrWhiteSpace(password))
            {
                await DoChecked(() => userManager.AddPasswordAsync(user, password), "Cannot create user.");
            }

            return(user);
        }
Beispiel #3
0
        public void CreateUser_CallIUserRepositoryAdd(
            [Frozen] IUserRepository userRepository,
            [Frozen] IUserFactory userFactory,
            CreateUserCommand message,
            User user,
            CreateUserCommandHandler createUserCommandHandler)
        {
            //Information
            A.CallTo(() => userFactory.Create(message.User)).Returns(user);

            //Act
            createUserCommandHandler.ExecuteAsync(message);

            //Test
            A.CallTo(() => userRepository.Add(user)).MustHaveHappened();
        }
Beispiel #4
0
    public void Register(UserRegisterCommand command)
    {
        using (var transactin = new TransactionScope())
        {
            var userName = new UserName(command.Name);
            var user     = userFactory.Create(userName);

            if (userService.Exists(user))
            {
                throw new CanNotRegisterUserException(user, "ユーザは既に存在しています。");
            }

            userRepository.Save(user);
            transaction.Complete *(; )
        }
    }
Beispiel #5
0
        public Task <UserRegisterOutputData> Handle(UserRegisterCommand command, CancellationToken cancellationToken)
        {
            using var transaction = new TransactionScope();

            var user = _userFactory.Create(command.Name);

            if (_userService.Exists(user))
            {
                throw new CanNotUserRegisterException($"名前が { user.Name.Value } のユーザーは既に存在します。");
            }

            _userRepository.Save(user);

            transaction.Complete();

            return(Task.FromResult(new UserRegisterOutputData(user.Id.Value)));
        }
Beispiel #6
0
        public IActionResult Register([FromForm] RegisterViewModel inputRegister, [FromServices] IUserFactory userFactory)
        {
            if (ModelState.IsValid)
            {
                var user = _userAppService.FirstOrDefault(u => u.Email == inputRegister.Email);

                if (user != null)
                {
                    _notificationService.AddErrorToastMessage("Já existe um usuário com o e-mail cadastrado!", new ToastrOptions
                    {
                        CloseButton = true,
                        Title       = "Usuario Existente"
                    });

                    return(View());
                }

                var newPassword = Helpers.Helpers.GenerateHashSHA256($"{inputRegister.Password}{inputRegister.Salt}");

                var newUser = userFactory.Create(inputRegister.Email, newPassword, inputRegister.Salt, inputRegister.FirstName, inputRegister.LastName);

                _userAppService.Add(newUser);

                if (_unitOfWorkAppService.Complete() == 1)
                {
                    _notificationService.AddErrorToastMessage($"Usuário {inputRegister.Email} registrado com sucesso!", new ToastrOptions
                    {
                        CloseButton = true,
                        Title       = "Novo Usuário Registrado"
                    });

                    return(RedirectToAction("Login"));
                }

                return(RedirectToAction("Login"));
            }

            _notificationService.AddErrorToastMessage("Ocorreu um erro ao criar o usuário.", new ToastrOptions
            {
                CloseButton = true,
                Title       = "Erro ao Criar Usuário"
            });

            return(View());
        }
        public UserRegisterResult Register(UserRegisterCommand command)
        {
            using (var transaction = new TransactionScope())
            {
                var name = new UserName(command.Name);
                var user = userFactory.Create(name);
                if (userService.Exists(user))
                {
                    throw new CanNotRegisterUserException(user, "이미 등록된 사용자임");
                }

                userRepository.Save(user);

                transaction.Complete();

                return(new UserRegisterResult(user.Id.Value));
            }
        }
Beispiel #8
0
        public UserRegisterOutputData Handle(UserRegisterInputData inputData)
        {
            using var transaction = new TransactionScope();

            var name = new UserName(inputData.Name);
            var user = userFactory.Create(name);

            if (userService.Exists(user))
            {
                throw new CanNotRegisterUserException(user, "이미 등록된 사용자임");
            }

            userRepository.Save(user);

            transaction.Complete();

            return(new UserRegisterOutputData(user.Id.Value));
        }
Beispiel #9
0
        public void Register(UserRegisterCommand command)
        {
            // コネクションからトランザクションを開始
            using (var transaction = connection.BeginTransaction())
            {
                var name = new UserName(command.Name);
                var user = userFactory.Create(name);

                if (userService.Exists(user))
                {
                    throw new CanNotRegisterUserException(user, "ユーザは既に存在しています。");
                }

                userRepository.Save(user);
                // 完了時にコミットを行う
                transaction.Commit();
            }
        }
Beispiel #10
0
        public void CreateUser_(
            [Frozen] IUserRepository userRepository,
            [Frozen] IUserFactory userFactory,
            CreateUserCommandHandler createUserCommandHandler,
            User user,
            UserController userController
            )
        {
            //Information
            A.CallTo(() => userFactory.Create(A <User> .Ignored)).Returns(user);

            //Act
            createUserCommandHandler.ExecuteAsync(new CreateUserCommand(user));

            //Test
            A.CallTo(() => userRepository.Add(user))
            .MustHaveHappenedOnceExactly();
        }
Beispiel #11
0
        public void Register(UserRegisterCommand command)
        {
            // 커넥션을 통해 트랜잭션을 시작
            using (var transaction = connection.BeginTransaction())
            {
                var name = new UserName(command.Name);
                var user = userFactory.Create(name);

                if (userService.Exists(user))
                {
                    throw new CanNotRegisterUserException(user, "이미 등록된 사용자임");
                }

                userRepository.Save(user);
                // 처리가 완료되면 커밋
                transaction.Commit();
            }
        }
        public void Register(UserRegisterCommand command)
        {
            // トランザクションスコープを生成する
            // using句のスコープ内でコネクションが開かれると自動的にトランザクションが開始される
            using (var transaction = new TransactionScope())
            {
                var name = new UserName(command.Name);
                var user = userFactory.Create(name);

                if (userService.Exists(user))
                {
                    throw new CanNotRegisterUserException(user, "ユーザは既に存在しています。");
                }

                userRepository.Save(user);
                // 処理を反映する際にはコミット処理を行う
                transaction.Complete();
            }
        }
Beispiel #13
0
        public void Register(UserRegisterCommand command)
        {
            // 트랜잭션 범위를 생성함
            // using 문의 범위 안에서 커넥션을 열면 자동으로 트랜잭션이 시작된다
            using (var transaction = new TransactionScope())
            {
                var name = new UserName(command.Name);
                var user = userFactory.Create(name);

                if (userService.Exists(user))
                {
                    throw new CanNotRegisterUserException(user, "이미 등록된 사용자임");
                }

                userRepository.Save(user);
                // 실제 데이터에 반영하기 위해 커밋
                transaction.Complete();
            }
        }
Beispiel #14
0
        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            IUser user = await userFactory.Create(messageEventArgs.Message.From.Id).ConfigureAwait(false);

            IInteractor interactor = await interactorFactory.Create(user, botClient).ConfigureAwait(false);

            IMessage message = messageFactory.Create(messageEventArgs);

            await interactor.Execute(message).ConfigureAwait(false);


            //var message = messageEventArgs.Message;
            //if (message?.Type == MessageType.Text) {

            //	await client.DeleteMessageAsync(message.Chat.Id, message.MessageId).ConfigureAwait(false);

            //	await client.SendTextMessageAsync(message.Chat.Id, message.Text);
            //}
        }
Beispiel #15
0
        public async Task <bool> CreateUserIfNotExists(string email)
        {
            var user = userFactory.Create(email);

            try
            {
                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.UpdateAsync(user, new UserValues { DisplayName = email });
                }

                return(result.Succeeded);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #16
0
        private IUser CreateUser(ExternalLoginInfo externalLogin, string email)
        {
            var user = userFactory.Create(email);

            foreach (var squidexClaim in externalLogin.Principal.GetSquidexClaims())
            {
                user.AddClaim(squidexClaim);
            }

            if (!user.HasPictureUrl())
            {
                user.SetPictureUrl(GravatarHelper.CreatePictureUrl(email));
            }

            if (!user.HasDisplayName())
            {
                user.SetDisplayName(email);
            }

            return(user);
        }
Beispiel #17
0
        private IUser CreateUser(ExternalLoginInfo externalLogin, string email)
        {
            var user = userFactory.Create(email);

            if (!externalLogin.Principal.HasClaim(x => x.Type == SquidexClaimTypes.SquidexPictureUrl))
            {
                user.SetClaim(SquidexClaimTypes.SquidexPictureUrl, GravatarHelper.CreatePictureUrl(email));
            }

            if (!externalLogin.Principal.HasClaim(x => x.Type == SquidexClaimTypes.SquidexDisplayName))
            {
                user.SetClaim(SquidexClaimTypes.SquidexDisplayName, email);
            }

            foreach (var squidexClaim in externalLogin.Principal.Claims.Where(c => c.Type.StartsWith(SquidexClaimTypes.Prefix)))
            {
                user.AddClaim(squidexClaim);
            }

            return(user);
        }
Beispiel #18
0
        private async Task <IUser> GetUser()
        {
            IUser         user;
            IEmailAddress emailAddress = null;

            using (ILifetimeScope scope = _container.BeginLifetimeScope())
            {
                string               subscriber          = User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
                IUserFactory         userFactory         = scope.Resolve <IUserFactory>();
                IEmailAddressFactory emailAddressFactory = scope.Resolve <IEmailAddressFactory>();
                SettingsFactory      settingsFactory     = scope.Resolve <SettingsFactory>();
                user = await userFactory.GetByReferenceId(settingsFactory.CreateAccount(_settings.Value), subscriber);

                if (user == null)
                {
                    string email = User.Claims.First(c => c.Type == ClaimTypes.Email).Value;
                    emailAddress = await emailAddressFactory.GetByAddress(settingsFactory.CreateAccount(_settings.Value), email);

                    if (emailAddress == null)
                    {
                        emailAddress = emailAddressFactory.Create(email);
                        IEmailAddressSaver emailAddressSaver = scope.Resolve <IEmailAddressSaver>();
                        await emailAddressSaver.Create(settingsFactory.CreateAccount(_settings.Value), emailAddress);
                    }
                    user      = userFactory.Create(subscriber, emailAddress);
                    user.Name = User.Claims.First(c => string.Equals(c.Type, "name", StringComparison.OrdinalIgnoreCase)).Value;
                    SetSuperUser(user);
                    IUserSaver userSaver = scope.Resolve <IUserSaver>();
                    await userSaver.Create(settingsFactory.CreateAccount(_settings.Value), user);
                }
                else
                {
                    user.Name = User.Claims.First(c => string.Equals(c.Type, "name", StringComparison.OrdinalIgnoreCase)).Value;
                    SetSuperUser(user);
                    IUserSaver userSaver = scope.Resolve <IUserSaver>();
                    await userSaver.Update(settingsFactory.CreateAccount(_settings.Value), user);
                }
            }
            return(user);
        }
Beispiel #19
0
        public IUser GetUser(long chatId)
        {
            if (IsUserAuthorized(chatId))
            {
                return(authorizedUsers[chatId]);
            }

            if (IsUserExist(chatId))
            {
                using (UsersContext db = new UsersContext())
                {
                    UserModel userModel = db.Users
                                          .Where(user => user.ChatId == chatId)
                                          .First();

                    IUser user = userFactory.Create(userModel.ChatId, userModel.HashPassword);
                    return(user);
                }
            }

            return(null);
        }
Beispiel #20
0
        public List <UserDTO> GetRestaurantUsersById(int restaurantId)
        {
            var restaurant      = _uow.Restaurants.Find(restaurantId);
            var restaurantUsers = _uow.RestaurantUsers.FindAllByRestaurantId(restaurant.RestaurantId);

            if (restaurantUsers == null)
            {
                return(null);
            }
            List <UserDTO> users = new List <UserDTO>();

            foreach (var restaurantUser in restaurantUsers)
            {
                var user = _uow.Users.Find(restaurantUser.UserId);
                if (user != null)
                {
                    var userObject = _userFactory.Create(user);
                    users.Add(userObject);
                }
            }
            return(users);
        }
Beispiel #21
0
        public static async Task <UserWithClaims> CreateAsync(this UserManager <IdentityUser> userManager, IUserFactory factory, UserValues values)
        {
            var user = factory.Create(values.Email);

            try
            {
                await DoChecked(() => userManager.CreateAsync(user));
                await DoChecked(() => values.SyncClaims(userManager, user));

                if (!string.IsNullOrWhiteSpace(values.Password))
                {
                    await DoChecked(() => userManager.AddPasswordAsync(user, values.Password));
                }
            }
            catch
            {
                await userManager.DeleteAsync(user);

                throw;
            }

            return((await userManager.ResolveUserAsync(user)) !);
        }
        public async Task <IResult <long> > AddAsync(UserModel model)
        {
            var validation = await new AddUserModelValidator().ValidationAsync(model);

            if (validation.Failed)
            {
                return(Result <long> .Fail(validation.Message));
            }

            var authResult = await _authService.AddAsync(model.Auth);

            if (authResult.Failed)
            {
                return(Result <long> .Fail(authResult.Message));
            }

            var user = _userFactory.Create(model, authResult.Data);

            await _userRepository.AddAsync(user);

            await _unitOfWork.SaveChangesAsync();

            return(Result <long> .Success(user.Id));
        }
Beispiel #23
0
        public async Task <IUser> CreateAsync(string email, UserValues?values = null, bool lockAutomatically = false,
                                              CancellationToken ct            = default)
        {
            Guard.NotNullOrEmpty(email);

            var user = userFactory.Create(email);

            try
            {
                var isFirst = !userManager.Users.Any();

                await userManager.CreateAsync(user).Throw(log);

                values ??= new UserValues();
                values.Roles ??= new HashSet <string>();

                if (string.IsNullOrWhiteSpace(values.DisplayName))
                {
                    values.DisplayName = email;
                }

                if (isFirst)
                {
                    values.Roles.Add(NotifoRoles.HostAdmin);
                }

                await userManager.SyncClaims(user, values).Throw(log);

                if (!string.IsNullOrWhiteSpace(values.Password))
                {
                    await userManager.AddPasswordAsync(user, values.Password).Throw(log);
                }

                foreach (var role in values.Roles)
                {
                    await userManager.AddToRoleAsync(user, role).Throw(log);
                }

                if (!isFirst && lockAutomatically)
                {
                    await userManager.SetLockoutEndDateAsync(user, LockoutDate()).Throw(log);
                }
            }
            catch (Exception)
            {
                try
                {
                    if (userFactory.IsId(user.Id))
                    {
                        await userManager.DeleteAsync(user);
                    }
                }
                catch (Exception ex2)
                {
                    log.LogError(ex2, "Failed to cleanup user after creation failed.");
                }

                throw;
            }

            var resolved = await ResolveAsync(user);

            foreach (var @events in userEvents)
            {
                await @events.OnUserRegisteredAsync(resolved);
            }

            if (HasConsentGiven(values, null !))
            {
                foreach (var @events in userEvents)
                {
                    await @events.OnConsentGivenAsync(resolved);
                }
            }

            return(resolved);
        }
Beispiel #24
0
        public void Execute(string username, string password)
        {
            var user = _factory.Create(username, password);

            _dbCommand.Execute(user);
        }
Beispiel #25
0
        public async Task <IActionResult> ExternalCallback(string?returnUrl = null)
        {
            var externalLogin = await signInManager.GetExternalLoginInfoWithDisplayNameAsync();

            if (externalLogin == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            var result = await signInManager.ExternalLoginSignInAsync(externalLogin.LoginProvider, externalLogin.ProviderKey, true);

            if (!result.Succeeded && result.IsLockedOut)
            {
                return(View(nameof(LockedOut)));
            }

            var isLoggedIn = result.Succeeded;

            UserWithClaims?user;

            if (isLoggedIn)
            {
                user = await userManager.FindByLoginWithClaimsAsync(externalLogin.LoginProvider, externalLogin.ProviderKey);
            }
            else
            {
                var email = externalLogin.Principal.FindFirst(ClaimTypes.Email).Value;

                user = await userManager.FindByEmailWithClaimsAsync(email);

                if (user != null)
                {
                    isLoggedIn =
                        await AddLoginAsync(user, externalLogin) &&
                        await AddClaimsAsync(user, externalLogin, email) &&
                        await LoginAsync(externalLogin);
                }
                else
                {
                    user = new UserWithClaims(userFactory.Create(email), new List <Claim>());

                    var isFirst = userManager.Users.LongCount() == 0;

                    isLoggedIn =
                        await AddUserAsync(user) &&
                        await AddLoginAsync(user, externalLogin) &&
                        await AddClaimsAsync(user, externalLogin, email, isFirst) &&
                        await LockAsync(user, isFirst) &&
                        await LoginAsync(externalLogin);

                    userEvents.OnUserRegistered(user);

                    if (await userManager.IsLockedOutAsync(user.Identity))
                    {
                        return(View(nameof(LockedOut)));
                    }
                }
            }

            if (!isLoggedIn)
            {
                return(RedirectToAction(nameof(Login)));
            }
            else if (user != null && !user.HasConsent() && !identityOptions.NoConsent)
            {
                return(RedirectToAction(nameof(Consent), new { returnUrl }));
            }
            else
            {
                return(RedirectToReturnUrl(returnUrl));
            }
        }
Beispiel #26
0
 public IUser Create(string name)
 {
     return(m_factory.Create(name));
 }
Beispiel #27
0
 private User Map(UserRecord rec) => factory.Create(rec.Id, rec.Username, rec.Email, rec.PasswordHash, rec.JoinedDate, rec.PostKarma, rec.CommentKarma);
Beispiel #28
0
        public bool Execute(string emailAddress)
        {
            var user = _factory.Create(emailAddress);

            return(_dbQuery.Execute(user));
        }
Beispiel #29
0
        public async Task <IUser> CreateAsync(string email, UserValues?values = null, bool lockAutomatically = false)
        {
            Guard.NotNullOrEmpty(email, nameof(email));

            var isFirst = !userManager.Users.Any();

            var user = userFactory.Create(email);

            try
            {
                await userManager.CreateAsync(user).Throw(log);

                values ??= new UserValues();

                if (string.IsNullOrWhiteSpace(values.DisplayName))
                {
                    values.DisplayName = email;
                }

                if (isFirst)
                {
                    var permissions = values.Permissions?.ToIds().ToList() ?? new List <string>();

                    permissions.Add(Permissions.Admin);

                    values.Permissions = new PermissionSet(permissions);
                }

                await userManager.SyncClaims(user, values).Throw(log);

                if (!string.IsNullOrWhiteSpace(values.Password))
                {
                    await userManager.AddPasswordAsync(user, values.Password).Throw(log);
                }

                if (!isFirst && lockAutomatically)
                {
                    await userManager.SetLockoutEndDateAsync(user, LockoutDate()).Throw(log);
                }
            }
            catch (Exception)
            {
                try
                {
                    if (userFactory.IsId(user.Id))
                    {
                        await userManager.DeleteAsync(user);
                    }
                }
                catch (Exception ex2)
                {
                    log.LogError(ex2, w => w
                                 .WriteProperty("action", "CleanupUser")
                                 .WriteProperty("status", "Failed"));
                }

                throw;
            }

            var resolved = await ResolveAsync(user);

            foreach (var @events in userEvents)
            {
                @events.OnUserRegistered(resolved);
            }

            if (HasConsentGiven(values, null !))
            {
                foreach (var @events in userEvents)
                {
                    @events.OnConsentGiven(resolved);
                }
            }

            return(resolved);
        }