aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Controllers
diff options
context:
space:
mode:
authorunknown <crupest@outlook.com>2019-08-07 17:38:56 +0800
committerunknown <crupest@outlook.com>2019-08-07 17:38:56 +0800
commit29bd71cd93b03248254f341aff9252374abc74ec (patch)
treedf5d1325c3b73b17f4f86b71097775e9ce3fa122 /Timeline/Controllers
parent0c0e0c963458aae3ba9589622fc688388833fa9c (diff)
downloadtimeline-29bd71cd93b03248254f341aff9252374abc74ec.tar.gz
timeline-29bd71cd93b03248254f341aff9252374abc74ec.tar.bz2
timeline-29bd71cd93b03248254f341aff9252374abc74ec.zip
Add script to convert encoding and eof. And of course run it.
Diffstat (limited to 'Timeline/Controllers')
-rw-r--r--Timeline/Controllers/TokenController.cs276
-rw-r--r--Timeline/Controllers/UserController.cs250
-rw-r--r--Timeline/Controllers/UserTestController.cs62
3 files changed, 294 insertions, 294 deletions
diff --git a/Timeline/Controllers/TokenController.cs b/Timeline/Controllers/TokenController.cs
index 549e227b..ff397518 100644
--- a/Timeline/Controllers/TokenController.cs
+++ b/Timeline/Controllers/TokenController.cs
@@ -1,55 +1,55 @@
-using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
-using System;
+using System;
using System.Collections.Generic;
-using System.Threading.Tasks;
-using Timeline.Entities.Http;
-using Timeline.Services;
-using static Timeline.Helpers.MyLogHelper;
-
-namespace Timeline.Controllers
-{
- [Route("token")]
- public class TokenController : Controller
- {
- private static class LoggingEventIds
- {
- public const int CreateSucceeded = 1000;
- public const int CreateFailed = 1001;
-
- public const int VerifySucceeded = 2000;
- public const int VerifyFailed = 2001;
- }
-
- public static class ErrorCodes
- {
- public const int Create_UserNotExist = -1001;
- public const int Create_BadPassword = -1002;
- public const int Create_BadExpireOffset = -1003;
-
- public const int Verify_BadToken = -2001;
- public const int Verify_UserNotExist = -2002;
- public const int Verify_BadVersion = -2003;
- public const int Verify_Expired = -2004;
- }
-
- private readonly IUserService _userService;
- private readonly ILogger<TokenController> _logger;
- private readonly IClock _clock;
-
- public TokenController(IUserService userService, ILogger<TokenController> logger, IClock clock)
- {
- _userService = userService;
- _logger = logger;
- _clock = clock;
- }
-
- [HttpPost("create")]
- [AllowAnonymous]
- public async Task<IActionResult> Create([FromBody] CreateTokenRequest request)
- {
+using System.Threading.Tasks;
+using Timeline.Entities.Http;
+using Timeline.Services;
+using static Timeline.Helpers.MyLogHelper;
+
+namespace Timeline.Controllers
+{
+ [Route("token")]
+ public class TokenController : Controller
+ {
+ private static class LoggingEventIds
+ {
+ public const int CreateSucceeded = 1000;
+ public const int CreateFailed = 1001;
+
+ public const int VerifySucceeded = 2000;
+ public const int VerifyFailed = 2001;
+ }
+
+ public static class ErrorCodes
+ {
+ public const int Create_UserNotExist = -1001;
+ public const int Create_BadPassword = -1002;
+ public const int Create_BadExpireOffset = -1003;
+
+ public const int Verify_BadToken = -2001;
+ public const int Verify_UserNotExist = -2002;
+ public const int Verify_BadVersion = -2003;
+ public const int Verify_Expired = -2004;
+ }
+
+ private readonly IUserService _userService;
+ private readonly ILogger<TokenController> _logger;
+ private readonly IClock _clock;
+
+ public TokenController(IUserService userService, ILogger<TokenController> logger, IClock clock)
+ {
+ _userService = userService;
+ _logger = logger;
+ _clock = clock;
+ }
+
+ [HttpPost("create")]
+ [AllowAnonymous]
+ public async Task<IActionResult> Create([FromBody] CreateTokenRequest request)
+ {
void LogFailure(string reason, int code, Exception e = null)
{
_logger.LogInformation(LoggingEventIds.CreateFailed, e, FormatLogMessage("Attemp to login failed.",
@@ -58,51 +58,51 @@ namespace Timeline.Controllers
Pair("Username", request.Username),
Pair("Password", request.Password),
Pair("Expire Offset (in days)", request.ExpireOffset)));
- }
-
- TimeSpan? expireOffset = null;
- if (request.ExpireOffset != null)
- {
- if (request.ExpireOffset.Value <= 0.0)
- {
- const string message = "Expire time is not bigger than 0.";
- var code = ErrorCodes.Create_BadExpireOffset;
- LogFailure(message, code);
- return BadRequest(new CommonResponse(code, message));
- }
- expireOffset = TimeSpan.FromDays(request.ExpireOffset.Value);
- }
-
- try
- {
- var expiredTime = expireOffset == null ? null : (DateTime?)(_clock.GetCurrentTime() + expireOffset.Value);
- var result = await _userService.CreateToken(request.Username, request.Password, expiredTime);
+ }
+
+ TimeSpan? expireOffset = null;
+ if (request.ExpireOffset != null)
+ {
+ if (request.ExpireOffset.Value <= 0.0)
+ {
+ const string message = "Expire time is not bigger than 0.";
+ var code = ErrorCodes.Create_BadExpireOffset;
+ LogFailure(message, code);
+ return BadRequest(new CommonResponse(code, message));
+ }
+ expireOffset = TimeSpan.FromDays(request.ExpireOffset.Value);
+ }
+
+ try
+ {
+ var expiredTime = expireOffset == null ? null : (DateTime?)(_clock.GetCurrentTime() + expireOffset.Value);
+ var result = await _userService.CreateToken(request.Username, request.Password, expiredTime);
_logger.LogInformation(LoggingEventIds.CreateSucceeded, FormatLogMessage("Attemp to login succeeded.",
Pair("Username", request.Username),
- Pair("Expire Time", expiredTime == null ? "default" : expiredTime.Value.ToString())));
- return Ok(new CreateTokenResponse
- {
- Token = result.Token,
- User = result.User
- });
- }
- catch (UserNotExistException e)
- {
- var code = ErrorCodes.Create_UserNotExist;
- LogFailure("User does not exist.", code, e);
- return BadRequest(new CommonResponse(code, "Bad username or password."));
- }
- catch (BadPasswordException e)
- {
- var code = ErrorCodes.Create_BadPassword;
- LogFailure("Password is wrong.", code, e);
- return BadRequest(new CommonResponse(code, "Bad username or password."));
- }
- }
-
- [HttpPost("verify")]
- [AllowAnonymous]
- public async Task<IActionResult> Verify([FromBody] VerifyTokenRequest request)
+ Pair("Expire Time", expiredTime == null ? "default" : expiredTime.Value.ToString())));
+ return Ok(new CreateTokenResponse
+ {
+ Token = result.Token,
+ User = result.User
+ });
+ }
+ catch (UserNotExistException e)
+ {
+ var code = ErrorCodes.Create_UserNotExist;
+ LogFailure("User does not exist.", code, e);
+ return BadRequest(new CommonResponse(code, "Bad username or password."));
+ }
+ catch (BadPasswordException e)
+ {
+ var code = ErrorCodes.Create_BadPassword;
+ LogFailure("Password is wrong.", code, e);
+ return BadRequest(new CommonResponse(code, "Bad username or password."));
+ }
+ }
+
+ [HttpPost("verify")]
+ [AllowAnonymous]
+ public async Task<IActionResult> Verify([FromBody] VerifyTokenRequest request)
{
void LogFailure(string reason, int code, Exception e = null, params KeyValuePair<string, object>[] otherProperties)
{
@@ -112,52 +112,52 @@ namespace Timeline.Controllers
properties[2] = Pair("Token", request.Token);
otherProperties.CopyTo(properties, 3);
_logger.LogInformation(LoggingEventIds.VerifyFailed, e, FormatLogMessage("Token verification failed.", properties));
- }
-
- try
- {
- var result = await _userService.VerifyToken(request.Token);
+ }
+
+ try
+ {
+ var result = await _userService.VerifyToken(request.Token);
_logger.LogInformation(LoggingEventIds.VerifySucceeded,
FormatLogMessage("Token verification succeeded.",
- Pair("Username", result.Username), Pair("Token", request.Token)));
- return Ok(new VerifyTokenResponse
- {
- User = result
- });
- }
- catch (JwtTokenVerifyException e)
- {
- if (e.ErrorCode == JwtTokenVerifyException.ErrorCodes.Expired)
- {
- const string message = "Token is expired.";
- var code = ErrorCodes.Verify_Expired;
- var innerException = e.InnerException as SecurityTokenExpiredException;
- LogFailure(message, code, e, Pair("Expires", innerException.Expires));
- return BadRequest(new CommonResponse(code, message));
- }
- else
- {
- const string message = "Token is of bad format.";
- var code = ErrorCodes.Verify_BadToken;
- LogFailure(message, code, e);
- return BadRequest(new CommonResponse(code, message));
- }
- }
- catch (UserNotExistException e)
+ Pair("Username", result.Username), Pair("Token", request.Token)));
+ return Ok(new VerifyTokenResponse
+ {
+ User = result
+ });
+ }
+ catch (JwtTokenVerifyException e)
{
- const string message = "User does not exist. Administrator might have deleted this user.";
+ if (e.ErrorCode == JwtTokenVerifyException.ErrorCodes.Expired)
+ {
+ const string message = "Token is expired.";
+ var code = ErrorCodes.Verify_Expired;
+ var innerException = e.InnerException as SecurityTokenExpiredException;
+ LogFailure(message, code, e, Pair("Expires", innerException.Expires));
+ return BadRequest(new CommonResponse(code, message));
+ }
+ else
+ {
+ const string message = "Token is of bad format.";
+ var code = ErrorCodes.Verify_BadToken;
+ LogFailure(message, code, e);
+ return BadRequest(new CommonResponse(code, message));
+ }
+ }
+ catch (UserNotExistException e)
+ {
+ const string message = "User does not exist. Administrator might have deleted this user.";
var code = ErrorCodes.Verify_UserNotExist;
- LogFailure(message, code, e);
- return BadRequest(new CommonResponse(code, message));
- }
- catch (BadTokenVersionException e)
- {
- const string message = "Token has a old version.";
- var code = ErrorCodes.Verify_BadVersion;
- LogFailure(message, code, e);
- _logger.LogInformation(LoggingEventIds.VerifyFailed, e, "Attemp to verify a bad token because version is old. Code: {} Token: {}.", code, request.Token);
- return BadRequest(new CommonResponse(code, message));
- }
- }
- }
-}
+ LogFailure(message, code, e);
+ return BadRequest(new CommonResponse(code, message));
+ }
+ catch (BadTokenVersionException e)
+ {
+ const string message = "Token has a old version.";
+ var code = ErrorCodes.Verify_BadVersion;
+ LogFailure(message, code, e);
+ _logger.LogInformation(LoggingEventIds.VerifyFailed, e, "Attemp to verify a bad token because version is old. Code: {} Token: {}.", code, request.Token);
+ return BadRequest(new CommonResponse(code, message));
+ }
+ }
+ }
+}
diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs
index 2099690c..8d338949 100644
--- a/Timeline/Controllers/UserController.cs
+++ b/Timeline/Controllers/UserController.cs
@@ -1,126 +1,126 @@
-using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
-using System;
-using System.Threading.Tasks;
-using Timeline.Authenticate;
-using Timeline.Entities;
-using Timeline.Entities.Http;
-using Timeline.Services;
-using static Timeline.Helpers.MyLogHelper;
-
-namespace Timeline.Controllers
-{
- public class UserController : Controller
- {
- private static class ErrorCodes
- {
- public const int Get_NotExists = -1001;
-
- public const int Put_NoPassword = -2001;
-
- public const int Patch_NotExists = -3001;
-
- public const int ChangePassword_BadOldPassword = -4001;
- }
-
- private readonly ILogger<UserController> _logger;
- private readonly IUserService _userService;
-
- public UserController(ILogger<UserController> logger, IUserService userService)
- {
- _logger = logger;
- _userService = userService;
- }
-
- [HttpGet("users"), AdminAuthorize]
- public async Task<ActionResult<UserInfo[]>> List()
- {
- return Ok(await _userService.ListUsers());
- }
-
- [HttpGet("user/{username}"), AdminAuthorize]
- public async Task<IActionResult> Get([FromRoute] string username)
- {
- var user = await _userService.GetUser(username);
- if (user == null)
- {
- _logger.LogInformation(FormatLogMessage("Attempt to get a non-existent user.", Pair("Username", username)));
- return NotFound(new CommonResponse(ErrorCodes.Get_NotExists, "The user does not exist."));
- }
- return Ok(user);
- }
-
- [HttpPut("user/{username}"), AdminAuthorize]
- public async Task<IActionResult> Put([FromBody] UserPutRequest request, [FromRoute] string username)
- {
- if (request.Password == null) // This place will be refactored.
- {
- _logger.LogInformation("Attempt to put a user without a password. Username: {} .", username);
- return BadRequest();
- }
-
- var result = await _userService.PutUser(username, request.Password, request.Administrator);
- switch (result)
- {
- case PutResult.Created:
- _logger.LogInformation(FormatLogMessage("A user is created.", Pair("Username", username)));
- return CreatedAtAction("Get", new { username }, CommonPutResponse.Created);
- case PutResult.Modified:
- _logger.LogInformation(FormatLogMessage("A user is modified.", Pair("Username", username)));
- return Ok(CommonPutResponse.Modified);
- default:
- throw new Exception("Unreachable code.");
- }
- }
-
- [HttpPatch("user/{username}"), AdminAuthorize]
- public async Task<IActionResult> Patch([FromBody] UserPatchRequest request, [FromRoute] string username)
- {
- try
- {
- await _userService.PatchUser(username, request.Password, request.Administrator);
- return Ok();
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, FormatLogMessage("Attempt to patch a non-existent user.", Pair("Username", username)));
- return BadRequest(new CommonResponse(ErrorCodes.Patch_NotExists, "The user does not exist."));
- }
- }
-
- [HttpDelete("user/{username}"), AdminAuthorize]
- public async Task<IActionResult> Delete([FromRoute] string username)
- {
- try
- {
- await _userService.DeleteUser(username);
- _logger.LogInformation(FormatLogMessage("A user is deleted.", Pair("Username", username)));
- return Ok(CommonDeleteResponse.Deleted);
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, FormatLogMessage("Attempt to delete a non-existent user.", Pair("Username", username)));
- return Ok(CommonDeleteResponse.NotExists);
- }
- }
-
- [HttpPost("userop/changepassword"), Authorize]
- public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
- {
- try
- {
- await _userService.ChangePassword(User.Identity.Name, request.OldPassword, request.NewPassword);
- _logger.LogInformation(FormatLogMessage("A user changed password.", Pair("Username", User.Identity.Name)));
- return Ok();
- }
- catch (BadPasswordException e)
- {
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Threading.Tasks;
+using Timeline.Authenticate;
+using Timeline.Entities;
+using Timeline.Entities.Http;
+using Timeline.Services;
+using static Timeline.Helpers.MyLogHelper;
+
+namespace Timeline.Controllers
+{
+ public class UserController : Controller
+ {
+ private static class ErrorCodes
+ {
+ public const int Get_NotExists = -1001;
+
+ public const int Put_NoPassword = -2001;
+
+ public const int Patch_NotExists = -3001;
+
+ public const int ChangePassword_BadOldPassword = -4001;
+ }
+
+ private readonly ILogger<UserController> _logger;
+ private readonly IUserService _userService;
+
+ public UserController(ILogger<UserController> logger, IUserService userService)
+ {
+ _logger = logger;
+ _userService = userService;
+ }
+
+ [HttpGet("users"), AdminAuthorize]
+ public async Task<ActionResult<UserInfo[]>> List()
+ {
+ return Ok(await _userService.ListUsers());
+ }
+
+ [HttpGet("user/{username}"), AdminAuthorize]
+ public async Task<IActionResult> Get([FromRoute] string username)
+ {
+ var user = await _userService.GetUser(username);
+ if (user == null)
+ {
+ _logger.LogInformation(FormatLogMessage("Attempt to get a non-existent user.", Pair("Username", username)));
+ return NotFound(new CommonResponse(ErrorCodes.Get_NotExists, "The user does not exist."));
+ }
+ return Ok(user);
+ }
+
+ [HttpPut("user/{username}"), AdminAuthorize]
+ public async Task<IActionResult> Put([FromBody] UserPutRequest request, [FromRoute] string username)
+ {
+ if (request.Password == null) // This place will be refactored.
+ {
+ _logger.LogInformation("Attempt to put a user without a password. Username: {} .", username);
+ return BadRequest();
+ }
+
+ var result = await _userService.PutUser(username, request.Password, request.Administrator);
+ switch (result)
+ {
+ case PutResult.Created:
+ _logger.LogInformation(FormatLogMessage("A user is created.", Pair("Username", username)));
+ return CreatedAtAction("Get", new { username }, CommonPutResponse.Created);
+ case PutResult.Modified:
+ _logger.LogInformation(FormatLogMessage("A user is modified.", Pair("Username", username)));
+ return Ok(CommonPutResponse.Modified);
+ default:
+ throw new Exception("Unreachable code.");
+ }
+ }
+
+ [HttpPatch("user/{username}"), AdminAuthorize]
+ public async Task<IActionResult> Patch([FromBody] UserPatchRequest request, [FromRoute] string username)
+ {
+ try
+ {
+ await _userService.PatchUser(username, request.Password, request.Administrator);
+ return Ok();
+ }
+ catch (UserNotExistException e)
+ {
+ _logger.LogInformation(e, FormatLogMessage("Attempt to patch a non-existent user.", Pair("Username", username)));
+ return BadRequest(new CommonResponse(ErrorCodes.Patch_NotExists, "The user does not exist."));
+ }
+ }
+
+ [HttpDelete("user/{username}"), AdminAuthorize]
+ public async Task<IActionResult> Delete([FromRoute] string username)
+ {
+ try
+ {
+ await _userService.DeleteUser(username);
+ _logger.LogInformation(FormatLogMessage("A user is deleted.", Pair("Username", username)));
+ return Ok(CommonDeleteResponse.Deleted);
+ }
+ catch (UserNotExistException e)
+ {
+ _logger.LogInformation(e, FormatLogMessage("Attempt to delete a non-existent user.", Pair("Username", username)));
+ return Ok(CommonDeleteResponse.NotExists);
+ }
+ }
+
+ [HttpPost("userop/changepassword"), Authorize]
+ public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
+ {
+ try
+ {
+ await _userService.ChangePassword(User.Identity.Name, request.OldPassword, request.NewPassword);
+ _logger.LogInformation(FormatLogMessage("A user changed password.", Pair("Username", User.Identity.Name)));
+ return Ok();
+ }
+ catch (BadPasswordException e)
+ {
_logger.LogInformation(e, FormatLogMessage("A user attempt to change password but old password is wrong.",
- Pair("Username", User.Identity.Name), Pair("Old Password", request.OldPassword)));
- return BadRequest(new CommonResponse(ErrorCodes.ChangePassword_BadOldPassword, "Old password is wrong."));
- }
- // User can't be non-existent or the token is bad.
- }
- }
-}
+ Pair("Username", User.Identity.Name), Pair("Old Password", request.OldPassword)));
+ return BadRequest(new CommonResponse(ErrorCodes.ChangePassword_BadOldPassword, "Old password is wrong."));
+ }
+ // User can't be non-existent or the token is bad.
+ }
+ }
+}
diff --git a/Timeline/Controllers/UserTestController.cs b/Timeline/Controllers/UserTestController.cs
index 21686b81..f65d9857 100644
--- a/Timeline/Controllers/UserTestController.cs
+++ b/Timeline/Controllers/UserTestController.cs
@@ -1,31 +1,31 @@
-using Microsoft.AspNetCore.Authorization;
-using Microsoft.AspNetCore.Mvc;
-using Timeline.Authenticate;
-
-namespace Timeline.Controllers
-{
- [Route("Test/User")]
- public class UserTestController : Controller
- {
- [HttpGet("[action]")]
- [Authorize]
- public ActionResult Authorize()
- {
- return Ok();
- }
-
- [HttpGet("[action]")]
- [UserAuthorize]
- public new ActionResult User()
- {
- return Ok();
- }
-
- [HttpGet("[action]")]
- [AdminAuthorize]
- public ActionResult Admin()
- {
- return Ok();
- }
- }
-}
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Timeline.Authenticate;
+
+namespace Timeline.Controllers
+{
+ [Route("Test/User")]
+ public class UserTestController : Controller
+ {
+ [HttpGet("[action]")]
+ [Authorize]
+ public ActionResult Authorize()
+ {
+ return Ok();
+ }
+
+ [HttpGet("[action]")]
+ [UserAuthorize]
+ public new ActionResult User()
+ {
+ return Ok();
+ }
+
+ [HttpGet("[action]")]
+ [AdminAuthorize]
+ public ActionResult Admin()
+ {
+ return Ok();
+ }
+ }
+}