public async Task ThrowException_IfUsernameIsLessThanThreeSymbols()
        {
            var username = "******";
            var password = "******";
            var email    = "TestEmail";
            var role     = "TestRole";

            var loggerMock = new Mock <ILogger <UserService> >().Object;

            var options = TestUtilities.GetOptions(nameof(ThrowException_IfUsernameIsLessThanThreeSymbols));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                var accountDto = new RegisterAccountDto
                {
                    UserName = username,
                    Password = password,
                    Role     = role,
                    Email    = email
                };

                var accountService = new UserService(actContext, null, loggerMock);

                await accountService.RegisterAccountAsync(accountDto);
            }
        }
        public async Task ThrowExeptionWhenUserEmailIsMoreThanMaxLength_Test()
        {
            var username = "******";
            var password = "******";
            var email    = new String('T', 51);
            var role     = "Manager";

            var loggerMock = new Mock <ILogger <UserService> >().Object;

            var options = TestUtilities.GetOptions(nameof(ThrowExeptionWhenUserEmailIsMoreThanMaxLength_Test));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                var accountDto = new RegisterAccountDto
                {
                    UserName = username,
                    Password = password,
                    Role     = role,
                    Email    = email
                };

                var accountService = new UserService(actContext, null, loggerMock);

                await accountService.RegisterAccountAsync(accountDto);
            }
        }
Esempio n. 3
0
 public static void ValidatorUserName(RegisterAccountDto registerAccountDto)
 {
     if (registerAccountDto.UserName.Length < 3 || registerAccountDto.UserName.Length > 50)
     {
         throw new UserExeption("Username must be betweeen 3 and 50 symbols!");
     }
 }
        public async Task <IActionResult> RegisterAccount(RegisterAccountViewModel viewModel)
        {
            try
            {
                var registerAccountDto = new RegisterAccountDto
                {
                    CurrentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier),
                    UserName      = viewModel.UserName,
                    Password      = viewModel.Password,
                    Email         = viewModel.Email,
                    Role          = viewModel.Role
                };

                await this.service.RegisterAccountAsync(registerAccountDto);
            }
            catch (UserExeption ex)
            {
                return(View("Message", new MessageViewModel {
                    Message = ex.Message
                }));
            }

            return(View("Message", new MessageViewModel
            {
                Message = $"Successful registration",

                IsSuccess = true
            }));
        }
Esempio n. 5
0
 public static void ValidatorRoleName(RegisterAccountDto registerAccountDto)
 {
     if (registerAccountDto.Role != "Manager" && registerAccountDto.Role != "Operator")
     {
         throw new UserExeption("Wrong role name!");
     }
 }
Esempio n. 6
0
 public static void ValidatorPassword(RegisterAccountDto registerAccountDto)
 {
     if (registerAccountDto.Password.Length < 5 || registerAccountDto.Password.Length > 100)
     {
         throw new UserExeption("Password must be betweeen 5 and 100 symbols!");
     }
 }
Esempio n. 7
0
 public static void ValidatorForExistUsername(string username, RegisterAccountDto registerAccountDto)
 {
     if (username != null)
     {
         throw new UserExeption($"You cannot register accout with the following username {registerAccountDto.UserName}");
     }
 }
Esempio n. 8
0
        public void Register([FromBody] RegisterAccountDto model)
        {
            if (!_roleManager.RoleExistsAsync(Roles.Administrator).Result)
            {
                throw new ApplicationException(ExceptionMessages.RolesHaveNotBeenCreated);
            }

            var user = new ApplicationUser
            {
                UserName = model.Email,
                Email    = model.Email
            };

            var result = _userManager.CreateAsync(user, model.Password).Result;

            if (!result.Succeeded)
            {
                throw new ApplicationException(ExceptionMessages.UsernameAlreadyExists);
            }

            using (var dbContext = new ApplicationDbContext())
            {
                var appUser = _userManager.Users.SingleOrDefault(au => au.Email == model.Email);

                result = _userManager.AddToRoleAsync(appUser, Roles.Administrator).Result;

                if (!result.Succeeded)
                {
                    throw new ApplicationException(ExceptionMessages.InternalServerError);
                }

                if (string.IsNullOrWhiteSpace(model.Logo))
                {
                    model.Logo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAoBAMAAACMbPD7AAAAG1BMVEXMzMyWlpbFxcWjo6OqqqqxsbGcnJy+vr63t7eN+fR5AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAApElEQVQ4je2QsQrCQBBEJ5fLpt2AHxCJWCc2WkZFsTwx9kcQ0ypK6lR+t3eInWw6q3vVLrwdlgECgcAvVFXqy3dm7GvR1ubczMxnjjnZ7ESbclqmJZK6B54c3x6iHYGsslBdByyYMBft2BwZDLxcvuHIXUuoatu6bEwHFGDK5ewUhf8bJ4t7lhUjf9Nw8J2oduWW0U7Sq9ETX2Tvbaxr0Q4E/s8bo1sUV4qjWrAAAAAASUVORK5CYII=";
                }

                if (!dbContext.Cities.Any(c => c.Id == model.City))
                {
                    throw new ApplicationException(ExceptionMessages.BadRequest);
                }

                var clinic = new Clinic
                {
                    Name        = model.Name,
                    Description = model.Description,
                    CityId      = model.City,
                    Address     = model.Address,
                    Latitude    = model.Latitude,
                    Longitude   = model.Longitude,
                    UserId      = appUser.Id,
                    Logo        = model.Logo
                };

                dbContext.Clinics.Add(clinic);
                dbContext.SaveChanges();
            }
        }
Esempio n. 9
0
        public async Task <IActionResult> RegisterMod([FromBody] RegisterAccountDto model)
        {
            var result = await _accountService.RegisterModAccountAsync(model);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }

            return(Ok(result.Token));
        }
Esempio n. 10
0
        public static void ValidatorUserEmail(RegisterAccountDto registerAccountDto)
        {
            if (registerAccountDto.Email == null)
            {
                throw new UserExeption("Email cannot be null!");
            }

            if (registerAccountDto.Email.Length < 5 || registerAccountDto.Email.Length > 50)
            {
                throw new UserExeption("Email must be betweeen 5 and 50 symbols!");
            }
        }
Esempio n. 11
0
        private async Task <RegisterResult> Regist(RegisterAccountDto registerAccountModel)
        {
            var registModel = new RegisterModel()
            {
                Account  = registerAccountModel.UserAccount,
                Password = registerAccountModel.Password
            };

            var RegistResult = await authenticationService.Register(registModel);

            return(RegistResult);
        }
Esempio n. 12
0
        public async Task <ActionResult <UserRegisteredDto> > RegisterAccount([FromBody] RegisterAccountDto model)
        {
            var registerAccountModel = _mapper.Map <RegisterAccountModel>(model);
            var user = await _userLogic.RegisterAccount(registerAccountModel);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(user));
        }
Esempio n. 13
0
        public async Task <AccountResponse> RegisterModAccountAsync(RegisterAccountDto model)
        {
            Dictionary <string, string[]> errors = new Dictionary <string, string[]>();
            UserAccount UserAdmin = _context.Users.FirstOrDefault(e => e.Email == _userName || e.UserName == _userName);
            UserAccount userr     = _context.Users.FirstOrDefault(e => e.Email == model.Email || e.UserName == model.UserName);

            if (UserAdmin.Rola != "admin" && UserAdmin.Rola != "moderator")
            {
                errors.Add("Rola", new[] { "NIe masz tutaj dostępu" });
                return(new AccountResponse(errors));
            }
            if (userr != null)
            {
                errors.Add("Emial", new[] { "Email jets juz zajety" });
                return(new AccountResponse(errors));
            }

            userr = _context.Users.FirstOrDefault(e => e.NormalizedUserName == model.UserName.ToUpper());
            if (userr != null)
            {
                errors.Add("Useranme", new[] { "Nazwa uzytkoniwka jest juz zajeta" });
                return(new AccountResponse(errors));
            }

            UserAccount user = _mapper.Map <RegisterAccountDto, UserAccount>(model);

            var result = await _userManager.CreateAsync(user, model.Password);

            string rola = "moderator";

            user.Rola = rola;
            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    errors.Add(error.Code, new[] { error.Description });
                }

                return(new AccountResponse(errors));
            }

            _context.SaveChanges();

            UserAccount appUser  = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
            JwtTokenDto response = new JwtTokenDto
            {
                Token = GenerateJwtToken(model.Email, appUser)
            };

            return(new AccountResponse(response));
        }
        public async Task <IActionResult> Register([FromBody] RegisterAccountDto item)
        {
            var account = await _accountRepository.GetByUserName(item.UserName);

            if (account != null)
            {
                return(Error($"Account with username :{item.UserName} already registered."));
            }

            await _accountRepository.CreateAccount(new UserAccounts
            {
                UserName = item.UserName,
                Password = item.Password.ToSha256(),
                Role     = item.Role
            });

            return(Ok());
        }
Esempio n. 15
0
        public async Task <IActionResult> Register(RegisterAccountDto registerDtoViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerDtoViewModel));
            }
            var checkUser = await _userManager.FindByNameAsync(registerDtoViewModel.UserName);

            if (checkUser != null)
            {
                ViewBag.RegisterError = $"Tài khoản {registerDtoViewModel.UserName} đã tồn tại!";
                return(View(registerDtoViewModel));
            }
            var checkEmail = await _userManager.FindByEmailAsync(registerDtoViewModel.Email);

            if (checkEmail != null)
            {
                ViewBag.RegisterError = $"Email {registerDtoViewModel.Email} đã được sử dụng!";
                return(View(registerDtoViewModel));
            }
            AppUser newUser = new AppUser(registerDtoViewModel.UserName)
            {
                Email = registerDtoViewModel.Email
            };
            var createUserResult = await _userManager.CreateAsync(newUser, registerDtoViewModel.Password);

            if (!createUserResult.Succeeded)
            {
                ViewBag.RegisterError = $"Có lỗi khi tạo tài khoản, xin vui lòng liên hệ quản trị viên!";
                return(View(registerDtoViewModel));
            }
            await SendEmailConfirmationLink(newUser, registerDtoViewModel.ReturnUrl);

            var context = await _identityServerInteractionService
                          .GetAuthorizationContextAsync(registerDtoViewModel.ReturnUrl);

            if (context != null && string.Equals(context.ClientId, "mvc_admin"))
            {
                return(Redirect(_configuration["AdminHost"]));
            }
            return(Redirect(_configuration["ClientHost"]));
        }
Esempio n. 16
0
        private async Task AutoLogin(RegisterAccountDto registerAccountModel)
        {
            ToastSuccess("注册成功,即将自动登录...");
            var loginModel = new LoginModel
            {
                Password = registerAccountModel.Password,
                Username = registerAccountModel.UserAccount
            };
            var loginResult = await authenticationService.Login(loginModel);

            if (loginResult.Successful)
            {
                await  NavigateToReturnUrl();
            }
            else
            {
                foreach (var item in loginResult.Errors)
                {
                    ToastError(item);
                }
            }
        }
Esempio n. 17
0
        public async Task RegisterAccountAsync(RegisterAccountDto registerAccountDto)
        {
            ValidatorUserService.ValidatorRoleName(registerAccountDto);
            ValidatorUserService.ValidatorUserName(registerAccountDto);
            ValidatorUserService.ValidatorPassword(registerAccountDto);
            ValidatorUserService.ValidatorUserEmail(registerAccountDto);

            var user = await this.context.Users
                       .Where(name => name.UserName == registerAccountDto.UserName)
                       .Select(username => username.UserName)
                       .SingleOrDefaultAsync();

            ValidatorUserService.ValidatorForExistUsername(user, registerAccountDto);

            var passwordHasher = new PasswordHasher <User>();

            var account = new User
            {
                UserName           = registerAccountDto.UserName,
                NormalizedUserName = registerAccountDto.UserName.ToUpper(),
                LockoutEnabled     = true,
                Email           = registerAccountDto.Email,
                NormalizedEmail = registerAccountDto.Email.ToUpper()
            };

            account.PasswordHash = passwordHasher.HashPassword(account, registerAccountDto.Password);

            await this.userManager.CreateAsync(account);

            await this.userManager.AddToRoleAsync(account, registerAccountDto.Role);

            var currentUser = await this.context.Users
                              .Where(userId => userId.Id == registerAccountDto.CurrentUserId)
                              .Select(uName => uName.UserName)
                              .SingleOrDefaultAsync();

            logger.LogInformation($"New user {registerAccountDto.UserName} registered by {currentUser}");
        }
        public async Task ThrowException_IfUsernameIsТaken()
        {
            var username = "******";
            var password = "******";
            var email    = "TestEmail";
            var role     = "TestRole";

            var loggerMock = new Mock <ILogger <UserService> >().Object;

            var options = TestUtilities.GetOptions(nameof(ThrowException_IfUsernameIsТaken));

            using (var actContext = new E_MailApplicationsManagerContext(options))
            {
                var user = await actContext.Users.AddAsync(
                    new User
                {
                    UserName           = username,
                    NormalizedUserName = username.ToUpper(),
                    LockoutEnabled     = true
                });

                await actContext.SaveChangesAsync();

                var accountDto = new RegisterAccountDto
                {
                    UserName = username,
                    Password = password,
                    Role     = role,
                    Email    = email
                };

                var accountService = new UserService(actContext, null, loggerMock);

                await accountService.RegisterAccountAsync(accountDto);
            }
        }