public async Task <IActionResult> PostContact([FromBody] ContactForModificationsDto contactForModificationsDto) { var invokingUserId = int.Parse(User.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier).Value); //trying to update an existing Contact not created by invokingUserId var res = await _repository.GetContactByNameAsync(contactForModificationsDto.ContactName); if (res != null && res.CreatedByUserId != invokingUserId) { return(BadRequest("You're trying to modify a Contact not created by you!")); } var contact = await _repository.CreateOrUpdateContactByNameAsync(invokingUserId, contactForModificationsDto); var contactDto = _mapper.Map <Contact, ContactDto>(contact); return(Ok(contactDto)); }
public async Task <Contact> CreateOrUpdateContactByNameAsync(int invokingUserId, ContactForModificationsDto contactForModificationsDto) { var contact = await _reservationDbContext.Contacts.EagerLoadRelatedObjects() .SingleOrDefaultAsync( contact => contact.Name.ToLower() == contactForModificationsDto.ContactName.ToLower()); var toAdd = contact == null; //trying to modify contact and invokingUserId is the creator of this contact then modify properties //if not then use the contact without modifying its properties. if (!toAdd && invokingUserId == contact.CreatedByUserId) { _mapper.Map <ContactForModificationsDto, Contact>(contactForModificationsDto, contact); } else if (toAdd) { contact = _mapper.Map <ContactForModificationsDto, Contact>(contactForModificationsDto); } if (toAdd) { contact.CreatedByUserId = invokingUserId; await _reservationDbContext.Contacts.AddAsync(contact); } await _unitOfWork.CompleteAsync(); return(await GetContactAsync(contact.Id)); }