File size: 2,480 Bytes
87c9973
c596926
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87c9973
f53877e
87c9973
 
 
 
 
 
 
f53877e
87c9973
 
 
 
 
 
 
c596926
87c9973
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f53877e
87c9973
 
 
 
 
 
 
 
f53877e
87c9973
c596926
87c9973
 
 
 
 
 
f53877e
87c9973
 
 
 
 
c596926
 
 
87c9973
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace LibraryManagement.Backend.Features.Users
{
    [ApiController]
    [Route("api/users")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpGet]
        //[Authorize(Roles = "Librarian")]
        public async Task<ActionResult<IEnumerable<UserDto>>> GetUsers()
        {
            var users = await _userService.GetAllUsersAsync();
            return Ok(users);
        }

        [HttpGet("{id}")]
        //[Authorize(Roles = "Librarian")]
        public async Task<ActionResult<UserDto>> GetUser(int id)
        {
            var user = await _userService.GetUserByIdAsync(id);
            if (user == null) return NotFound();
            return Ok(user);
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult<UserDto>> CreateUser([FromBody] UserCreateRequest request)
        {
            try
            {
                var response = await _userService.CreateUserAsync(request);
                return CreatedAtAction(nameof(GetUser), new { id = response.Id }, response);
            }
            catch (Exception ex)
            {
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPut("{id}")]
        //[Authorize(Roles = "Librarian")]
        public async Task<ActionResult<UserDto>> UpdateUser(int id, [FromBody] UserUpdateRequest request)
        {
            var updatedUser = await _userService.UpdateUserAsync(id, request);
            if (updatedUser == null) return NotFound();
            return Ok(updatedUser);
        }

        [HttpPatch("{id}/role")]
        //[Authorize(Roles = "Librarian")]
        public async Task<IActionResult> UpdateUserRole(int id, [FromBody] UserRoleUpdateRequest request)
        {
            var success = await _userService.UpdateUserRoleAsync(id, request.Role);
            if (!success) return NotFound();
            return NoContent();
        }

        [HttpDelete("{id}")]
        //[Authorize(Roles = "Librarian")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            var success = await _userService.DeleteUserAsync(id);
            if (!success) return NotFound();
            return NoContent();
        }
    }
}