Backend for the Teso project written in 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.2 KiB

3 months ago
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using Teso_API.Models;
namespace Teso_API.Controllers
{
[AllowAnonymous, Route("favoriteCategories")]
[ApiController]
public class UserFavCategoriesController : ControllerBase
{
private readonly TESOContext _context;
public UserFavCategoriesController(TESOContext context)
{
_context = context;
}
[Authorize]
[Route("pullUser"), HttpPost]
public async Task<IEnumerable<UserFavCategory>> GetUserFavCategory([FromBody]string id)
{
List<UserFavCategory> userFavCategory = await _context.UserFavCategories.AsQueryable().Where(i => i.UserGuid == id).ToListAsync();
if (userFavCategory == null)
{
userFavCategory = new List<UserFavCategory>();
}
return userFavCategory;
}
[Authorize]
[Route("updateFavorites"), HttpPost]
public async Task<ActionResult> GeUpdateUserFavCategory(List<UserFavCategory> favCategory)
{
var accessToken = Request.Headers[HeaderNames.Authorization];
string token = accessToken;
token = token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadToken(token) as JwtSecurityToken;
string userID = jwtToken.Claims.First(claim => claim.Type == "userGUID").Value;
List<UserFavCategory> oldFav = await _context.UserFavCategories.AsQueryable().Where(u => u.UserGuid == userID).ToListAsync();
_context.UserFavCategories.RemoveRange(oldFav);
_context.UserFavCategories.AddRange(favCategory);
try
{
await _context.SaveChangesAsync();
return Ok();
}
catch (DbUpdateException)
{
return Conflict();
}
}
}
}