public async Task RegisterMethodShouldFailWhenTryingToRegisterWithAlreadyExistingUsername()
        {
            var client             = this.factory.CreateClient();
            var registerInputModel = new RegisterInputModel
            {
                Email     = "*****@*****.**",
                FirstName = "Ivan",
                LastName  = "Nenov",
                Username  = "******",
                Password  = "******"
            };

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

            var response = await client.PostAsync("/api/account/register", stringContent);

            var content = await response.Content.ReadAsStringAsync();

            var badRequestObj = JsonConvert.DeserializeObject <BadRequestViewModel>(content);

            Assert.Equal("This username is already taken. Please try with another one.", badRequestObj.Message);
            Assert.Equal(400, badRequestObj.Status);
        }
Esempio n. 2
0
        public async Task <IActionResult> Register(RegisterInputModel inputModel)
        {
            if (ModelState.IsValid)
            {
                var user = new User
                {
                    UserName   = inputModel.Email,
                    Email      = inputModel.Email,
                    FirstName  = inputModel.FirstName,
                    LastName   = inputModel.LastName,
                    Town       = inputModel.Town,
                    PictureUrl = defaultPictureUrl
                };
                var result = await _userManager.CreateAsync(user, inputModel.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    await _signInManager.SignInAsync(user, isPersistent : false);

                    return(Redirect("/"));
                }
                else
                {
                    ModelState.AddModelError(UserFields.Email, ErrorMessages.DublicateEmail);
                    return(this.View());
                }
            }

            return(this.View());
        }
        public IActionResult Register(RegisterInputModel model)
        {
            if (model.Password != model.ConfirmPassword)
            {
                //TODO: return Error;
            }

            if (!DataValidator.ValidateObject(model))
            {
                //TODO: return Error;
            }

            var hashedPassword = this.hashService.Hash(model.Password);

            this.userService.RegisterUser(model.Username, hashedPassword, model.Email);

            var identity = new IdentityUser
            {
                Username = model.Username,
                Password = hashedPassword,
                Email    = model.Email
            };

            this.SignIn(identity);

            return(this.RedirectToAction("/"));
        }
        public async Task RegisterMethodShouldFailWithInvalidParameter(
            string email,
            string username,
            string firstName,
            string lastName,
            string password
            )
        {
            var client             = this.factory.CreateClient();
            var registerInputModel = new RegisterInputModel
            {
                Email     = email,
                FirstName = firstName,
                LastName  = lastName,
                Username  = username,
                Password  = password
            };

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

            var response = await client.PostAsync("/api/account/register", stringContent);

            var content = await response.Content.ReadAsStringAsync();

            var problemDetails = JsonConvert.DeserializeObject <ProblemDetails>(content);

            Assert.Equal("One or more validation errors occurred.", problemDetails.Title);
            Assert.Equal(400, problemDetails.Status);
        }
        public async Task <IActionResult> Register(RegisterInputModel model, string?returnUrl = default)
        {
            if (!ModelState.IsValid)
            {
                return(View(model as RegisterViewModel));
            }

            var user = new ApplicationUser
            {
                Name       = $"{model.GivenName} {model.FamilyName}",
                GivenName  = model.GivenName,
                FamilyName = model.FamilyName,
                UserName   = model.Username ?? model.Email,
                Email      = model.Email
            };

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

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(View());
            }

            await PublishConfirmEmailMessage(user, returnUrl);

            return(View("EmailConfirmation", model.Email));
        }
Esempio n. 6
0
        public HttpResponse Register(RegisterInputModel input)
        {
            if (string.IsNullOrEmpty(input.Username) || input.Username.Length < 5 || input.Username.Length > 20)
            {
                return(this.Error("Username should be between 5 and 20 character long."));
            }

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

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

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

            if (!this.usersService.IsEmailAvailable(input.Email))
            {
                return(this.Error("Email already taken."));
            }

            if (!this.usersService.IsUsernameAvailable(input.Username))
            {
                return(this.Error("Username already taken."));
            }

            this.usersService.Create(input.Username, input.Email, input.Password);
            return(this.Redirect("/Users/Login"));
        }
Esempio n. 7
0
        public async Task <ActionResult <string> > Registrar([FromBody] RegisterInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var userModel = new User
                {
                    Username = model.Username,
                    Password = model.Password,
                    Role     = model.Role
                };

                var user = await _authService.Criar(userModel, model.Password);

                return(Ok(new { mensagem = "Usuário registrado com sucesso!" }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new { mensagem = ex.Message }));
            }
        }
        public async Task <IActionResult> Register([FromBody] RegisterInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

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

            // TODO: define roles externally
            string role = "User";

            if (result.Succeeded)
            {
                if (await _roleManager.FindByNameAsync(role) == null)
                {
                    await _roleManager.CreateAsync(new IdentityRole(role));
                }
                await _userManager.AddToRoleAsync(user, role);

                //await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(JwtClaimTypes.GivenName, model.FirstName));
                //await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim(JwtClaimTypes.FamilyName, model.LastName));

                return(Ok(new ProfileViewModel(user)));
            }

            return(BadRequest(result.Errors));
        }
        public ActionResult Index(RegisterInputModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var account = this.userAccountService.CreateAccount(model.Username, model.Password, model.Email);

                    // add our custom stuff
                    account.FirstName = model.FirstName;
                    account.LastName  = model.LastName;
                    this.userAccountService.Update(account);

                    if (userAccountService.Configuration.RequireAccountVerification)
                    {
                        return(View("Success", model));
                    }
                    else
                    {
                        return(View("Confirm", true));
                    }
                }
                catch (ValidationException ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return(View(model));
        }
        public IActionResult Register(RegisterInputModel model)
        {
            if (this.User.Identity.IsAuthenticated)
            {
                return(this.RedirectToAction("Index", "Home"));
            }

            if (ModelState.IsValid)
            {
                var user = new EventuresUser
                {
                    Email               = model.Email,
                    UserName            = model.Username,
                    FirstName           = model.FirstName,
                    LastName            = model.LastName,
                    UniqueCitizenNumber = model.UCN,
                };

                var result = this.userManager.CreateAsync(user, model.Password).GetAwaiter().GetResult();

                var roleResult = this.userManager.AddToRoleAsync(user, "User").GetAwaiter().GetResult();
                if (roleResult.Errors.Any())
                {
                    return(this.View());
                }

                if (result.Succeeded)
                {
                    this.signIn.SignInAsync(user, true).Wait();
                    return(this.RedirectToAction("Index", "Home"));
                }
            }

            return(this.View());
        }
Esempio n. 11
0
        public ActionResult Register()
        {
            RegisterInputModel model = new RegisterInputModel();

            model.userRoles = _userManager.GetListUserRoles();
            return(View(model));
        }
Esempio n. 12
0
 public HttpResponse Register(RegisterInputModel inputModel)
 {
     if (inputModel.Password != inputModel.ConfirmPassword)
     {
         return(this.Register());
     }
     if (inputModel.Username.Length < 5 || inputModel.Username.Length > 20)
     {
         return(this.Register());
     }
     if (inputModel.Password.Length < 6 || inputModel.Password.Length > 20)
     {
         return(this.Register());
     }
     if (!new EmailAddressAttribute().IsValid(inputModel.Email))
     {
         return(this.Register());
     }
     if (!this.userService.IsEmailAvailable(inputModel.Email) || !this.userService.IsUsernameAvailable(inputModel.Username))
     {
         return(this.Register());
     }
     this.userService.CreateUser(inputModel.Username, inputModel.Email, inputModel.Password);
     return(this.Redirect("/Users/Login"));
 }
Esempio n. 13
0
        public async Task <IActionResult> Register([FromBody] RegisterInputModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser()
                {
                    UserName = model.UserName,
                    Email    = model.Email
                };

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

                if (!result.Succeeded)
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, new ResponseOutputModel {
                        Status = StatusCodes.Status500InternalServerError, Message = result.Errors.Select(s => s.Description).FirstOrDefault()
                    }));
                }

                if (!await _roleManager.RoleExistsAsync(Roles.User))
                {
                    await _roleManager.CreateAsync(new ApplicationRole { Name = Roles.User });
                }

                if (await _roleManager.RoleExistsAsync(Roles.User))
                {
                    await _userManager.AddToRoleAsync(user, Roles.User);
                }

                return(Ok());
            }

            return(BadRequest());
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Register([FromBody] RegisterInputModel model)
        {
            var user = new UserIdentity
            {
                UserName            = model.Login,
                PhoneNumber         = model.Phone,
                OrganizationName    = model.OrganizationName,
                OrganizationType    = model.OrganizationType,
                OrganizationVariant = model.OrganizationVariant
            };

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

            if (result.Succeeded)
            {
                _sender.Send(new CreateUserCommand(user));
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
                await _signInManager.SignInAsync(user, isPersistent : false);

                //_logger.LogInformation(3, "User created a new account with password.");
                //return RedirectToLocal(returnUrl);

                return(Ok());
            }
            //AddErrors(result);


            // If we got this far, something failed, redisplay form
            return(BadRequest(result.Errors.First()));
        }
Esempio n. 15
0
        public HttpResponse Register(RegisterInputModel input)
        {
            if (this.IsUserSignedIn())
            {
                return(this.Redirect("/"));
            }
            if (string.IsNullOrEmpty(input.Username) || input.Username.Length < 5 || input.Username.Length > 20)
            {
                return(this.Error("Username should be between 5 and 20 characters!"));
            }
            if (!userService.IsUsernameAvailable(input.Username))
            {
                return(this.Error("The username is already taken."));
            }
            if (string.IsNullOrWhiteSpace(input.Email) || !new EmailAddressAttribute().IsValid(input.Email))
            {
                return(this.Error("Invalid email address."));
            }
            if (!userService.IsEmailAvailable(input.Email))
            {
                return(this.Error("The email is already taken!"));
            }
            if (string.IsNullOrWhiteSpace(input.Password) || input.Password.Length < 6 || input.Password.Length > 20)
            {
                return(this.Error("Password must be between 6 and 20 characters!"));
            }
            if (input.Password != input.ConfirmPassword)
            {
                return(this.Error("The passwords are not identical."));
            }

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

            return(this.Redirect("/Users/Login"));
        }
Esempio n. 16
0
        public async Task <IActionResult> Register(RegisterInputModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (model.Username == null ||
                    model.Password == null ||
                    model.Email == null ||
                    model.FirstName == null ||
                    model.LastName == null ||
                    model.ConfirmPassword == null)
                {
                    return(this.View(model));
                }

                var userCreateResult = this._accountService.Create(model);
                if (await userCreateResult)
                {
                    if (returnUrl == null)
                    {
                        return(RedirectToAction(nameof(HomeController.Index), "Home"));
                    }

                    return(RedirectToAction(returnUrl));
                }
            }

            return(View(model));
        }
Esempio n. 17
0
        public async Task<IActionResult> Register(RegisterInputModel inputModel)
        {
            if (this.ModelState.IsValid)
            {
                var userId = Guid.NewGuid().ToString();

                var user = new ApplicationUser
                {
                    Id = userId,
                    UserName = inputModel.Username,
                    Email = inputModel.Email,
                };

                var result = await this.userManager.CreateAsync(user, inputModel.Password);

                if (result.Succeeded)
                {
                    await this.profilePicturesService.AddPictureAsync("wwwroot/images/DefaultPhoto.png", userId);
                    await this.signInManager.SignInAsync(user, isPersistent: false);
                    return this.Redirect("/");
                }

                foreach (var error in result.Errors)
                {
                    this.ModelState.AddModelError(string.Empty, error.Description);
                }

                return this.Register();
            }

            return this.Register();
        }
Esempio n. 18
0
        public HttpResponse Register(RegisterInputModel input)
        {
            if (input.Password.Length < MinPasswordLength || input.Password.Length > MaxPasswordLength)
            {
                return(this.Redirect("/Users/Register"));
            }

            if (input.Username.Length < MinUsernameLength || input.Username.Length > MaxUsernameLength)
            {
                return(this.Redirect("/Users/Register"));
            }

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

            if (string.IsNullOrWhiteSpace(input.Email))
            {
                return(this.Redirect("/Users/Register"));
            }

            if (this.usersService.EmailExists(input.Email))
            {
                return(this.Redirect("/Users/Register"));
            }

            if (this.usersService.UsernameExists(input.Username))
            {
                return(this.Redirect("/Users/Register"));
            }

            this.usersService.Register(input.Username, input.Email, input.Password);
            return(this.Redirect("/Users/Login"));
        }
Esempio n. 19
0
        public async Task <IActionResult> Register(RegisterInputModel parameters)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(state => state.Errors)
                                  .Select(error => error.ErrorMessage)
                                  .FirstOrDefault()));
            }

            var user = new AppUser();

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

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

            return(await Login(new LoginInputModel
            {
                Key = parameters.UserName,
                Password = parameters.Password
            }));
        }
Esempio n. 20
0
        public HttpResponse Register(RegisterInputModel registerInputModel)
        {
            if (registerInputModel.Username.Length < 4 ||
                registerInputModel.Username.Length > 10)
            {
                return(this.Error("Invalid Username lenght!"));
            }

            if (registerInputModel.Password.Length < 6 ||
                registerInputModel.Password.Length > 20)
            {
                return(this.Error("Invalid Password lenght!"));
            }

            if (registerInputModel.Password != registerInputModel.ConfirmPassword)
            {
                return(this.Error("Password must be same as ConfirmPassword!"));
            }

            if (this.usersService.EmailExists(registerInputModel.Email))
            {
                return(this.Error("This Email is already taken!"));
            }

            if (this.usersService.UsernameExists(registerInputModel.Username))
            {
                return(this.Error("This Username is already taken!"));
            }

            this.usersService.Register(registerInputModel.Username,
                                       registerInputModel.Email, registerInputModel.Password);

            return(this.Redirect("/Users/Login"));
        }
        public async Task <IActionResult> Register([FromForm] RegisterInputModel model)
        {
            //var aVal = 0; var blowUp = 1 / aVal;

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new AppUser {
                UserName = model.Username, Name = $"{model.FirstName} {model.LastName}", Email = $"{model.Username}@monstersinc.com", ScareStartDate = model.ScareStartDate
            };

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

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

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("userName", user.UserName));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("name", user.Name));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("PhoneNumber", model.PhoneNumber));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("TentaclesNumber", model.TentaclesNumber.ToString()));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("ScareStartDate", model.ScareStartDate.ToString()));

            await _userManager.AddClaimAsync(user, new System.Security.Claims.Claim("role", Roles.Consumer));

            return(Ok(new RegisterResponseViewModel(user)));
        }
Esempio n. 22
0
        public HttpResponse Register(RegisterInputModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Username) || model.Username.Length < 5 || model.Username.Length > 20)
            {
                return(this.Error("Invalid username input.Username should be between 5 and 20 characters."));
            }
            if (string.IsNullOrWhiteSpace(model.Password) || model.Password.Length < 6 || model.Password.Length > 20)
            {
                return(this.Error("Invalid password input.Password should be between 6 and 20 characters."));
            }
            if (string.IsNullOrWhiteSpace(model.Email) || !new EmailAddressAttribute().IsValid(model.Email))
            {
                return(this.Error("Invalid email input."));
            }
            if (model.Password != model.ConfirmPassword)
            {
                return(this.Error("Passwords should match."));
            }
            if (!this.usersService.IsUsernameAvailable(model.Username))
            {
                return(this.Error("Username or email already taken."));
            }
            if (!this.usersService.IsEmailAvailable(model.Email))
            {
                return(this.Error("Username or email already taken."));
            }

            this.usersService.CreateUser(model.Username, model.Password, model.Email);
            return(this.Redirect("/Users/Login"));
        }
Esempio n. 23
0
        public IActionResult Register(RegisterInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Redirect("/Users/Register"));
            }

            if (model.Password != model.ConfirmPassword)
            {
                ModelState.Add(string.Empty, "The passwords must match");
                return(Redirect("/Users/Register"));
            }

            if (usersService.UserExists(model.Username))
            {
                ModelState.Add(string.Empty, "User with the same username already exists!");
                return(Redirect("/Users/Register"));
            }

            User   user   = model.MapTo <User>();
            string userId = usersService.CreateUser(user);

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

            return(Redirect("/"));
        }
Esempio n. 24
0
        public async Task <IActionResult> Register(RegisterInputModel model, string button)
        {
            if (button == "register")
            {
                //todo fix this

/*                if (model.Password.Equals(model.ConfirmPassword))
 *              {
 *                  Console.WriteLine(model.Password + " : " + model.ConfirmPassword);
 *                  return BadRequest("Passwords did not match");
 *              }*/

                var user = new AuctorUser
                {
                    Email = model.Email, UserName = model.Username, PhoneNumber = model.PhoneNumber, SecurityStamp = new Random().Next().ToString()
                };

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

                if (!res.Succeeded)
                {
                    foreach (var identityError in res.Errors)
                    {
                        Console.WriteLine(identityError.Code + " : " + identityError.Description);
                    }
                }
            }
            if (model.ReturnUrl != null)
            {
                return(Redirect(model.ReturnUrl));
            }

            return(Redirect("/"));
        }
Esempio n. 25
0
        public ActionResult AddDetailsPost(AddDetailsViewModel model)
        {
            // Create a user too if missing
            var customer = _service.GetCustomer(model.UserName);

            if (customer == null)
            {
                var register = new RegisterInputModel()
                {
                    UserName  = model.UserName,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Gender    = model.Gender,
                    Avatar    = model.Avatar
                };
                _service.Register(register);
            }

            var identity = IdentityHelpers.Create(model.UserName, model.Email, model.Gender, model.Avatar);

            AuthenticationManager.SignIn(new AuthenticationProperties {
                IsPersistent = true
            }, identity);
            return(RedirectToLocal(model.ReturnUrl));
        }
        public async Task RegisterMethodShouldRegisterUserSuccessfully()
        {
            var client             = this.factory.CreateClient();
            var registerInputModel = new RegisterInputModel
            {
                Email     = "*****@*****.**",
                FirstName = "Ivancho",
                LastName  = "Nenov",
                Username  = "******",
                Password  = "******"
            };

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

            var response = await client.PostAsync("/api/account/register", stringContent);

            var content = await response.Content.ReadAsStringAsync();

            var authObj = JsonConvert.DeserializeObject <AuthenticationViewModel>(content);

            response.EnsureSuccessStatusCode();
            Assert.Equal("You have successfully registered.", authObj.Message);
            Assert.NotNull(authObj.Token);
            Assert.Equal(261, authObj.Token.Length);
        }
Esempio n. 27
0
        public void RegisterUser_Should_Fail_With_Same_Username()
        {
            //arrange
            var toRegister = new RegisterInputModel
            {
                Nickname        = "NewUser",
                Password        = "******",
                ConfirmPassword = "******",
                Email           = "*****@*****.**",
                Username        = "******"
            };

            var user = new FanFictionUser
            {
                Nickname = "NewUserTwo",
                Email    = "*****@*****.**",
                UserName = "******"
            };

            this.userManager.CreateAsync(user).GetAwaiter();
            this.Context.SaveChanges();
            //act
            this.roleService.CreateAsync(new IdentityRole {
                Name = GlobalConstants.DefaultRole
            }).GetAwaiter();
            var result = this.userService.RegisterUser(toRegister).GetAwaiter().GetResult();

            //assert

            result.Should().BeEquivalentTo(SignInResult.Failed);
        }
Esempio n. 28
0
        public HttpResponse Register(RegisterInputModel input)
        {
            if (input.Password.Length < 6 || input.Password.Length > 20)
            {
                return(this.View());
            }

            if (input.Username.Length < 4 || input.Username.Length > 10)
            {
                return(this.View());
            }

            if (input.Password != input.ConfirmPassword)
            {
                return(this.View());
            }

            if (this.usersService.EmailExists(input.Email))
            {
                return(this.View());
            }

            if (this.usersService.UsernameExists(input.Username))
            {
                return(this.View());
            }

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

            return(this.Redirect("/Users/Login"));
        }
Esempio n. 29
0
        public UserDto CreateUser(RegisterInputModel inputModel)
        {
            var user = _dbContext.Users.FirstOrDefault(u => u.Email == inputModel.Email);

            if (user != null)
            {
                throw new Exception("User already exist");
            }

            var entity = new UserEntity
            {
                Email          = inputModel.Email,
                FullName       = inputModel.FullName,
                HashedPassword = HashingHelper.HashPassword(inputModel.Password)
            };

            _dbContext.Users.Add(entity);
            _dbContext.SaveChanges();

            var token = new JwtToken();

            _dbContext.JwtTokens.Add(token);
            _dbContext.SaveChanges();

            return(new UserDto
            {
                Id = _dbContext.Users.FirstOrDefault(u => u.Email == inputModel.Email).Id,
                FullName = entity.FullName,
                Email = entity.Email,
                TokenId = token.Id
            });
        }
Esempio n. 30
0
        public HttpResponse Register(RegisterInputModel inputModel)
        {
            if (string.IsNullOrWhiteSpace(inputModel.Email))
            {
                return(this.Error("Email cannot be empty!"));
            }

            if (inputModel.Password.Length < 6 || inputModel.Password.Length > 20)
            {
                return(this.Error("Password must be at least 6 characters and at most 20"));
            }

            if (inputModel.Username.Length < 4 || inputModel.Username.Length > 10)
            {
                return(this.Error("Username must be at least 4 characters and at most 10"));
            }

            if (inputModel.Password != inputModel.ConfirmPassword)
            {
                return(this.Error("Password should match."));
            }

            if (this.usersService.EmailExists(inputModel.Email))
            {
                return(this.Error("Email already in use."));
            }

            if (this.usersService.UsernameExists(inputModel.Username))
            {
                return(this.Error("Username already in use."));
            }

            this.usersService.Register(inputModel.Username, inputModel.Email, inputModel.Password);
            return(this.Redirect("/Users/Login"));
        }
Esempio n. 31
0
        public ActionResult Register(RegisterInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var acc = Adapter.CheckAccount(model.Login);
            if (acc != null && acc.Login != null)
            {
                ModelState.AddModelError("Login", "Пользователь с таким логином уже существует!");
            }

            //Чтобы показать новые ошибки
            if (!ModelState.IsValid)
            {
                if (Request.IsAjaxRequest())
                {
                    return PartialView(model);
                }
                return View(model);
            }

            Account account = new Account
            {
                Login = model.Login,
                Password = Adapter.GetSHA256(model.Password),
                Email = model.Email
            };

            bool success = Adapter.CreateUserAndAccount(account);
            if (success)
            {
                FormsAuthentication.SetAuthCookie(account.Login, true);
            }

            return RedirectToAction("Index", "Home");
        }