Skip to content

Commit 2e390c9

Browse files
update refresh token
1 parent 6841576 commit 2e390c9

20 files changed

+1170
-83
lines changed

jjodel-persistence/jjodel-persistence/Controllers/API/AccountController.cs

Lines changed: 78 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -276,30 +276,24 @@ public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest) {
276276

277277
var roles = await this._signInManager.UserManager.GetRolesAsync(user);
278278

279-
List<Claim> claims = new List<Claim>();
280-
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
281-
claims.Add(new Claim(ClaimTypes.Email, user.Email));
282-
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id));
283-
claims.Add(new Claim("_Id", user._Id != null ? user._Id : "-"));
284-
foreach(var role in roles) {
285-
claims.Add(new Claim(ClaimTypes.Role, role));
279+
JwtSecurityToken token = this._authService.CreateJwtToken(user, roles.ToList());
280+
281+
if(token == null) {
282+
_logger.LogWarning("Token creation failed for user: " + loginRequest.Email);
283+
return BadRequest();
286284
}
287285

288-
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._jwtSettings.SecurityKey));
289-
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
290-
var expiry = DateTime.Now.AddMinutes(System.Convert.ToInt32(this._jwtSettings.ExpiresInMinutes));
291-
292-
var token = new JwtSecurityToken(
293-
_jwtSettings.Issuer,
294-
_jwtSettings.Audience,
295-
claims,
296-
expires: expiry,
297-
signingCredentials: creds
298-
);
299-
300-
response.Token = new JwtSecurityTokenHandler().WriteToken(token);
301-
response.Expires = expiry;
302-
return Ok(response);
286+
user.RefreshToken = AuthService.GenerateRefreshToken();
287+
user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(this._jwtSettings.RefreshTokenValidityInDays);
288+
await _userManager.UpdateAsync(user);
289+
290+
return Ok(
291+
new TokenResponse() {
292+
Token = new JwtSecurityTokenHandler().WriteToken(token),
293+
Expires = token.ValidTo,
294+
RefreshToken = user.RefreshToken,
295+
RefreshTokenExpiryTime = user.RefreshTokenExpiryTime
296+
});
303297
}
304298
return BadRequest();
305299
}
@@ -310,6 +304,46 @@ public async Task<IActionResult> Login([FromBody] LoginRequest loginRequest) {
310304
}
311305
}
312306

307+
[HttpPost]
308+
[Route("refresh-token")]
309+
public async Task<IActionResult> RefreshToken(RefreshTokenRequest request) {
310+
try {
311+
var principal = this._authService.GetPrincipalFromExpiredToken(request.Token);
312+
if(principal == null) {
313+
return BadRequest();
314+
}
315+
string username = principal.Identity.Name;
316+
ApplicationUser user = await _userManager.FindByNameAsync(username);
317+
318+
if(user == null || user.RefreshToken != request.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) {
319+
return BadRequest();
320+
}
321+
IList<string> roles = await _signInManager.UserManager.GetRolesAsync(user);
322+
323+
JwtSecurityToken token = this._authService.CreateJwtToken(user, roles.ToList());
324+
325+
if(token == null) {
326+
_logger.LogWarning("Token creation failed for user: " + username);
327+
return BadRequest();
328+
}
329+
330+
user.RefreshToken = AuthService.GenerateRefreshToken();
331+
332+
await _userManager.UpdateAsync(user);
333+
334+
return Ok(new TokenResponse() {
335+
Token = new JwtSecurityTokenHandler().WriteToken(token),
336+
Expires = token.ValidTo,
337+
RefreshToken = user.RefreshToken,
338+
RefreshTokenExpiryTime = user.RefreshTokenExpiryTime
339+
});
340+
}
341+
catch(Exception ex) {
342+
_logger.LogError("Refresh token error: " + ex.Message);
343+
return BadRequest();
344+
}
345+
}
346+
313347
[AllowAnonymous]
314348
[HttpPost("register")]
315349
public async Task<IActionResult> Register([FromBody] RegisterRequest request) {
@@ -459,6 +493,28 @@ public async Task<IActionResult> ResetPasswordWithEmail([FromBody] ResetPassword
459493
}
460494
}
461495

496+
[Authorize(Roles = "Admin, User")]
497+
[HttpPost]
498+
[Route("[action]")]
499+
public async Task<IActionResult> Revoke([FromBody] RevokeTokenRequest request) {
500+
try {
501+
ApplicationUser user = await _userManager.FindByNameAsync(request.UserName);
502+
if(user == null) {
503+
return BadRequest();
504+
}
505+
506+
user.RefreshToken = null;
507+
await this._userManager.UpdateAsync(user);
508+
509+
return Ok();
510+
}
511+
catch(Exception ex) {
512+
_logger.LogError($"Revoke token error for user {request.UserName}: " + ex.Message);
513+
return BadRequest();
514+
}
515+
}
516+
517+
462518
[Authorize(Roles = "Admin, User")]
463519
[HttpPut]
464520
public async Task<IActionResult> Update([FromBody] UpdateUserRequest updateUserRequest) {

jjodel-persistence/jjodel-persistence/Controllers/API/ClientLogController.cs

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ public async Task<IActionResult> SaveUserError([FromBody] CreateClientLog create
3535
try {
3636
if(ModelState.IsValid) {
3737
ClientLog clientLog = Convert(createClientLog, await this._userManager.FindByNameAsync(User.Identity.Name));
38-
3938

4039
if(await this._clientLogService.Add(clientLog)) {
4140
return Ok();
@@ -56,15 +55,24 @@ public static ClientLog Convert(CreateClientLog createClientLog, ApplicationUser
5655
Id = new Guid(),
5756
User = applicationUser,
5857
Level = createClientLog.Level,
59-
Title = createClientLog.Title,
58+
Url = createClientLog.Url,
6059
Version = createClientLog.Version,
60+
State = createClientLog.State,
6161
Creation = createClientLog.Creation,
62-
Message = createClientLog.Message,
63-
StackTrace = createClientLog.StackTrace,
64-
CompoStack = createClientLog.CompoStack,
65-
ContextJson = createClientLog.ContextJson,
66-
DState = createClientLog.DState,
67-
TransientJson = createClientLog.TransientJson
62+
Message = createClientLog.Error.Message,
63+
Error = createClientLog.Error.Error,
64+
CompoStack = createClientLog.CompoStack,
65+
ReactMsg = createClientLog.ReactMsg,
66+
Browser = createClientLog.Browser.Browser,
67+
BrowserMajorVersion = createClientLog.Browser.BrowserMajorVersion,
68+
BrowserVersion = createClientLog.Browser.BrowserVersion,
69+
Cookies = createClientLog.Browser.Cookies,
70+
Mobile = createClientLog.Browser.Mobile,
71+
Os = createClientLog.Browser.Os,
72+
OsVersion = createClientLog.Browser.OsVersion,
73+
Screen = createClientLog.Browser.Screen,
74+
UserAgent = createClientLog.Browser.UserAgent,
75+
6876
};
6977
return clientLog;
7078
}

jjodel-persistence/jjodel-persistence/Controllers/API/ProjectController.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,11 @@ public async Task<IActionResult> GetByJJodelId(string Id) {
124124
// todo check permission to open project (public/private)
125125
Project result = await this._projectService.GetByJJodelId(Id);
126126

127+
//todo: remove
128+
result.Collaborators.Add(await this._userManager.FindByNameAsync(this.User.Identity.Name));
129+
await this._projectService.Save();
130+
131+
127132
if(result == null) {
128133
return BadRequest();
129134
}

jjodel-persistence/jjodel-persistence/Controllers/Web/AccountController.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,9 @@ public async Task<IActionResult> Login(LoginRequest loginRequest) {
176176

177177
var result = await _signInManager.PasswordSignInAsync(user, loginRequest.Password, false, false);
178178

179+
if(result == null || !result.Succeeded) {
180+
return View(loginRequest);
181+
}
179182

180183
var roles = await _signInManager.UserManager.GetRolesAsync(user);
181184

jjodel-persistence/jjodel-persistence/Controllers/Web/ClientLogController.cs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,35 @@ public ActionResult Index() {
3535
public async Task<ActionResult> List(string? type = "Error") {
3636

3737
try {
38+
// "Log", "Information", "Warning", "Error", "Exception", "DevError", "DevException")]
3839

3940
List<ClientLog> logs = new List<ClientLog>();
4041
if(type == "All") {
4142
logs = await this._analyticsService.GetAllAsync();
4243
}
44+
else if(type == "Information") {
45+
logs = await this._analyticsService.GetAllInformationAsync();
46+
47+
}
4348
else if(type == "Warning") {
4449
logs = await this._analyticsService.GetAllWarningAsync();
4550
}
46-
else if(type == "Information") {
47-
logs = await this._analyticsService.GetAllInformationAsync();
51+
else if(type == "Error") {
52+
logs = await this._analyticsService.GetAllErrorAsync();
53+
}
54+
else if(type == "Exception") {
55+
logs = await this._analyticsService.GetAllExceptionAsync();
56+
57+
}
58+
else if(type == "DevError") {
59+
logs = await this._analyticsService.GetAllDevErrorAsync();
4860

4961
}
50-
logs = await this._analyticsService.GetAllErrorAsync();
62+
else {
63+
// DevException
64+
65+
}
66+
5167
return PartialView("~/Views/Shared/UC_AnalyticsDevList.cshtml", logs);
5268

5369
}

0 commit comments

Comments
 (0)