Ejemplo n.º 1
0
        public JsonResult Register(RegisterUserInputModel inputModel)
        {
            try
            {
                Assert.ArgumentNotNull(inputModel, "RegisterInputModel");
                RegisterBaseJsonResult result = new RegisterBaseJsonResult();

                this.ValidateModel(result);
                if (result.HasErrors)
                {
                    return(Json(result, JsonRequestBehavior.AllowGet));
                }

                var anonymousVisitorId = this.CurrentVisitorContext.UserId;

                var response = this.AccountManager.RegisterUser(this.CurrentStorefront, inputModel);
                if (response.ServiceProviderResult.Success && response.Result != null)
                {
                    result.Initialize(response.Result);
                    this.AccountManager.Login(CurrentStorefront, CurrentVisitorContext, anonymousVisitorId, response.Result.UserName, inputModel.Password, false);
                }
                else
                {
                    result.SetErrors(response.ServiceProviderResult);
                }

                return(Json(result));
            }
            catch (Exception e)
            {
                CommerceLog.Current.Error("Register", this, e);
                return(Json(new BaseJsonResult("Register", e), JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Register([FromBody] RegisterUserInputModel registerModel)
        {
            if (!this.ModelState.IsValid)
            {
                var errors = this.ExtractModelErrors(this.ModelState);

                return(this.BadRequest(errors));
            }

            try
            {
                var response = await this.accountService.RegisterUser(registerModel);

                if (!response.Succeeded)
                {
                    this.AddErrors(response);

                    return(this.BadRequest(this.ModelState));
                }

                return(this.Ok(new List <int>()
                {
                    1, 2, 3, 4, 5
                }));
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex.Message));
            }
        }
Ejemplo n.º 3
0
        public async Task RegisterAsync(RegisterUserInputModel model)
        {
            var userExists = await this.userManager.FindByEmailAsync(model.Email) != null;

            if (userExists)
            {
                throw new EntityExistsException("User");
            }

            var newUser = new User
            {
                Id       = Guid.NewGuid().ToString(),
                Email    = model.Email,
                UserName = model.Username,

                NormalizedEmail    = model.Email.ToUpper(),
                NormalizedUserName = model.Username.ToUpper(),

                UserRoles = new List <UserRole>
                {
                    new() { RoleId = RoleIds.Client }
                }
            };

            newUser.PasswordHash = new PasswordHasher <User>().HashPassword(newUser, model.Password);

            this.repo.Add(newUser);

            this.repo.Save();
        }
Ejemplo n.º 4
0
        public async Task <IdentityResult> RegisterUser(RegisterUserInputModel model)
        {
            //TODO: Profile picture, response if registration exists
            this.CheckModelForNull(model);

            if (this.ValidateEmail(model.Email) && this.ValidateUsername(model.Username))
            {
                var user = new ApplicationUser()
                {
                    UserName = model.Username, Email = model.Email
                };
                var result = await this.UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var vacationUser = new User()
                    {
                        Username        = model.Username,
                        ProfilePicture  = null,
                        Email           = model.Email,
                        ApplicationUser = user
                    };

                    this.Data.User.Add(vacationUser);
                    this.Data.SaveChanges();

                    return(result);
                }

                throw new Exception(string.Join("; ", result.Errors));
            }

            throw new Exception("Invalid data.");
        }
Ejemplo n.º 5
0
        public HttpResponse Register(RegisterUserInputModel input)
        {
            if (String.IsNullOrEmpty(input.Username) || input.Username.Length < 5 || input.Username.Length > 20)
            {
                return(this.Error("Invalid Username"));
            }

            if (!userService.IsUsernameAvailable(input.Username))
            {
                return(this.Error("This username is already taken"));
            }

            if (string.IsNullOrEmpty(input.Email) || !new EmailAddressAttribute().IsValid(input.Email))
            {
                return(this.Error("Invalid email"));
            }

            if (!userService.IsEmailAvailable(input.Email))
            {
                return(this.Error("This email is already taken."));
            }

            if (string.IsNullOrEmpty(input.Password) || input.Password.Length < 6 || input.Password.Length > 20)
            {
                return(this.Error("Password is incorrect"));
            }

            if (input.Password != input.ConfirmPassword)
            {
                return(this.Error("Passowrds dont match"));
            }
            this.userService.CreateUser(input.Username, input.Email, input.Password);

            return(this.Redirect("/Users/Login"));
        }
Ejemplo n.º 6
0
        public JsonResult Register(RegisterUserInputModel inputModel)
        {
            try
            {
                Assert.ArgumentNotNull(inputModel, nameof(inputModel));
                var result = this.CreateJsonResult <RegisterApiModel>();
                if (result.HasErrors)
                {
                    return(Json(result, JsonRequestBehavior.AllowGet));
                }

                var response = AccountManager.RegisterUser(inputModel);
                if (response.ServiceProviderResult.Success && response.Result != null)
                {
                    result.Initialize(response.Result);
                    AccountManager.Login(response.Result.UserName, inputModel.Password, false);
                }
                else
                {
                    result.SetErrors(response.ServiceProviderResult);
                }

                return(Json(result));
            }
            catch (Exception e)
            {
                return(Json(new ErrorApiModel("Register", e), JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 7
0
        public ManagerResponse <CreateUserResult, CommerceUser> RegisterUser(RegisterUserInputModel inputModel)
        {
            Assert.ArgumentNotNull(inputModel, "inputModel");
            Assert.ArgumentNotNullOrEmpty(inputModel.FirstName, "inputModel.FirstName");
            Assert.ArgumentNotNullOrEmpty(inputModel.LastName, "inputModel.LastName");

            CreateUserResult result;

            // Attempt to register the user
            try
            {
                var request = new CreateUserRequest(inputModel.UserName, inputModel.Password, inputModel.UserName, StorefrontContext.Current.ShopName);
                request.Properties.Add("FirstName", inputModel.FirstName);
                request.Properties.Add("LastName", inputModel.LastName);
                result = this.CustomerServiceProvider.CreateUser(request);
            }
            catch (MembershipCreateUserException e)
            {
                result = new CreateUserResult {
                    Success = false
                };
                result.SystemMessages.Add(new SystemMessage {
                    Message = ErrorCodeToString(e.StatusCode)
                });
            }
            result.WriteToSitecoreLog();
            return(new ManagerResponse <CreateUserResult, CommerceUser>(result, result.CommerceUser));
        }
Ejemplo n.º 8
0
        public HttpResponse Register(RegisterUserInputModel input)
        {
            if (this.IsUserSignedIn())
            {
                return(this.Redirect("/"));
            }

            if (string.IsNullOrWhiteSpace(input.Username) ||
                input.Username.Length < 5 ||
                input.Username.Length > 20)
            {
                return(this.Error("Invalid username."));
            }

            if (string.IsNullOrWhiteSpace(input.Email))
            {
                return(this.Error("Email is required."));
            }

            if (string.IsNullOrWhiteSpace(input.Password) ||
                input.Password.Length < 6 ||
                input.Password.Length > 20)
            {
                return(this.Error("Invalid password."));
            }

            if (input.Password != input.ConfirmPassword)
            {
                return(this.Error("Passwords not same."));
            }

            this.usersService.CreateUser(input.Username, input.Email, input.Password);

            return(this.Redirect("/Users/Login"));
        }
Ejemplo n.º 9
0
        private async Task SeedUser()
        {
            if (!this.data.ApplicationUser.Query().Any(u => u.UserName == "admin"))
            {
                var adminModel = new RegisterUserInputModel()
                {
                    Username = "******",
                    Email    = "*****@*****.**",
                    Password = "******"
                };

                await this.accountService.RegisterUser(adminModel);

                var createAdminRole = await this.roleManager.CreateAsync(new IdentityRole("Administrator"));

                if (!createAdminRole.Succeeded)
                {
                    throw new Exception(string.Join("; ", createAdminRole.Errors));
                }

                var adminUser    = this.data.ApplicationUser.Query().FirstOrDefault();
                var addAdminRole = await this.userManager.AddToRoleAsync(adminUser, "Administrator");

                if (!addAdminRole.Succeeded)
                {
                    throw new Exception(string.Join("; ", addAdminRole.Errors));
                }

                this.data.SaveChanges();
            }
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Register([FromBody] RegisterUserInputModel model)
        {
            var result = await this.identity.Register(model);

            if (!result.Succeeded)
            {
                return(this.BadRequest(result.Errors));
            }

            return(await this.Login(new LoginUserInputModel(model.UserName, model.Password)));
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> RegisterManager(RegisterUserInputModel inputModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(inputModel));
            }

            await this.userService.RegisterUserForCompanyAsync(inputModel, GlobalConstants.ManagerRoleName);

            return(this.Redirect("/"));
        }
Ejemplo n.º 12
0
        public async Task <ActionResult <UserOutputModel> > Register(RegisterUserInputModel input)
        {
            var result = await this.identity.Register(input);

            if (!result)
            {
                return(this.BadRequest(result.Errors));
            }

            return(await this.Login(new UserInputModel { Email = input.Email, Password = input.Password }));
        }
Ejemplo n.º 13
0
        public async Task <IdentityResult> Register(RegisterUserInputModel userInput)
        {
            var user = new ApplicationUser
            {
                Email    = userInput.Email,
                UserName = userInput.UserName,
            };
            var result = await this.userManager.CreateAsync(user, userInput.Password);

            return(result);
        }
Ejemplo n.º 14
0
        public void CreateUser(RegisterUserInputModel model)
        {
            var user = new User
            {
                Username = model.Username,
                Email    = model.Email,
                Password = ComputeHash(model.Password)
            };

            this.dbContext.Users.Add(user);
            this.dbContext.SaveChanges();
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> RegisterEmployee(RegisterUserInputModel inputModel)
        {
            if (!this.ModelState.IsValid)
            {
                this.ViewData.Add("Position", "Supervisor");
                return(this.View("RegisterUser", inputModel));
            }

            inputModel.CompanyId = this.companyService.GetIdByUserName(this.User.Identity.Name);

            await this.userService.RegisterUserForCompanyAsync(inputModel);

            return(this.RedirectToAction("Details", "Company"));
        }
        public ActionResult RegisterExistingUser(CommerceCustomer commerceUser)
        {
            try
            {
                Assert.ArgumentNotNull(commerceUser, "commerceUser");
                RegisterBaseResultApiModel result = new RegisterBaseResultApiModel();

                var userResponse = this.AccountManager.GetUser(commerceUser.Name);
                if (userResponse.Result == null)
                {
                    // create the user in Sitecore
                    var inputModel = new RegisterUserInputModel {
                        UserName = commerceUser.Name, Password = System.Web.Security.Membership.GeneratePassword(8, 4)
                    };
                    inputModel.FirstName = commerceUser.Properties["FirstName"] as string ?? string.Empty;
                    inputModel.LastName  = commerceUser.Properties["LastName"] as string ?? string.Empty;
                    var response = this.AccountManager.RegisterUser(inputModel);
                    if (!response.ServiceProviderResult.Success || response.Result == null)
                    {
                        result.SetErrors(response.ServiceProviderResult);
                        return(this.Json(result, JsonRequestBehavior.AllowGet));
                    }
                }

                var isLoggedIn = this.AccountManager.Login(commerceUser.Name, false);
                if (isLoggedIn)
                {
                    return(this.Redirect("/"));
                }
                else
                {
                    result.SetErrors(new List <string> {
                        "Could not create user"
                    });
                }

                return(this.Json(result));
            }
            catch (Sitecore.Commerce.OpenIDConnectionClosedUnexpectedlyException)
            {
                this.CleanNotAuthorizedSession();
                return(this.Redirect("/login"));
            }
            catch (Exception e)
            {
                return(this.Json(new ErrorApiModel("Register", e), JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 17
0
        public async Task <Result <User> > Register(RegisterUserInputModel userInput)
        {
            var user = new User
            {
                Email    = userInput.Email,
                UserName = userInput.Email,
            };

            var identityResult = await this.userManager.CreateAsync(user, userInput.Password);

            var errors = identityResult.Errors.Select(e => e.Description);

            return(identityResult.Succeeded
                ? Result <User> .SuccessWith(user)
                : Result <User> .Failure(errors));
        }
        public void Register_Initialized_ShouldReturnOk(Database db, IOrderManager orderManager, IContactFactory contactFactory, ILogger logger, HttpContextBase httpContextBase)
        {
            // arrange
            FakeSiteContext.Database = db;
            var controller = new AccountController(new MockAccountManager(), contactFactory, logger, new MockAccountRepository());
            var model      = new RegisterUserInputModel {
                UserName = "******", Password = "******", ConfirmPassword = "******"
            };

            // act
            var result = controller.Register(model);

            // assert
            result.As <JsonResult>().Should().NotBeNull();
            result.As <JsonResult>().Data.As <RegisterBaseJsonResult>().Should().NotBeNull();
            result.As <JsonResult>().Data.As <RegisterBaseJsonResult>().Success.Should().BeTrue();
        }
        public RegisterBaseJsonResult RegisterUser(RegisterUserInputModel inputModel)
        {
            var fixture = new Fixture();
            var res     = fixture.Create <RegisterBaseJsonResult>();

            if (!inputModel.UserName.IsNullOrEmpty() && inputModel.UserName.Equals("fake") &&
                !inputModel.Password.IsNullOrEmpty() && !inputModel.ConfirmPassword.IsNullOrEmpty() &&
                inputModel.Password.Equals(inputModel.ConfirmPassword))
            {
                res.Success = true;
            }
            else
            {
                res.Success = false;
            }
            return(res);
        }
Ejemplo n.º 20
0
        public async Task <ActionResult> Register(RegisterUserInputModel input)
        {
            if (await usersService.IsUserExists(input.UserId))
            {
                return(BadRequest(string.Format(UsersConstants.UserAlreadyExists, input.UserId)));
            }

            var result = await usersService
                         .RegisterUser(input.UserId);

            if (!result.Succeeded)
            {
                return(BadRequest(result.Errors));
            }

            return(Ok(result.Data));
        }
Ejemplo n.º 21
0
        public HttpResponse Register(RegisterUserInputModel model)
        {
            if (IsUserSignedIn())
            {
                return(this.Redirect("/"));
            }

            if (string.IsNullOrEmpty(model.Username) ||
                model.Username.Length < 5 ||
                model.Username.Length > 20)
            {
                return(this.Error("Name should be between 5 and 20 characters long."));
            }

            if (!this.usersService.IsUsernameAvailable(model))
            {
                return(this.Error("Username not available."));
            }

            if (string.IsNullOrEmpty(model.Email) ||
                !new EmailAddressAttribute().IsValid(model.Email))
            {
                return(this.Error("Email is required."));
            }

            if (!this.usersService.IsEmailAvailable(model))
            {
                return(this.Error("Email is not in the right format."));
            }

            if (string.IsNullOrEmpty(model.Password) ||
                model.Password.Length < 6 ||
                model.Password.Length > 20)
            {
                return(this.Error("Password should be between 6 and 20 characters long."));
            }

            if (model.ConfirmPassword != model.Password)
            {
                return(this.Error("Passwords do not match."));
            }

            this.usersService.CreateUser(model);
            return(this.Redirect("/Users/Login"));
        }
Ejemplo n.º 22
0
        public HttpResponse Register(RegisterUserInputModel model)
        {
            if (this.IsUserSignedIn())
            {
                return(this.Redirect("/"));
            }

            if (string.IsNullOrEmpty(model.Username) ||
                model.Username.Length < 5 ||
                model.Username.Length > 20)
            {
                return(this.Error("Username should be between 5 and 20 characters long."));
            }

            if (string.IsNullOrEmpty(model.Email) ||
                !new EmailAddressAttribute().IsValid(model.Email))
            {
                return(this.Error("Invalid email address."));
            }

            if (string.IsNullOrEmpty(model.Password) ||
                model.Password.Length < 6 ||
                model.Password.Length > 20)
            {
                return(this.Error("Password is required and should be between 6 and 20 characters long."));
            }

            if (model.ConfirmPassword != model.Password)
            {
                return(this.Error("Passwords do not match."));
            }

            if (!this.usersService.IsEmailAvailable(model.Email))
            {
                return(this.Error("The email address is already taken."));
            }

            if (!this.usersService.IsUsernameAvailable(model.Username))
            {
                return(this.Error("The username is already taken."));
            }

            this.usersService.Create(model.Username, model.Email, model.Password);
            return(this.Redirect("/Users/Login"));
        }
Ejemplo n.º 23
0
        public IActionResult Register(RegisterUserInputModel input)
        {
            if (!ModelState.IsValid)
            {
                return(this.Redirect("/Users/Register"));
            }

            if (input.Password != input.ConfirmPassword)
            {
                return(this.Redirect("/Users/Register"));
            }

            string userId = this.usersService.CreateUser(input.Username, input.Email, input.Password);

            this.SignIn(userId, input.Username, input.Email);

            return(this.Redirect("/"));
        }
        public RegisterBaseJsonResult RegisterUser(RegisterUserInputModel inputModel)
        {
            RegisterBaseJsonResult result = new RegisterBaseJsonResult();
            var anonymousVisitorId        = this.CurrentVisitorContext.UserId;
            var response = this.AccountManager.RegisterUser(this.CurrentStorefront, inputModel);

            if (response.ServiceProviderResult.Success && response.Result != null)
            {
                result.Initialize(response.Result);
                this.AccountManager.Login(CurrentStorefront, CurrentVisitorContext, anonymousVisitorId, response.Result.UserName, inputModel.Password, false);
            }
            else
            {
                result.SetErrors(response.ServiceProviderResult);
            }

            return(result);
        }
Ejemplo n.º 25
0
        public async Task <object> Register([FromBody] RegisterUserInputModel model)
        {
            try
            {
                await this.accountService.Register(model);

                return(this.Ok(new ReturnMessage()
                {
                    Message = "You have successfully registered! Now you should be able to log in!"
                }));
            }
            catch (Exception e)
            {
                return(this.BadRequest(new ReturnMessage {
                    Message = e.Message
                }));
            }
        }
Ejemplo n.º 26
0
        public async Task SeedAdmin(RegisterUserInputModel model)
        {
            var user = this.Mapper.Map <RegisterUserInputModel, User>(model);

            user.IsActive       = true;
            user.DateRegistered = DateTime.UtcNow;

            try
            {
                await this.UserManager.CreateAsync(user, model.Password);

                await this.UserManager.AddToRoleAsync(user, Enum.GetName(typeof(Roles), 1));
            }
            catch (Exception e)
            {
                this.Logger.LogWarning(e, "Creation of ApplicationUser and its role resulted in failure: " + e.Message);
            }
        }
Ejemplo n.º 27
0
        public async Task Register(string email, string password, string username)
        {
            var user = new RegisterUserInputModel
            {
                Email    = email,
                Password = password,
                Username = username
            };

            var json = new StringContent(
                JsonConvert.SerializeObject(user),
                Encoding.UTF8,
                "application/json");


            var response = await client.PostAsync(RegisterEndpoint, json);

            response.EnsureSuccessStatusCode();
        }
Ejemplo n.º 28
0
        public ManagerResponse <CreateUserResult, CommerceUser> RegisterUser(RegisterUserInputModel inputModel)
        {
            Assert.ArgumentNotNull(inputModel, nameof(inputModel));
            Assert.ArgumentNotNullOrEmpty(inputModel.UserName, nameof(inputModel.UserName));
            Assert.ArgumentNotNullOrEmpty(inputModel.Password, nameof(inputModel.Password));
            if (StorefrontContext.Current == null)
            {
                throw new InvalidOperationException("Cannot be called without a valid storefront context.");
            }

            CreateUserResult result;

            // Attempt to register the user
            try
            {
                var request = new CreateUserRequest(inputModel.UserName, inputModel.Password, inputModel.UserName, StorefrontContext.Current.ShopName);
                result = CustomerServiceProvider.CreateUser(request);
                result.WriteToSitecoreLog();

                if (result.Success && result.CommerceUser == null && !result.SystemMessages.Any())
                {
                    // Connect bug:  This is a work around to a Connect bug.  When the user already exists,connect simply aborts the pipeline but
                    // does not set the success flag nor does it return an error message.
                    result.Success = false;
                    result.SystemMessages.Add(new SystemMessage
                    {
                        Message = DictionaryPhraseRepository.Current.Get("/System Messages/Accounts/User Already Exists", "User name already exists. Please enter a different user name.")
                    });
                }
            }
            catch (MembershipCreateUserException e)
            {
                result = new CreateUserResult {
                    Success = false
                };
                result.SystemMessages.Add(new SystemMessage {
                    Message = ErrorCodeToString(e.StatusCode)
                });
            }

            return(new ManagerResponse <CreateUserResult, CommerceUser>(result, result.CommerceUser));
        }
Ejemplo n.º 29
0
        private async Task SeedUser(IRepository <User> userRepository, IConfiguration configuration, IAccountService accountService, ILogger <IDatabaseInitializer> logger)
        {
            string username = configuration.GetSection("UserSettings")["Username"];

            if (!userRepository.Query().Any(u => u.UserName == username))
            {
                logger.LogWarning("Start Seeding User...");

                var adminModel = new RegisterUserInputModel()
                {
                    Username = configuration.GetSection("UserSettings")["Username"],
                    Email    = configuration.GetSection("UserSettings")["Email"],
                    Password = configuration.GetSection("UserSettings")["Password"],
                };

                await accountService.SeedAdmin(adminModel);

                logger.LogWarning("End Seeding User Successfully");
            }
        }
Ejemplo n.º 30
0
        public async Task Register(RegisterUserInputModel model)
        {
            var user = this.Mapper.Map <RegisterUserInputModel, User>(model);

            if (this.UserManager.Users.Count(u => u.UserName == user.UserName) != 0)
            {
                throw new Exception("Username is already taken!");
            }

            if (this.UserManager.Users.Count(u => u.Email == user.Email) != 0)
            {
                throw new Exception("Email is already taken!");
            }

            user.DateRegistered = DateTime.UtcNow;

            await this.UserManager.CreateAsync(user, model.Password);

            await this.UserManager.AddToRoleAsync(user, Enum.GetName(typeof(Roles), 2));
        }