public async Task <IActionResult> PutPost(Guid id, PostEditDTO postEditDTO)
        {
            if (id != postEditDTO.Id)
            {
                return(BadRequest("Post id in request does not match the id of Post to be edited"));
            }

            var post = await _context.Posts.FindAsync(id);

            if (post == null)
            {
                return(NotFound("Post to be edited does not exist"));
            }

            // Get user based on existing JWT Token or Guest User account.
            var user = await GetUserFromTokenOrDefault();

            // Return Unauthorized if no AppUser account could be assigned.
            if (user == null)
            {
                return(Unauthorized("Account could not be located."));
            }

            // Post does not belong to User.
            if (post.AppUser != user)
            {
                return(Unauthorized("User does not have permission to edit."));
            }

            _mapper.Map <PostEditDTO, Post>(postEditDTO, post);

            _context.Entry(post).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                var postExists = await PostExists(id);

                if (!postExists)
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemple #2
0
        /// <summary>
        /// Edits a post.
        /// The method is used in the admin area where the posts are managed.
        /// The "edit" button takes the user to /admin/posts/edit/id
        /// </summary>
        /// <param name="id"></param>
        public void EditPost(PostEditDTO data)
        {
            using (DbContext)
            {
                var postToEdit = DbContext.Posts.FirstOrDefault(e => e.Id == data.Id);

                postToEdit.Description = data.Description;
                postToEdit.CategoryId  = data.CategoryId;
                postToEdit.TagId       = data.TagId;
                postToEdit.Title       = data.Title;

                DbContext.SaveChanges();
            }
        }