Exemplo n.º 1
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    User user = await repository.GetUsers().FirstOrDefaultAsync(u => u.Email == model.Email);

                    if (user == null)
                    {
                        user = new User
                        {
                            Name      = model.Name,
                            Birthdate = model.Birthdate,
                            Email     = model.Email,
                            Password  = model.Password
                        };

                        Role userRole = await repository.GetRoles().FirstOrDefaultAsync(r => r.Name == "user");

                        if (userRole != null)
                        {
                            user.Role = userRole;
                        }

                        repository.AddUser(user);
                        repository.SaveAsync();

                        await Authenticate(user);

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Incorrect login or password!");
                    }
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return(View(model));
        }