From 12fef7cbaf2073f9cc349ed765ea140be0259d8e Mon Sep 17 00:00:00 2001 From: Paweł Bernaciak Date: Sat, 21 Oct 2023 11:55:33 +0200 Subject: Basic API auth and Google login --- .../Elements.Backend/Controllers/UserController.cs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 backend/Elements.Backend/Controllers/UserController.cs (limited to 'backend/Elements.Backend/Controllers/UserController.cs') diff --git a/backend/Elements.Backend/Controllers/UserController.cs b/backend/Elements.Backend/Controllers/UserController.cs new file mode 100644 index 0000000..bde93aa --- /dev/null +++ b/backend/Elements.Backend/Controllers/UserController.cs @@ -0,0 +1,41 @@ +using System.Security.Claims; +using System.Text.Json; +using Elements.Data; +using Elements.Data.Models; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; + +namespace Elements.Backend.Controllers; + +[ApiController] +[Route("[controller]/[action]")] +public class UserController: ControllerBase +{ + private readonly ApplicationDbContext _dbContext; + + public UserController(ApplicationDbContext dbContext) + { + _dbContext = dbContext; + } + + [HttpGet] + [Authorize] + [Route("/user/{id:int}")] + public async Task Users(int id) + { + IEnumerable claims = User.Claims; + string? currentUserId = claims.FirstOrDefault(claim => claim.Type == "id")?.Value; + if (currentUserId == null) + return StatusCode(StatusCodes.Status500InternalServerError); + if (currentUserId != id.ToString()) + return Unauthorized(); + + User? user = await _dbContext.Users.FirstOrDefaultAsync(user => user.Id == id); + if (user == null) + return StatusCode(StatusCodes.Status500InternalServerError); + + string userJson = JsonSerializer.Serialize(user); + return Ok(userJson); + } +} \ No newline at end of file -- cgit v1.2.3