File size: 8,471 Bytes
70556b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
using Application.Abstractions.Interfaces;
using Application.DTOs.UserDTOs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RobDeliveryAPI.Extensions;
using System.Security.Claims;
using System.Threading.Tasks;

namespace RobDeliveryAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IWebHostEnvironment _environment;

        public UserController(
            IUserService userService,
            IWebHostEnvironment environment)
        {
            _userService = userService;
            _environment = environment;
        }

        /// <summary>
        /// Get full profile of authenticated user
        /// </summary>
        [HttpGet("profile")]
        public async Task<IActionResult> GetProfile()
        {
            var userIdClaim = User.FindFirst("Id")?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
            {
                return Unauthorized(new { error = "Invalid token" });
            }

            try
            {
                var profile = await _userService.GetProfileAsync(userId);
                if (profile == null)
                {
                    return NotFound(new { error = "User not found" });
                }

                return Ok(profile);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while retrieving profile", details = ex.Message });
            }
        }

        /// <summary>
        /// Get profile photo of authenticated user
        /// </summary>
        [HttpGet("profile/photo")]
        public async Task<IActionResult> GetProfilePhoto()
        {
            var userIdClaim = User.FindFirst("Id")?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
            {
                return Unauthorized(new { error = "Invalid token" });
            }

            try
            {
                var photo = await _userService.GetProfilePhotoAsync(userId);
                if (photo == null)
                {
                    return NotFound(new { error = "Profile photo not found" });
                }

                var fileBytes = await _userService.GetProfilePhotoContentAsync(userId, _environment.ContentRootPath);
                if (fileBytes == null)
                {
                    return NotFound(new { error = "Profile photo file not found on disk" });
                }

                return File(fileBytes, photo.ContentType, photo.FileName);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while retrieving profile photo", details = ex.Message });
            }
        }

        /// <summary>
        /// Get profile photo of specific user by ID
        /// </summary>
        [HttpGet("{userId}/photo")]
        [Authorize]
        public async Task<IActionResult> GetUserPhoto(int userId)
        {
            try
            {
                var photo = await _userService.GetProfilePhotoAsync(userId);
                if (photo == null)
                {
                    return NotFound(new { error = "Profile photo not found" });
                }

                var fileBytes = await _userService.GetProfilePhotoContentAsync(userId, _environment.ContentRootPath);
                if (fileBytes == null)
                {
                    return NotFound(new { error = "Profile photo file not found on disk" });
                }

                return File(fileBytes, photo.ContentType, photo.FileName);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while retrieving profile photo", details = ex.Message });
            }
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetUserById(int id)
        {
            var userDto = await _userService.GetUserByIdAsync(id);
            if (userDto == null)
            {
                return NotFound(new { error = "User not found" });
            }

            return Ok(userDto);
        }

        [HttpGet("my-node")]
        public async Task<IActionResult> GetMyNode()
        {
            var userIdClaim = User.FindFirst("Id")?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
            {
                return Unauthorized(new { error = "Invalid token" });
            }

            try
            {
                var nodeDTO = await _userService.GetMyNodeAsync(userId);
                if (nodeDTO == null)
                {
                    return NotFound(new { error = "Personal node not found" });
                }

                return Ok(nodeDTO);
            }
            catch (ArgumentException ex)
            {
                return NotFound(new { error = ex.Message });
            }
        }

        [HttpPut("my-node")]
        public async Task<IActionResult> UpdateMyNode([FromBody] UpdateMyNodeDTO updateDto)
        {
            var userIdClaim = User.FindFirst("Id")?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
            {
                return Unauthorized(new { error = "Invalid token" });
            }

            try
            {
                var nodeDTO = await _userService.UpdateMyNodeAsync(userId, updateDto);
                return Ok(new { message = "Personal node updated successfully", node = nodeDTO });
            }
            catch (ArgumentException ex)
            {
                return NotFound(new { error = ex.Message });
            }
        }

        [HttpGet]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> GetAllUsers()
        {
            var userDTOs = await _userService.GetAllUsersAsync();
            return Ok(userDTOs);
        }

        [HttpGet("search")]
        public async Task<IActionResult> SearchUsers([FromQuery] string? query)
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return BadRequest(new { error = "Search query cannot be empty" });
            }

            var userIdClaim = User.FindFirst("Id")?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out int currentUserId))
            {
                return Unauthorized(new { error = "Invalid token" });
            }

            try
            {
                var userDTOs = await _userService.SearchUsersAsync(query, currentUserId);
                return Ok(userDTOs);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { error = ex.Message });
            }
        }

        /// <summary>
        /// Update user profile (username, phone, password, and profile photo)
        /// </summary>
        [HttpPut("profile")]
        [Consumes("multipart/form-data")]
        public async Task<IActionResult> UpdateProfile(
            [FromForm] string? userName,
            [FromForm] string? phoneNumber,
            [FromForm] string? password,
            IFormFile? profilePhoto)
        {
            var userIdClaim = User.FindFirst("Id")?.Value;
            if (userIdClaim == null || !int.TryParse(userIdClaim, out int userId))
            {
                return Unauthorized(new { error = "Invalid token" });
            }

            try
            {
                var updateDto = new UpdateUserProfileDTO
                {
                    UserName = userName,
                    PhoneNumber = phoneNumber,
                    Password = password
                };

                var updatedProfile = await _userService.UpdateProfileWithPhotoAsync(userId, updateDto, profilePhoto?.ToFileUploadDTO(), _environment.ContentRootPath);

                return Ok(new { message = "Profile updated successfully", profile = updatedProfile });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { error = "An error occurred while updating profile", details = ex.Message });
            }
        }
    }
}