public async Task <IActionResult> UpdateUser(int id, UserFormDto userFormDto) { if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)) // Makes sure the user that is being edited is the person who is logged in { return(Unauthorized()); } var currentUser = await _repository.GetUser(id); _mapper.Map(userFormDto, currentUser); // Update just the matching values between these objects return(await _repository.SaveAll() ? NoContent() : throw new Exception($"Updating user {id} failed on save.")); }
public async Task <IActionResult> Register(UserFormDto userFormDto) { userFormDto.Email = userFormDto.Email.ToLower(); if (await _db.Users.AnyAsync(x => x.Email == userFormDto.Email)) { return(BadRequest("Taki email już istnieje.")); } var userToCreate = new User { Email = userFormDto.Email, Created = DateTime.Now }; var createdUser = await RegisterInDb(userToCreate, userFormDto.Password); return(StatusCode(201)); }
public async Task <IActionResult> Login(UserFormDto userFormDto) { var userFromRepo = await LoginInDb(userFormDto.Email.ToLower(), userFormDto.Password); if (userFromRepo == null) { return(Unauthorized()); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.Email) }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(_configuration.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(new { token = tokenHandler.WriteToken(token) })); }