Skip to content

Commit

Permalink
API Response implementations and Major Code Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
gentcod committed May 17, 2024
1 parent 3158b54 commit 5a6dd81
Show file tree
Hide file tree
Showing 13 changed files with 346 additions and 111 deletions.
66 changes: 58 additions & 8 deletions API/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,87 @@
using API.Models;
using API.RequestHelpers;
using API.Token;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace API.Controllers;
public class AccountController(FoodieContext context, UserManager<User> userManager, JwtTokenGenerator tokenGenerator) : BaseApiController
{
private readonly FoodieContext _context = context;
private readonly UserManager<User> _usermanager = userManager;
private readonly UserManager<User> _userManager = userManager;
private readonly JwtTokenGenerator _tokenGenerator = tokenGenerator;

[HttpPost("login")]
public async Task<ActionResult<object>> Login(UserLoginDto loginDto)
public async Task<ActionResult<ApiSuccessResponse<object>>> Login(UserLoginDto loginDto)
{
var user = await _usermanager.FindByEmailAsync(loginDto.Email);
var authenticated = await _usermanager.CheckPasswordAsync(user, loginDto.Password);
var user = await _userManager.FindByEmailAsync(loginDto.Email);
var authenticated = await _userManager.CheckPasswordAsync(user, loginDto.Password);

if (user == null || !authenticated) return Unauthorized(new ProblemDetails { Title = "User account does not exist" });
if (user == null || !authenticated) return Unauthorized(new ProblemDetails
{
Title = "error",
Detail = "User account does not exist",
});

var token = await _tokenGenerator.CreateToken(user);
var userDto = new UserDto
{
Name = user.Name,
Username = user.UserName,
Name = user.Name,
Email = user.Email,
};

return new
var data = new
{
AccessToken = token,
User = userDto,
};

return Ok(ApiSuccessResponse<object>.Response(
"success",
"Account logged in successfully",
data
));
}

[HttpPost("signup")]
public async Task<ActionResult> Signup(UserSignupDto userSignupDto)
{
var existingUser = await _userManager.FindByEmailAsync(userSignupDto.Email);

if (existingUser != null) return BadRequest(ApiErrorResponse.Response(
"error",
"User account already exists. Please login"
));

var existingUserName = await _context.Users.FirstOrDefaultAsync(user => user.UserName == userSignupDto.Username.ToLower());

if (existingUserName != null) return BadRequest(ApiErrorResponse.Response(
"error",
"Username already taken. Please select a different username"
));

var user = new User
{
UserId = Guid.NewGuid().ToString(),
UserName = userSignupDto.Username,
Name = $"{userSignupDto.FirstName} {userSignupDto.LastName}",
Email = userSignupDto.Email,
};

var result = await _userManager.CreateAsync(user, userSignupDto.Password);
if (!result.Succeeded) return BadRequest(ApiErrorResponse.Response(
"error",
"Validation issues creating account"
));

await _userManager.AddToRoleAsync(user, "Member");

return StatusCode(201, ApiSuccessResponse<object>.Response(
"success",
"Account created successfully",
null
));
}
}
56 changes: 37 additions & 19 deletions API/Controllers/BookmarksController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using API.Data;
using API.DTOs;
using API.Extensions;
using API.Models;
using API.RequestHelpers;
Expand All @@ -22,53 +23,70 @@ public BookmarksController(FoodieContext context)


[HttpGet(Name = "GetBookmark")]
public async Task<ActionResult<Bookmarks>> GetBookMark()
public async Task<ActionResult> GetBookMark()
{
var userId = GetUserId();
Bookmarks bookmarks = await RetrieveBookmarks(userId);

if (bookmarks == null) return NotFound(new ProblemDetails
{
Detail = "Bookmarked Recipes could not be found"
});
if (bookmarks == null) return NotFound(ApiErrorResponse.Response(
"error",
"No bookmarks found"
));

IEnumerable<Bookmarks> enumerable = [bookmarks];
var bookmarksResult = enumerable.AsQueryable();
var respomse = bookmarksResult.MapBookmarksToDto();
return Ok(respomse);
var data = bookmarksResult.MapBookmarksToDto();

return Ok(ApiSuccessResponse<IQueryable<BookmarksDto>>.Response(
"success",
"Bookmarks have been fetched successfully",
data
));
}

[HttpPost("AddBookmark")]
public async Task<ActionResult<Bookmarks>> AddNewBookMark([BindRequired][FromQuery] BookmarkParams bookmarkParam)
public async Task<ActionResult> AddNewBookMark([BindRequired][FromQuery] BookmarkParams bookmarkParam)
{
var userId = GetUserId();
var bookmarks = await RetrieveBookmarks(userId);
bookmarks ??= CreateBookmarks(userId);

var recipe = await _context.Recipes.FindAsync(bookmarkParam.RecipeId);
if (recipe == null) return NotFound();
if (recipe == null) return BadRequest(ApiErrorResponse.Response(
"error",
"Recipe not found"
));

if (bookmarks.Recipes != null)
{
var existingBookmark = bookmarks.Recipes.FirstOrDefault(rec => rec.RecipeId == recipe.Id);
if (existingBookmark != null) return BadRequest(new ProblemDetails
{
Detail = "Recipe has been previously bookmarks"
});
if (existingBookmark != null) return BadRequest(ApiErrorResponse.Response(
"error",
"Recipe has been previously bookmarked"
));
}

bookmarks.AddBookmark(recipe);

IEnumerable<Bookmarks> enumerable = [bookmarks];
var bookmarksResult = enumerable.AsQueryable();
var data = bookmarksResult.MapBookmarksToDto();

var result = await _context.SaveChangesAsync() > 0;
if (result) return CreatedAtRoute("GetBookmark", bookmarksResult.MapBookmarksToDto());
var response = ApiSuccessResponse<IQueryable<BookmarksDto>>.Response(
"success",
"Bookmark has been added successfully",
data
);

return BadRequest(new ProblemDetails
{
Detail = "Problem creating bookmark"
});
var result = await _context.SaveChangesAsync() > 0;
if (result) return CreatedAtRoute("GetBookmark", response);

return BadRequest(
ApiErrorResponse.Response(
"error",
"Problem adding bookmark"
)
);
}

// private async Task<string> GetUserId()
Expand Down
21 changes: 18 additions & 3 deletions API/Controllers/CookieBookmarksController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using API.Data;
using API.DTOs;
using API.Extensions;
using API.Models;
using API.RequestHelpers;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -21,8 +23,22 @@ public ActionResult<Bookmarks> GetCookiesBookMarks()
{
Bookmarks bookmarks = RetrieveCookiesBookmarks(GetUserId());

if (bookmarks == null) return NotFound(new ProblemDetails { Title = "Bookmarked Recipes could not be found" });
return Ok(bookmarks);
if (bookmarks == null) return NotFound(ApiErrorResponse.Response(
"error",
"Bookmarked Recipes could not be found"
));

IEnumerable<Bookmarks> enumerable = [bookmarks];
var bookmarksResult = enumerable.AsQueryable();
var data = bookmarksResult.MapBookmarksToDto();

var response = ApiSuccessResponse<IQueryable<BookmarksDto>>.Response(
"success",
"Bookmarks have been fetched successfully",
data
);

return Ok(response);
}

[HttpPost("AddCookieBookmark")]
Expand All @@ -41,7 +57,6 @@ public async Task<ActionResult<Bookmarks>> AddNewCookiesBookMark([BindRequired][
return BadRequest(new ProblemDetails { Title = "Problem creating bookmark" });
}
return CreatedAtRoute("GetBookmark", cookieBookmark);

}

private string GetUserId()
Expand Down
80 changes: 56 additions & 24 deletions API/Controllers/FavoritesController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Security.Claims;
using API.Data;
using API.DTOs;
using API.Extensions;
using API.Models;
using API.RequestHelpers;
Expand All @@ -16,19 +17,24 @@ public class FavoritesController(FoodieContext context) : BaseApiController
private readonly FoodieContext _context = context;

[HttpGet(Name = "GetFavorites")]
public async Task<ActionResult<Favorites>> GetFavorites()
public async Task<ActionResult> GetFavorites()
{
Favorites favorites = await RetrieveFavorites(GetUserId());

if (favorites == null)
{
return NotFound();
};
if (favorites == null) return NotFound(ApiErrorResponse.Response(
"error",
"No favorites found"
));

IEnumerable<Favorites> enumerable = [favorites];
var favoritesResult = enumerable.AsQueryable();
var data = favoritesResult.MapFavoritesToDto();

return Ok(favoritesResult.MapFavoritesToDto());
return Ok(ApiSuccessResponse<IQueryable<FavoritesDto>>.Response(
"success",
"Favorites have been fetched successfully",
data
));
}

[HttpPost("AddRecipe")]
Expand All @@ -37,54 +43,80 @@ public async Task<ActionResult<Favorites>> AddNewFavoriteRecipe([BindRequired][F
var favorites = await InitializeFavorites(GetUserId());

var recipe = await _context.Recipes.FindAsync(favoriteRecipeParams.RecipeId);
if (recipe == null) return NotFound();
if (recipe == null) return BadRequest(ApiErrorResponse.Response(
"error",
"Recipe not found"
));

if (favorites.Recipes != null)
{
var existingBookmark = favorites.Recipes.FirstOrDefault(rec => rec.RecipeId == recipe.Id);
if (existingBookmark != null) return BadRequest(new ProblemDetails
{
Detail = "Recipe has been previously added to Favorites"
});
var existingFavRecipe = favorites.Recipes.FirstOrDefault(rec => rec.RecipeId == recipe.Id);
if (existingFavRecipe != null) return BadRequest(ApiErrorResponse.Response(
"error",
"Recipe has been previously added to Favorites"
));
}

favorites.AddFavoriteRecipe(recipe);

IEnumerable<Favorites> enumerable = [favorites];
var favoritesResult = enumerable.AsQueryable();
var data = favoritesResult.MapFavoritesToDto();

var response = ApiSuccessResponse<IQueryable<FavoritesDto>>.Response(
"success",
"Recipe has been added to Favorites successfully",
data
);

var result = _context.SaveChangesAsync();
if (result != null) return CreatedAtRoute("GetFavorites", favoritesResult.MapFavoritesToDto());
if (result != null) return CreatedAtRoute("GetFavorites", response);

return BadRequest(new ProblemDetails { Title = "Problem adding Favorite" });
return BadRequest(ApiErrorResponse.Response(
"error",
"Problem adding recipe to Favorite"
));
}

[HttpPost("AddRestaurant")]
public async Task<ActionResult<Favorites>> AddNewFavoriteRestaurant([BindRequired][FromQuery] FavoriteRestaurantParams favoriteRecipeParams)
public async Task<ActionResult> AddNewFavoriteRestaurant([BindRequired][FromQuery] FavoriteRestaurantParams favoriteRecipeParams)
{
var favorites = await InitializeFavorites(GetUserId());

var restaurant = await _context.Restaurants.FindAsync(favoriteRecipeParams.RestaurantId);
if (restaurant == null) return NotFound();
if (restaurant == null) return BadRequest(ApiErrorResponse.Response(
"error",
"Restaurant not found"
));

if (favorites.Recipes != null)
if (favorites.Restaurants != null)
{
var existingBookmark = favorites.Restaurants.FirstOrDefault(rec => rec.RestaurantId == restaurant.Id);
if (existingBookmark != null) return BadRequest(new ProblemDetails
{
Detail = "Restaurant has been previously added to Favorites"
});
var existingFavREstaurant = favorites.Restaurants.FirstOrDefault(rec => rec.RestaurantId == restaurant.Id);
if (existingFavREstaurant != null) return BadRequest(ApiErrorResponse.Response(
"error",
"Restaurant has been previously added to Favorites"
));
}

favorites.AddFavoriteRestaurant(restaurant);

IEnumerable<Favorites> enumerable = [favorites];
var favoritesResult = enumerable.AsQueryable();
var data = favoritesResult.MapFavoritesToDto();

var response = ApiSuccessResponse<IQueryable<FavoritesDto>>.Response(
"success",
"Restaurant has been added to Favorites successfully",
data
);

var result = _context.SaveChangesAsync();
if (result != null) return CreatedAtRoute("GetFavorites", favoritesResult.MapFavoritesToDto());
if (result != null) return CreatedAtRoute("GetFavorites", response);

return BadRequest(new ProblemDetails { Title = "Problem adding Favorite" });
return BadRequest( ApiErrorResponse.Response(
"error",
"Problem adding restaurant to Favorite"
));
}

private string GetUserId()
Expand Down
Loading

0 comments on commit 5a6dd81

Please sign in to comment.