Ejemplo n.º 1
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            RegisterValidator validator = new RegisterValidator();
            ValidationResult  result    = validator.Validate(model);
            bool chekname = await _context.Users.AnyAsync(p => p.Username.Equals(model.Username));

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }
            if (chekname)
            {
                return(BadRequest("This email address already exist"));
            }

            var user = new User();

            user.Username  = model.Username;
            user.FirstName = model.FirstName;
            user.LastName  = model.LastName;
            user.Password  = Crypto.HashPassword(model.Password);
            await _context.Users.AddAsync(user);

            await _context.SaveChangesAsync();

            var userRole = new UserRolePivot();

            userRole.UserId = user.Id;
            userRole.RoleId = _context.Roles.FirstOrDefault(p => p.Name.Equals("customer")).Id;
            await _context.UserRoles.AddAsync(userRole);

            await _context.SaveChangesAsync();

            return(Ok());
        }
        public void Save()
        {
            try
            {
                bool IsSaved = false;

                UsersDTO temp = new UsersDTO();

                /// operations required for fluent validation
                RegisterValidator reg     = new RegisterValidator(CurrentUser);
                ValidationResult  results = reg.Validate(CurrentUser);


                if (!results.IsValid)
                {
                    Message = results.Errors[0].ToString();
                }
                else
                {
                    temp.Id              = CurrentUser.Id;
                    temp.FirstName       = CurrentUser.FirstName;
                    temp.LastName        = CurrentUser.LastName;
                    temp.Email           = CurrentUser.Email;
                    temp.Password        = CurrentUser.Password;
                    temp.PasswordConfirm = CurrentUser.PasswordConfirm;
                    temp.UserName        = CurrentUser.UserName;

                    if (!results.IsValid)
                    {
                        Message = results.Errors[0].ToString();
                    }
                    else
                    {
                        IsSaved = userService.Register(temp);
                        LoadData();
                    }
                }


                if (IsSaved)
                {
                    Message = "User saved";
                }
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }
Ejemplo n.º 3
0
        public IActionResult Register([FromBody] RegisterDto dto
                                      , [FromServices] IRegisterCommand command
                                      , [FromServices] RegisterValidator validator)
        {
            var result = validator.Validate(dto);

            if (result.IsValid)
            {
                ApplicationUser applicationUser = _mapper.Map <ApplicationUser>(dto);
                _executor.ExecuteCommand(command, applicationUser);
                return(Ok("Application user created successfully"));
            }

            return(UnprocessableEntity(UnprocessableEntityResponse.Message(result.Errors)));
        }
        public void Register_Validation_ShouldValidate(string username, string password, string firstName, string lastName, bool valid)
        {
            RegisterInputModel registerInput = new RegisterInputModel {
                Username  = username,
                Password  = password,
                FirstName = firstName,
                LastName  = lastName
            };

            RegisterValidator validator = new RegisterValidator();

            ValidationResult result = validator.Validate(registerInput);

            result.IsValid.Should().Be(valid);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Register([FromBody] UserRegisterApiModel model)
        {
            var validator   = new RegisterValidator(_recaptcha, _resourceManager);
            var validResult = validator.Validate(model);

            if (!validResult.IsValid)
            {
                return(BadRequest(new MessageApiModel()
                {
                    Message = validResult.ToString()
                }));
            }

            var RegisterResult = await _accountService.RegisterUserAsync(model);

            return(Created("", RegisterResult));
        }
Ejemplo n.º 6
0
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // validate for unique email and username
            RegisterValidator validator = new RegisterValidator();
            ValidationResult  results   = validator.Validate(model);

            if (!results.IsValid)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            // default role
            string role = "Employee";

            if (model.Role != null && model.Role != "")
            {
                role = model.Role;
            }

            var user = new ApplicationUser()
            {
                UserName    = model.UserName, Email = model.UserName,
                FirstName   = model.FirstName, LastName = model.LastName,
                HomeAddress = model.HomeAddress, PhoneNumber = model.PhoneNumber, BirthDate = model.BirthDate, Gender = model.Gender,
                Role        = role,

                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Register(RegisterViewModel register)
        {
            var validator        = new RegisterValidator();
            var validationResult = validator.Validate(register);

            if (validationResult.IsValid)
            {
                var user = new AppUser
                {
                    UserName = register.Name,
                    Email    = register.Email
                };

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

                if (result.Succeeded)
                {
                    return(View("Success", user.UserName));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        validationResult.Errors
                        .Add(new ValidationFailure(error.Code, error.Description));
                    }
                }
            }

            var model = new MultiFormViewModel();

            foreach (var error in validationResult.Errors)
            {
                model.ValidationErrors.Add(error.ToString());
            }

            return(View("Login-register-forms", model));
        }
Ejemplo n.º 8
0
        public async Task <JsonResult> Registration([FromBody] RegisterViewModel registerViewModel)
        {
            var validator       = new RegisterValidator();
            var validatorResult = validator.Validate(registerViewModel);

            if (validatorResult.IsValid)
            {
                var applicationUser = mapper.Map <RegisterViewModel, ApplicationUserEntity>(registerViewModel);
                var result          = await userManager.CreateAsync(applicationUser, registerViewModel.Password);

                if (!result.Succeeded)
                {
                    return(Json(result.Errors.Select(a => a.Description).ToList()));
                }
                await serviceOfAccount.TryToRegistration(registerViewModel.Login);

                var code = await userManager.GenerateEmailConfirmationTokenAsync(applicationUser);

                var callbackUrl = Url.Action(
                    nameof(ConfirmEmail),
                    this.ControllerContext.ActionDescriptor.ControllerName,
                    new
                {
                    userId = applicationUser.Id,
                    code   = code
                },
                    this.HttpContext.Request.Scheme,
                    this.HttpContext.Request.Host.ToString());
                serviceOfAccount.SendEmailAsync(registerViewModel.Email, "Confirm your account", $"Confirm your registration by clicking on the link: <a href='{callbackUrl}'>link</a>");
                return(Json(Ok()));
            }
            else
            {
                return(Json(validatorResult.Errors.Select(a => a.ErrorMessage).ToList()));
            }
        }
Ejemplo n.º 9
0
        public GenericOperationResult <bool> RegisterUser(RegisterDto user)
        {
            var registerValidator = new RegisterValidator();
            var res    = registerValidator.Validate(user);
            var result = new GenericOperationResult <bool>();

            if (res.IsValid)
            {
                try
                {
                    if (!unitOfWork.Authentication.UserExists(user.UserName, user.PhoneNumber))
                    {
                        var  registerUser   = MapUser(user);
                        User registeredUser = new User();
                        registeredUser = unitOfWork.Authentication.Register(registerUser, user.Password);
                        VerifyUserModel model = new VerifyUserModel
                        {
                            User     = registeredUser,
                            Password = user.Password
                        };
                        if (registeredUser != null)
                        {
                            httpContext.HttpContext.Session.SetString(user.PhoneNumber, JsonConvert.SerializeObject(model));
                            MessageModel messageModel = new MessageModel
                            {
                                From = new PhoneNumber("+12284564506"),
                                //Twilio license
                                To   = new PhoneNumber("+201121736295"),
                                Body = "Verification code of your account is: 0000"
                            };
                            var message = SendMessage(messageModel);
                            //ObjectCache cache = MemoryCache.Default;
                            //cache.Add("CachedValueKey", "Some value to cache", new CacheItemPolicy());
                            //cache.Add(user.PhoneNumber, user.Password, new CacheItemPolicy());
                            result.Status = OperationResultStatusEnum.Succeeded;
                            result.Messages.Add("Suceeded");
                            return(result);
                        }
                        result.Status = OperationResultStatusEnum.Failed;
                        result.Messages.Add("Failed");
                        return(result);
                    }
                    else
                    {
                        result.Status = OperationResultStatusEnum.Failed;
                        result.Messages.Add("User already exists");
                        return(result);
                    }
                }
                catch (ArgumentNullException e)
                {
                    throw new BusinessException("Argument is null ", e);
                }
                catch (SqlException e)
                {
                    throw new BusinessException("Database error ", e);
                }
                catch (NullReferenceException e)
                {
                    throw new BusinessException("Object Refrence is null ", e);
                }
                catch (Exception e)
                {
                    throw new BusinessException("error Occured ", e);
                }
            }
            result.Messages = res.Errors.Select(e => e.ErrorMessage).ToList();
            result.Status   = OperationResultStatusEnum.Validation;
            return(result);
        }
 public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
   var validator = new RegisterValidator();
   var result = validator.Validate(this);
   return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
 }