Esempio n. 1
0
        public JsonResult Register(RegisterUserInput input)
        {
            //TODO: Return better exception messages!
            //TODO: Show captcha after filling register form, not on startup!

            if (!ModelState.IsValid)
            {
                throw new UserFriendlyException("Your form is invalid!");
            }

            var recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                throw new UserFriendlyException("Captcha answer cannot be empty.");
            }

            var recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                throw new UserFriendlyException("Incorrect captcha answer.");
            }

            input.ProfileImage = ProfileImageHelper.GenerateRandomProfileImage();

            _userAppService.RegisterUser(input);

            return(Json(new AbpMvcAjaxResponse {
                TargetUrl = Url.Action("ActivationInfo")
            }));
        }
Esempio n. 2
0
        public async Task <ActionResult> Register(RegisterUserInput registerUser)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var user = new IdentityUser
                {
                    UserName       = registerUser.Email,
                    Email          = registerUser.Email,
                    EmailConfirmed = true
                };

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

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    return(Ok(GenerateToken()));
                }

                return(BadRequest(string.Join(",", result.Errors.Select(s => s.Description))));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 3
0
        public async Task <AuthenticationPayload> RegisterAsync(RegisterUserInput input, [ScopedService] GeoDbContext context)
        {
            var existingUser = context.Users
                               .Where(i => i.Email.ToLower() == input.Email.ToLower())
                               .SingleOrDefault();

            if (existingUser != null)
            {
                return(new AuthenticationPayload(null, "User with this email address already exists"));
            }


            var salt    = HashHelper.GenerateSalt();
            var newUser = new User
            {
                Email = input.Email,
                Salt  = salt,
                Hash  = HashHelper.GenerateHash(salt, input.Password)
            };

            var createdUser = await context.Users.AddAsync(newUser);

            await context.SaveChangesAsync();

            return(GenerateAuthenticationResultForUser(newUser));
        }
        /// <summary>
        /// The Execute
        /// </summary>
        /// <param name="input">The input<see cref="RegisterUserInput"/></param>
        /// <returns>The <see cref="Task"/></returns>
        public async Task Execute(RegisterUserInput input)
        {
            if (input is null)
            {
                _outputPort.WriteError(Messages.InputIsNull);
                _logger.LogInformation("Input is null");
                return;
            }


            _logger.LogInformation("Validation ok, Registering new user detail..");

            input.User.Guid = Guid.NewGuid().ToString();

            await _userRepository.Insert(input.User);

            var lastInsertedId = 1;

            if (lastInsertedId <= 0)
            {
                _logger.LogInformation(Messages.CouldNotRegister);
                this._outputPort.NotFound(Messages.CouldNotRegister);

                return;
            }

            var output = new RegisterUserOutput
            {
                Id = lastInsertedId
            };

            _outputPort.Standard(output);
        }
 public async Task <ResponseData <ValidateUserResult> > RegisterUser(
     [FromBody] RegisterUserInput registerUserInput)
 {
     try
     {
         if (User.Identity.IsAuthenticated)
         {
             if (User.Claims.Single(r => r.Type == "role").Value ==
                 Startup.Configuration.GetSection("AccessLevel").GetSection("AccessLevel1").Value)
             {
                 if (ModelState.IsValid)
                 {
                     return(await manageUserRepository.RegisterUser(registerUserInput.userName,
                                                                    registerUserInput.userPasswordHash, registerUserInput.userRoleID,
                                                                    registerUserInput.userFirstName, registerUserInput.userLastName,
                                                                    registerUserInput.userEmail));
                 }
                 else
                 {
                     return(new ResponseData <ValidateUserResult>()
                     {
                         responseCode = (int)ResponseStatusEnum.BadRequest,
                         responseStatusDescription = "Bad Request",
                         responseResults = null
                     });
                 }
             }
             else
             {
                 return(new ResponseData <ValidateUserResult>()
                 {
                     responseCode = (int)ResponseStatusEnum.AuthorizationFail,
                     responseStatusDescription = "Authorization Fail",
                     responseResults = null
                 });
             }
         }
         else
         {
             return(new ResponseData <ValidateUserResult>()
             {
                 responseCode = (int)ResponseStatusEnum.AuthenticationFail,
                 responseStatusDescription = "Authentication Fail",
                 responseResults = null
             });
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message.ToString());
         return(new ResponseData <ValidateUserResult>()
         {
             responseCode = (int)ResponseStatusEnum.APIError,
             responseStatusDescription = "API Error",
             responseResults = null
         });
     }
 }
Esempio n. 6
0
        public async Task <IActionResult> Register(RegisterUserInput input)
        {
            if (ModelState.IsValid)
            {
                await _userService.RegisterUser(input);

                return(RedirectToAction("Login"));
            }
            return(View(input));
        }
Esempio n. 7
0
        public async Task <ApiResult> RegisterUser([FromBody] RegisterUserInput input)
        {
            var newUser = new User
            {
                UserName = input.UserName,
                Email    = input.Email
            };

            await userService.AddUser(newUser, input.Password, "user", CancellationToken.None);

            return(ApiResult.SuccessResult);
        }
Esempio n. 8
0
        public async Task <IActionResult> RegisterUser(RegisterUserRequest request)
        {
            if (request.Password != request.ConfirmPassword)
            {
                // TODO use FluentValidation
                return(BadRequest("Password and ConfirmPassword does not match"));
            }
            var registerUserInput = new RegisterUserInput(request.FirstName, request.LastName, request.Username, request.Email, request.Password);
            await _registerInputHandler.HandleAsync(registerUserInput, _registerOutputHandler);

            return(_registerOutputHandler.Result());
        }
        public async Task <IResult <IAccessTokenOutput> > Handle(RegisterUserInput userInput, CancellationToken cancellationToken)
        {
            var validationResult = Validator.Validate(userInput);

            if (validationResult.Errors.Count > 0)
            {
                return(new Result <IAccessTokenOutput>(validationResult.Errors));
            }

            var user = new User
            {
                Email         = userInput.UserName,
                UserName      = userInput.UserName,
                FirstName     = userInput.FirstName,
                LastName      = userInput.LastName,
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var identityResult = await UserService.CreateAsync(user, userInput.Password, cancellationToken);

            if (!identityResult.Succeeded)
            {
                return(new Result <IAccessTokenOutput>(identityResult.Errors));
            }

            var linkUserWithRoleResult = await Mediator.Send(new LinkUserAndRoleInput
            {
                UserName = userInput.UserName,
                RoleName = RoleType.Patient.ToString()
            }, cancellationToken);

            if (linkUserWithRoleResult.Errors.Count() > 0)
            {
                return(new Result <IAccessTokenOutput>(linkUserWithRoleResult.Errors));
            }

            await PatientRepo.AddAsync(new Patient
            {
                IdentityUserId = user.Id,
            }, cancellationToken);

            await UoW.SaveAsync(cancellationToken);

            // Auto login after registrаtion (successful user registration should return access_token)
            return(await Mediator.Send(new UserCredentialsInput()
            {
                UserName = userInput.UserName,
                Password = userInput.Password
            }, cancellationToken));
        }
Esempio n. 10
0
        public async Task <RegisterUserOutput> RegisterUser(RegisterUserInput request)
        {
            UserEntity input = new UserEntity()
            {
                UserName = request.UserName,
                Password = request.Password
            };

            var user = await _userRepository.Add(input);

            return(new RegisterUserOutput()
            {
                Method = "RegisterUser",
                Result = user != default ? "SUCCESS" : "ERROR",
                Payload = user.CreateDto()
            });
Esempio n. 11
0
        public async Task <ActionResult <string> > AddUser([FromBody] RegisterUserInput registerUserInput)
        {
            try
            {
                var result = await _registerUserService.RegisterUser(registerUserInput);

                return(StatusCode((int)HttpStatusCode.Created, result));
            }
            catch (DefaultException e)
            {
                throw new DefaultException(e.StatusCode, e.Message);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 12
0
        public void RegisterUser(RegisterUserInput registerUser)
        {
            var existingUser = _userRepository.FirstOrDefault(u => u.Email == registerUser.EmailAddress);

            if (existingUser != null)
            {
                if (!existingUser.EmailConfirmed)
                {
                    SendConfirmationEmail(existingUser);
                    throw new UserFriendlyException("You registered with this email address before (" + registerUser.EmailAddress + ")! We re-sent an activation code to your email!");
                }

                throw new UserFriendlyException("There is already a user with this email address (" + registerUser.EmailAddress + ")! Select another email address!");
            }

            var userEntity = new User
            {
                PersonUser = new Person
                {
                    FirstName      = registerUser.Name,
                    LastName       = registerUser.LastName,
                    EmailAddresses = new List <Email>
                    {
                        new Email
                        {
                            EmailAddress = registerUser.EmailAddress
                        }
                    },
                    PhoneNumbers = new PhoneNumber
                    {
                        HomePhoneNumber = registerUser.Phone
                    }
                },

                PhoneNumber  = registerUser.Phone,
                Email        = registerUser.EmailAddress,
                PasswordHash = registerUser.Password,
                //UserName = registerUser.UserName
            };

            //var userEntity = registerUser;
            userEntity.PasswordHash          = new PasswordHasher().HashPassword(userEntity.PasswordHash);
            userEntity.EmailConfirmationCode = _userManager.GenerateEmailConfirmationTokenAsync(userEntity.Id).Result;
            _userRepository.Insert(userEntity);
            SendConfirmationEmail(userEntity);
        }
Esempio n. 13
0
        public async Task <string> RegisterPhone(RegisterUserInput input)
        {
#if true
            if (!input.IsPhoneValid())
            {
                throw new UserFriendlyException(L("InvalidPhoneNumber"));
            }

            if (await UserManager.Users.AnyAsync(x => x.PhoneNumber == input.ContactNumber))
            {
                throw new UserFriendlyException(L("PhoneNumberExists"));
            }

            return(await Task.Run(() => UserManager.GenerateTempToken(input.ContactNumber)));
#else
            return(await Task.Run(() => string.Empty));
#endif
        }
Esempio n. 14
0
        //Public Methods
        public RegisterUserOutput RegisterUser(RegisterUserInput input)
        {
            try
            {
                RestHTTP    http = new RestHTTP();
                RestRequest req  = new RestRequest("api/accounts/create", RestSharp.Method.POST);
                req.AddJsonBody(input);
                RegisterUserOutput response = http.HttpPost <RegisterUserOutput>(req);

                return(response);
            }
            catch (Exception ex)
            {
                WriteLogFile.Append("RegisterUser : ");
                WriteLogFile.Append(ex.Message);
                WriteLogFile.Append(ex.StackTrace);
            }
            return(null);
        }
        public async Task RegisterUserPassingTest()
        {
            RegisterUserInput registerUserInput = new RegisterUserInput()
            {
                userName         = Guid.NewGuid().ToString().Substring(0, 20),
                userPasswordHash = "bb96c2fc40d2d54617d6f276febe571f623a8dadf0b734855299b0e107fda32cf6b69f2da32b36445d73690b93cbd0f7bfc20e0f7f28553d2a4428f23b716e90",
                userRoleID       = 1,
                userFirstName    = "Test",
                userLastName     = "Free",
                userEmail        = "*****@*****.**"
            };
            string registerUserInputJsonString = JsonConvert.SerializeObject(registerUserInput);
            HttpResponseMessage httpResponse   = await ConnectHelper.HttpPostHelper(httpClient,
                                                                                    registerUserInputJsonString, "ManageUser/RegisterUser");

            Assert.Equal(httpResponse.StatusCode, HttpStatusCode.OK);
            var httpResponseContent = JObject.Parse(await httpResponse.Content.ReadAsStringAsync());

            Assert.Equal(Convert.ToInt32(httpResponseContent.GetValue("responseCode").ToString()),
                         (int)ResponseStatusEnum.Success);
        }
Esempio n. 16
0
        public IActionResult RegisterAccount(RegisterUserInput inputUser)
        {
            if (string.IsNullOrWhiteSpace(inputUser.Username) || string.IsNullOrWhiteSpace(inputUser.Password) ||
                string.IsNullOrWhiteSpace(inputUser.Captcha))
            {
                _logger.LogInformation("Username, password or captcha is empty.");
                return(BadRequest());
            }

            if (inputUser.Username.Length > 50)
            {
                _logger.LogInformation("Username exceeds permitted length.");
                return(BadRequest());
            }

            if (!_captcha.VerifyCaptcha(inputUser.Captcha, HttpContext.Connection.RemoteIpAddress, "register"))
            {
                _logger.LogInformation("Captcha failed verification");
                return(BadRequest());
            }

            if (Guid.TryParse(inputUser.Token, out _) &&
                _memoryCache.TryGetValue("R1" + inputUser.Token, out User cachedUser))
            {
                _memoryCache.Remove("R1" + inputUser.Token);
                cachedUser.Password = inputUser.Password;
                cachedUser.Username = inputUser.Username.ToLower();
                if (_authHandler.RegisterUser(ref cachedUser))
                {
                    _activityLogger.LogRegister(Request.HttpContext.Connection.RemoteIpAddress, cachedUser);
                    return(Ok());
                }

                _logger.LogInformation("Auth handler rejected account.");
                return(BadRequest());
            }

            _logger.LogInformation("Token is invalid.");
            return(BadRequest());
        }
        public void RegisterUser(RegisterUserInput registerUser)
        {
            var existingUser = _userRepository.FirstOrDefault(u => u.EmailAddress == registerUser.EmailAddress);

            if (existingUser != null)
            {
                if (!existingUser.IsEmailConfirmed)
                {
                    SendConfirmationEmail(existingUser);
                    throw new UserFriendlyException("You registere with this email address before (" + registerUser.EmailAddress + ")! We re-sent an activation code to your email!");
                }

                throw new UserFriendlyException("There is already a user with this email address (" + registerUser.EmailAddress + ")! Select another email address!");
            }

            var userEntity = registerUser.MapTo <TaskeverUser>();

            userEntity.Password = new PasswordHasher().HashPassword(userEntity.Password);
            userEntity.GenerateEmailConfirmationCode();
            _userRepository.Insert(userEntity);
            SendConfirmationEmail(userEntity);
        }
Esempio n. 18
0
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="input">input</param>
        /// <returns></returns>
        public async Task Register(RegisterUserInput input)
        {
            await ValidateCode(input.ValidateCode);

            var user = input.MapTo <User>();

            user.IsActive = true;
            user.Password = new PasswordHasher().HashPassword(input.Password);
            if (input.ValidateCode.ValidateType == ValidateType.手机)
            {
                user.IsPhoneNoConfirm = true;
            }
            else
            {
                user.IsEmailConfirmed = true;
            }
            var identityResult = await UserManager.CreateAsync(user);

            if (!identityResult.Succeeded)
            {
                throw new UserFriendlyException(identityResult.Errors.JoinAsString(" "));
            }
        }
Esempio n. 19
0
        public async Task RegisterUser(RegisterUserInput input)
        {
            if (!UserManager.VerifyTempToken(input.ContactNumber, input.VerificationCode))
            {
                throw new UserFriendlyException(L("InvalidPhoneVerificationCode"));
            }

            if (string.IsNullOrWhiteSpace(input.Name) || string.IsNullOrWhiteSpace(input.Email))
            {
                throw new UserFriendlyException(L("MissingFields"));
            }

            if (await UserManager.Users.AnyAsync(x => x.EmailAddress == input.Email))
            {
                throw new UserFriendlyException(L("EmailExists"));
            }

            var user = User.CreateAppUser(input.ContactNumber, input.Name, input.Email, input.Password);

            user.SetNormalizedNames();
            var userId = await UserManager.CreateUserAndGetIdAsync(user);

            await CurrentUnitOfWork.SaveChangesAsync();
        }
Esempio n. 20
0
        public virtual async Task RegisterUser(RegisterUserInput input)
        {
            Ensure.NotNull(input, nameof(input));

            await _userManager.RegisterUser(input.TenantName, input.CellPhone, input.UserName);
        }
Esempio n. 21
0
        public async Task <IActionResult> Register(RegisterUserInput model, CancellationToken cancellationToken)
        {
            var result = await Mediator.Value.Send(model, cancellationToken);

            return(PresentResult(result));
        }
        public async Task <IActionResult> Register(RegisterUserInput model)
        {
            var result = await RegisterUserCommand.Value.RegisterAsync(model);

            return(PresentResult(result));
        }
Esempio n. 23
0
 public async Task <bool> VerifyPhone(RegisterUserInput input)
 {
     return(await Task.Run(() => UserManager.VerifyTempToken(input.ContactNumber, input.VerificationCode)));
 }
Esempio n. 24
0
 public IHttpActionResult RegisterUser(RegisterUserInput input)
 {
     RegisterUserOutput output = _authSvc.RegisterUser(input);
     return Ok(output);
 }