-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProfileController.cs
More file actions
217 lines (193 loc) · 7.39 KB
/
Copy pathProfileController.cs
File metadata and controls
217 lines (193 loc) · 7.39 KB
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
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Glense.AccountService.Data;
using Glense.AccountService.DTOs;
namespace Glense.AccountService.Controllers
{
[ApiController]
[Route("api/profile")]
public class ProfileController : ControllerBase
{
private readonly AccountDbContext _context;
private readonly ILogger<ProfileController> _logger;
public ProfileController(AccountDbContext context, ILogger<ProfileController> logger)
{
_context = context;
_logger = logger;
}
private Guid GetCurrentUserId()
{
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (!Guid.TryParse(userIdClaim, out var userId))
throw new UnauthorizedAccessException("Invalid or missing user identity claim");
return userId;
}
[HttpGet("search")]
public async Task<IActionResult> SearchUsers([FromQuery] string? q, [FromQuery] int limit = 20)
{
try
{
var query = _context.Users.Where(u => u.IsActive);
if (!string.IsNullOrWhiteSpace(q))
{
var search = q.ToLower();
query = query.Where(u =>
u.Username.ToLower().Contains(search) ||
u.Email.ToLower().Contains(search));
}
var users = await query
.OrderBy(u => u.Username)
.Take(limit)
.Select(u => new UserDto
{
Id = u.Id,
Username = u.Username,
Email = u.Email,
ProfilePictureUrl = u.ProfilePictureUrl,
AccountType = u.AccountType,
CreatedAt = u.CreatedAt
})
.ToListAsync();
return Ok(users);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error searching users");
return StatusCode(500, new { message = "An error occurred" });
}
}
[Authorize]
[HttpGet("me")]
public async Task<IActionResult> GetMyProfile()
{
try
{
var userId = GetCurrentUserId();
var user = await _context.Users.FindAsync(userId);
if (user == null) return NotFound();
var dto = new UserDto
{
Id = user.Id,
Username = user.Username,
Email = user.Email,
ProfilePictureUrl = user.ProfilePictureUrl,
AccountType = user.AccountType,
CreatedAt = user.CreatedAt
};
return Ok(dto);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting current user");
return StatusCode(500, new { message = "An error occurred" });
}
}
[HttpGet("{userId:guid}")]
public async Task<IActionResult> GetById(Guid userId)
{
try
{
var user = await _context.Users
.Where(u => u.Id == userId && u.IsActive)
.FirstOrDefaultAsync();
if (user == null) return NotFound();
var dto = new UserDto
{
Id = user.Id,
Username = user.Username,
Email = user.Email,
ProfilePictureUrl = user.ProfilePictureUrl,
AccountType = user.AccountType,
CreatedAt = user.CreatedAt
};
return Ok(dto);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting user by ID");
return StatusCode(500, new { message = "An error occurred" });
}
}
[Authorize]
[HttpPut("me")]
public async Task<ActionResult<UserDto>> UpdateProfile([FromBody] UpdateProfileDto updateDto)
{
try
{
var userId = GetCurrentUserId();
var user = await _context.Users.FindAsync(userId);
if (user == null)
{
return NotFound(new { message = "User not found" });
}
// Update username if provided
if (!string.IsNullOrWhiteSpace(updateDto.Username) && updateDto.Username != user.Username)
{
var usernameExists = await _context.Users.AnyAsync(u => u.Username == updateDto.Username && u.Id != userId);
if (usernameExists)
{
return BadRequest(new { message = "Username already taken" });
}
user.Username = updateDto.Username;
}
// Update email if provided
if (!string.IsNullOrWhiteSpace(updateDto.Email) && updateDto.Email != user.Email)
{
var emailExists = await _context.Users.AnyAsync(u => u.Email == updateDto.Email && u.Id != userId);
if (emailExists)
{
return BadRequest(new { message = "Email already in use" });
}
user.Email = updateDto.Email;
user.IsVerified = false; // Reset verification when email changes
}
// Update profile picture if provided
if (updateDto.ProfilePictureUrl != null)
{
user.ProfilePictureUrl = updateDto.ProfilePictureUrl;
}
await _context.SaveChangesAsync();
return Ok(new UserDto
{
Id = user.Id,
Username = user.Username,
Email = user.Email,
ProfilePictureUrl = user.ProfilePictureUrl,
AccountType = user.AccountType,
CreatedAt = user.CreatedAt,
IsVerified = user.IsVerified
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating profile");
return StatusCode(500, new { message = "An error occurred" });
}
}
[Authorize]
[HttpDelete("me")]
public async Task<IActionResult> DeleteAccount()
{
try
{
var userId = GetCurrentUserId();
var user = await _context.Users.FindAsync(userId);
if (user == null)
{
return NotFound(new { message = "User not found" });
}
// Soft delete
user.IsActive = false;
await _context.SaveChangesAsync();
return Ok(new { message = "Account deactivated successfully" });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error deleting account");
return StatusCode(500, new { message = "An error occurred" });
}
}
}
}