Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [Produces("application/json")]
- // [Route("api/[controller]")]
- public class WordsController : Controller
- {
- public AppDbContext _db;
- private readonly OpenIddictUserManager<ApplicationUser> _userManager;
- public WordsController(AppDbContext context, OpenIddictUserManager<ApplicationUser> userManager)
- {
- _db = context;
- _userManager = userManager;
- }
- [HttpGet("api/[controller]")]
- public IEnumerable<object> Get()
- {
- return _db.Words.Include(y => y.Author).Select(x => new WordViewModel
- {
- ID = x.ID,
- Title = x.Title,
- AuthorName = x.Author.UserName,
- WhenCreated = x.WhenCreated
- }
- ).ToList();
- }
- [HttpPost("api/[controller]")]
- [Authorize]
- public void Post([FromBody] WordViewModel data)
- {
- ApplicationUser user = GetCurrentUser();
- Word word = new Word
- {
- Title = data.Title,
- WhenCreated = DateTime.Now,
- Author = user
- };
- _db.Words.Add(word);
- _db.SaveChanges();
- }
- [HttpPut("api/[controller]")]
- public IActionResult Put([FromBody] WordViewModel data)
- {
- if (data.ID != null)
- {
- Word dbWord = _db.Words.Where(x => x.ID == data.ID).FirstOrDefault();
- if (dbWord == null)
- {
- return NotFound();
- }
- if (CheckIfOwner(dbWord.Author))
- {
- return Unauthorized();
- }
- dbWord.Title = data.Title;
- _db.SaveChanges();
- return Ok();
- }
- else
- {
- return BadRequest("ID is required");
- }
- }
- [HttpDelete("api/[controller]")]
- [Authorize]
- public IActionResult Delete(int id)
- {
- Word dbWord = _db.Words.Where(x => x.ID == id).Include(x => x.Author).FirstOrDefault();
- if (dbWord == null)
- {
- return NotFound();
- }
- if (CheckIfOwner(dbWord.Author))
- {
- _db.Words.Remove(dbWord);
- _db.SaveChanges();
- return Ok();
- }
- else
- {
- return Unauthorized();
- }
- }
- /// <summary>
- /// Gets currently logged in user
- /// </summary>
- public ApplicationUser GetCurrentUser()
- {
- return _userManager.Users.FirstOrDefault(x => x.NormalizedUserName == User.Identity.Name);
- }
- /// <summary>
- /// Checks if user is the same as currently logged in one
- /// </summary>
- public bool CheckIfOwner(ApplicationUser userToCompare)
- {
- ApplicationUser currentUser = GetCurrentUser();
- return currentUser.Id == userToCompare.Id;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement