Ejemplo n.º 1
0
        private async Task LogInUserAsync(projeto_forum.Models.User user)
        {
            var claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Name, user.Name));
            if (user.IsAdministrator)
            {
                claims.Add(new Claim(ClaimTypes.Role, Roles.Administrator));
            }

            var claimsIndentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimsPrincipal = new ClaimsPrincipal(claimsIndentity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

            user.LastLogInDateTime = DateTime.Now;
            await _dbContext.SaveChangesAsync();
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new Exception("Invalid registration information.");
            }

            model.Name           = model.Name.Trim();
            model.Password       = model.Password.Trim();
            model.RepeatPassword = model.RepeatPassword.Trim();

            projeto_forum.Models.User user = _dbContext.User
                                             .SingleOrDefault(u => u.Name.Equals(model.Name, StringComparison.CurrentCultureIgnoreCase));
            var targetUser = user;

            if (targetUser != null)
            {
                throw new Exception("User name already exists.");
            }

            if (!model.Password.Equals(model.RepeatPassword))
            {
                throw new Exception("Passwords are not identical.");
            }

            var hasher = new PasswordHasher <projeto_forum.Models.User>();

            targetUser = new projeto_forum.Models.User {
                Name = model.Name, RegisterDateTime = DateTime.Now, Description = model.Description
            };
            targetUser.PasswordHash = hasher.HashPassword(targetUser, model.Password);

            if (_dbContext.User.Count() == 0)
            {
                targetUser.IsAdministrator = true;
            }

            await _dbContext.User.AddAsync(targetUser);

            await _dbContext.SaveChangesAsync();

            await LogInUserAsync(targetUser);

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