summaryrefslogtreecommitdiff
path: root/backend/Elements.Backend/Controllers/UserController.cs
blob: bde93aa9b28da08711f88b26621eb43cdc8198fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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<IActionResult> Users(int id)
    {
        IEnumerable<Claim> 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);
    }
}