diff options
Diffstat (limited to 'BackEnd/Timeline/Controllers')
11 files changed, 319 insertions, 304 deletions
diff --git a/BackEnd/Timeline/Controllers/ActionResultControllerExtensions.cs b/BackEnd/Timeline/Controllers/ActionResultControllerExtensions.cs new file mode 100644 index 00000000..a3da73fa --- /dev/null +++ b/BackEnd/Timeline/Controllers/ActionResultControllerExtensions.cs @@ -0,0 +1,24 @@ +using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Timeline.Models.Http;
+
+namespace Timeline.Controllers
+{
+ public static class ActionResultControllerExtensions
+ {
+ public static ObjectResult StatusCodeWithCommonResponse(this ControllerBase controller, int statusCode, int code, string message)
+ {
+ return controller.StatusCode(statusCode, new CommonResponse(code, message));
+ }
+
+ public static ObjectResult ForbidWithMessage(this ControllerBase controller, string? message = null)
+ {
+ return controller.StatusCode(StatusCodes.Status403Forbidden, new CommonResponse(ErrorCodes.Common.Forbid, message ?? Resource.MessageForbid));
+ }
+
+ public static BadRequestObjectResult BadRequestWithCommonResponse(this ControllerBase controller, int code, string message)
+ {
+ return controller.BadRequest(new CommonResponse(code, message));
+ }
+ }
+}
diff --git a/BackEnd/Timeline/Controllers/BookmarkTimelineController.cs b/BackEnd/Timeline/Controllers/BookmarkTimelineController.cs index e7ffa5c5..94cb0f3e 100644 --- a/BackEnd/Timeline/Controllers/BookmarkTimelineController.cs +++ b/BackEnd/Timeline/Controllers/BookmarkTimelineController.cs @@ -44,7 +44,7 @@ namespace Timeline.Controllers [ProducesResponseType(401)]
public async Task<ActionResult<List<HttpTimeline>>> List()
{
- var ids = await _service.GetBookmarks(this.GetUserId());
+ var ids = await _service.GetBookmarksAsync(this.GetUserId());
var timelines = await _timelineService.GetTimelineList(ids);
return await Map(timelines);
}
@@ -60,16 +60,9 @@ namespace Timeline.Controllers [ProducesResponseType(401)]
public async Task<ActionResult<CommonPutResponse>> Put([GeneralTimelineName] string timeline)
{
- try
- {
- var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
- var create = await _service.AddBookmark(this.GetUserId(), timelineId);
- return CommonPutResponse.Create(create);
- }
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
+ var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
+ var create = await _service.AddBookmarkAsync(this.GetUserId(), timelineId);
+ return CommonPutResponse.Create(create);
}
/// <summary>
@@ -83,16 +76,9 @@ namespace Timeline.Controllers [ProducesResponseType(401)]
public async Task<ActionResult<CommonDeleteResponse>> Delete([GeneralTimelineName] string timeline)
{
- try
- {
- var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
- var delete = await _service.RemoveBookmark(this.GetUserId(), timelineId);
- return CommonDeleteResponse.Create(delete);
- }
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
+ var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
+ var delete = await _service.RemoveBookmarkAsync(this.GetUserId(), timelineId);
+ return CommonDeleteResponse.Create(delete);
}
/// <summary>
@@ -109,13 +95,9 @@ namespace Timeline.Controllers try
{
var timelineId = await _timelineService.GetTimelineIdByNameAsync(request.Timeline);
- await _service.MoveBookmark(this.GetUserId(), timelineId, request.NewPosition!.Value);
+ await _service.MoveBookmarkAsync(this.GetUserId(), timelineId, request.NewPosition!.Value);
return Ok();
}
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
catch (InvalidBookmarkException)
{
return BadRequest(new CommonResponse(ErrorCodes.BookmarkTimelineController.NonBookmark, "You can't move a non-bookmark timeline."));
diff --git a/BackEnd/Timeline/Controllers/HighlightTimelineController.cs b/BackEnd/Timeline/Controllers/HighlightTimelineController.cs index 4e739056..e73bc7a9 100644 --- a/BackEnd/Timeline/Controllers/HighlightTimelineController.cs +++ b/BackEnd/Timeline/Controllers/HighlightTimelineController.cs @@ -43,7 +43,7 @@ namespace Timeline.Controllers [ProducesResponseType(200)]
public async Task<ActionResult<List<HttpTimeline>>> List()
{
- var ids = await _service.GetHighlightTimelines();
+ var ids = await _service.GetHighlightTimelinesAsync();
var timelines = await _timelineService.GetTimelineList(ids);
return await Map(timelines);
}
@@ -60,16 +60,9 @@ namespace Timeline.Controllers [ProducesResponseType(403)]
public async Task<ActionResult<CommonPutResponse>> Put([GeneralTimelineName] string timeline)
{
- try
- {
- var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
- var create = await _service.AddHighlightTimeline(timelineId, this.GetUserId());
- return CommonPutResponse.Create(create);
- }
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
+ var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
+ var create = await _service.AddHighlightTimelineAsync(timelineId, this.GetUserId());
+ return CommonPutResponse.Create(create);
}
/// <summary>
@@ -84,16 +77,9 @@ namespace Timeline.Controllers [ProducesResponseType(403)]
public async Task<ActionResult<CommonDeleteResponse>> Delete([GeneralTimelineName] string timeline)
{
- try
- {
- var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
- var delete = await _service.RemoveHighlightTimeline(timelineId, this.GetUserId());
- return CommonDeleteResponse.Create(delete);
- }
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
+ var timelineId = await _timelineService.GetTimelineIdByNameAsync(timeline);
+ var delete = await _service.RemoveHighlightTimelineAsync(timelineId, this.GetUserId());
+ return CommonDeleteResponse.Create(delete);
}
/// <summary>
@@ -110,13 +96,9 @@ namespace Timeline.Controllers try
{
var timelineId = await _timelineService.GetTimelineIdByNameAsync(body.Timeline);
- await _service.MoveHighlightTimeline(timelineId, body.NewPosition!.Value);
+ await _service.MoveHighlightTimelineAsync(timelineId, body.NewPosition!.Value);
return Ok();
}
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
catch (InvalidHighlightTimelineException)
{
return BadRequest(new CommonResponse(ErrorCodes.HighlightTimelineController.NonHighlight, "Can't move a non-highlight timeline."));
diff --git a/BackEnd/Timeline/Controllers/Resource.Designer.cs b/BackEnd/Timeline/Controllers/Resource.Designer.cs index 6279a055..f3d7264a 100644 --- a/BackEnd/Timeline/Controllers/Resource.Designer.cs +++ b/BackEnd/Timeline/Controllers/Resource.Designer.cs @@ -68,5 +68,158 @@ namespace Timeline.Controllers { return ResourceManager.GetString("ExceptionNoUserId", resourceCulture);
}
}
+
+ /// <summary>
+ /// Looks up a localized string similar to You have no permission to access this..
+ /// </summary>
+ internal static string MessageForbid {
+ get {
+ return ResourceManager.GetString("MessageForbid", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to You can't do this unless you are administrator..
+ /// </summary>
+ internal static string MessageForbidNotAdministrator {
+ get {
+ return ResourceManager.GetString("MessageForbidNotAdministrator", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to You can't do this unless you are administrator or resource owner..
+ /// </summary>
+ internal static string MessageForbidNotAdministratorOrOwner {
+ get {
+ return ResourceManager.GetString("MessageForbidNotAdministratorOrOwner", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Image is not a square..
+ /// </summary>
+ internal static string MessageImageBadSize {
+ get {
+ return ResourceManager.GetString("MessageImageBadSize", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Image decode failed..
+ /// </summary>
+ internal static string MessageImageDecodeFailed {
+ get {
+ return ResourceManager.GetString("MessageImageDecodeFailed", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Specified image format does not match the actual one ..
+ /// </summary>
+ internal static string MessageImageFormatUnmatch {
+ get {
+ return ResourceManager.GetString("MessageImageFormatUnmatch", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Unknown error happened to image..
+ /// </summary>
+ internal static string MessageImageUnknownError {
+ get {
+ return ResourceManager.GetString("MessageImageUnknownError", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to You can't do this because it is the root user..
+ /// </summary>
+ internal static string MessageInvalidOperationOnRootUser {
+ get {
+ return ResourceManager.GetString("MessageInvalidOperationOnRootUser", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The old password is wrong..
+ /// </summary>
+ internal static string MessageOldPasswordWrong {
+ get {
+ return ResourceManager.GetString("MessageOldPasswordWrong", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The user specified by query param "relate" does not exist..
+ /// </summary>
+ internal static string MessageTimelineListQueryRelateNotExist {
+ get {
+ return ResourceManager.GetString("MessageTimelineListQueryRelateNotExist", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to '{0}' is an unkown visibility in the query parameter 'visibility'. .
+ /// </summary>
+ internal static string MessageTimelineListQueryVisibilityUnknown {
+ get {
+ return ResourceManager.GetString("MessageTimelineListQueryVisibilityUnknown", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Username or password is invalid..
+ /// </summary>
+ internal static string MessageTokenCreateBadCredential {
+ get {
+ return ResourceManager.GetString("MessageTokenCreateBadCredential", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The token is of bad format. It might not be created by the server..
+ /// </summary>
+ internal static string MessageTokenVerifyBadFormat {
+ get {
+ return ResourceManager.GetString("MessageTokenVerifyBadFormat", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Token has an old version. User might have update some info..
+ /// </summary>
+ internal static string MessageTokenVerifyOldVersion {
+ get {
+ return ResourceManager.GetString("MessageTokenVerifyOldVersion", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The token is expired..
+ /// </summary>
+ internal static string MessageTokenVerifyTimeExpired {
+ get {
+ return ResourceManager.GetString("MessageTokenVerifyTimeExpired", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to User does not exist. Administrator might have deleted this user..
+ /// </summary>
+ internal static string MessageTokenVerifyUserNotExist {
+ get {
+ return ResourceManager.GetString("MessageTokenVerifyUserNotExist", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A user with given username already exists..
+ /// </summary>
+ internal static string MessageUsernameConflict {
+ get {
+ return ResourceManager.GetString("MessageUsernameConflict", resourceCulture);
+ }
+ }
}
}
diff --git a/BackEnd/Timeline/Controllers/Resource.resx b/BackEnd/Timeline/Controllers/Resource.resx index ec45a5c9..90c6bdd6 100644 --- a/BackEnd/Timeline/Controllers/Resource.resx +++ b/BackEnd/Timeline/Controllers/Resource.resx @@ -120,4 +120,55 @@ <data name="ExceptionNoUserId" xml:space="preserve">
<value>Can't get user id.</value>
</data>
+ <data name="MessageForbid" xml:space="preserve">
+ <value>You have no permission to access this.</value>
+ </data>
+ <data name="MessageForbidNotAdministrator" xml:space="preserve">
+ <value>You can't do this unless you are administrator.</value>
+ </data>
+ <data name="MessageForbidNotAdministratorOrOwner" xml:space="preserve">
+ <value>You can't do this unless you are administrator or resource owner.</value>
+ </data>
+ <data name="MessageImageBadSize" xml:space="preserve">
+ <value>Image is not a square.</value>
+ </data>
+ <data name="MessageImageDecodeFailed" xml:space="preserve">
+ <value>Image decode failed.</value>
+ </data>
+ <data name="MessageImageFormatUnmatch" xml:space="preserve">
+ <value>Specified image format does not match the actual one .</value>
+ </data>
+ <data name="MessageImageUnknownError" xml:space="preserve">
+ <value>Unknown error happened to image.</value>
+ </data>
+ <data name="MessageInvalidOperationOnRootUser" xml:space="preserve">
+ <value>You can't do this because it is the root user.</value>
+ </data>
+ <data name="MessageOldPasswordWrong" xml:space="preserve">
+ <value>The old password is wrong.</value>
+ </data>
+ <data name="MessageTimelineListQueryRelateNotExist" xml:space="preserve">
+ <value>The user specified by query param "relate" does not exist.</value>
+ </data>
+ <data name="MessageTimelineListQueryVisibilityUnknown" xml:space="preserve">
+ <value>'{0}' is an unkown visibility in the query parameter 'visibility'. </value>
+ </data>
+ <data name="MessageTokenCreateBadCredential" xml:space="preserve">
+ <value>Username or password is invalid.</value>
+ </data>
+ <data name="MessageTokenVerifyBadFormat" xml:space="preserve">
+ <value>The token is of bad format. It might not be created by the server.</value>
+ </data>
+ <data name="MessageTokenVerifyOldVersion" xml:space="preserve">
+ <value>Token has an old version. User might have update some info.</value>
+ </data>
+ <data name="MessageTokenVerifyTimeExpired" xml:space="preserve">
+ <value>The token is expired.</value>
+ </data>
+ <data name="MessageTokenVerifyUserNotExist" xml:space="preserve">
+ <value>User does not exist. Administrator might have deleted this user.</value>
+ </data>
+ <data name="MessageUsernameConflict" xml:space="preserve">
+ <value>A user with given username already exists.</value>
+ </data>
</root>
\ No newline at end of file diff --git a/BackEnd/Timeline/Controllers/SearchController.cs b/BackEnd/Timeline/Controllers/SearchController.cs index 76f3d8f2..cd085e5b 100644 --- a/BackEnd/Timeline/Controllers/SearchController.cs +++ b/BackEnd/Timeline/Controllers/SearchController.cs @@ -42,7 +42,7 @@ namespace Timeline.Controllers [ProducesResponseType(400)]
public async Task<ActionResult<List<HttpTimeline>>> TimelineSearch([FromQuery(Name = "q"), Required(AllowEmptyStrings = false)] string query)
{
- var searchResult = await _service.SearchTimeline(query);
+ var searchResult = await _service.SearchTimelineAsync(query);
var timelines = searchResult.Items.Select(i => i.Item).ToList();
return await Map(timelines);
}
@@ -57,7 +57,7 @@ namespace Timeline.Controllers [ProducesResponseType(400)]
public async Task<ActionResult<List<HttpUser>>> UserSearch([FromQuery(Name = "q"), Required(AllowEmptyStrings = false)] string query)
{
- var searchResult = await _service.SearchUser(query);
+ var searchResult = await _service.SearchUserAsync(query);
var users = searchResult.Items.Select(i => i.Item).ToList();
return await _mapper.MapListAsync<HttpUser>(users, Url, User);
}
diff --git a/BackEnd/Timeline/Controllers/TimelineController.cs b/BackEnd/Timeline/Controllers/TimelineController.cs index 497d7893..f04982dc 100644 --- a/BackEnd/Timeline/Controllers/TimelineController.cs +++ b/BackEnd/Timeline/Controllers/TimelineController.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic;
using System.Threading.Tasks;
using Timeline.Entities;
-using Timeline.Filters;
using Timeline.Models;
using Timeline.Models.Http;
using Timeline.Models.Validation;
@@ -21,7 +20,6 @@ namespace Timeline.Controllers /// </summary>
[ApiController]
[Route("timelines")]
- [CatchTimelineNotExistException]
[ProducesErrorResponseType(typeof(CommonResponse))]
public class TimelineController : Controller
{
@@ -29,9 +27,6 @@ namespace Timeline.Controllers private readonly ITimelineService _service;
private readonly IGenericMapper _mapper;
- /// <summary>
- ///
- /// </summary>
public TimelineController(IUserService userService, ITimelineService service, IGenericMapper mapper)
{
_userService = userService;
@@ -87,7 +82,7 @@ namespace Timeline.Controllers }
else
{
- return BadRequest(ErrorResponse.Common.CustomMessage_InvalidModel(Resources.Messages.TimelineController_QueryVisibilityUnknown, item));
+ return this.BadRequestWithCommonResponse(ErrorCodes.Common.InvalidModel, string.Format(Resource.MessageTimelineListQueryVisibilityUnknown, visibility));
}
}
}
@@ -103,9 +98,9 @@ namespace Timeline.Controllers relationship = new TimelineUserRelationship(relationType, relatedUserId);
}
- catch (UserNotExistException)
+ catch (EntityNotExistException)
{
- return BadRequest(ErrorResponse.TimelineController.QueryRelateNotExist());
+ return this.BadRequestWithCommonResponse(ErrorCodes.TimelineController.QueryRelateNotExist, Resource.MessageTimelineListQueryRelateNotExist);
}
}
@@ -148,20 +143,13 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _service.HasManagePermissionAsync(timelineId, this.GetUserId()))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
- try
- {
- await _service.ChangePropertyAsync(timelineId, _mapper.AutoMapperMap<TimelineChangePropertyParams>(body));
- var t = await _service.GetTimelineAsync(timelineId);
- var result = await Map(t);
- return result;
- }
- catch (EntityAlreadyExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NameConflict());
- }
+ await _service.ChangePropertyAsync(timelineId, _mapper.AutoMapperMap<TimelineChangePropertyParams>(body));
+ var t = await _service.GetTimelineAsync(timelineId);
+ var result = await Map(t);
+ return result;
}
/// <summary>
@@ -181,19 +169,12 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermissionAsync(timelineId, this.GetUserId())))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
- try
- {
- var userId = await _userService.GetUserIdByUsernameAsync(member);
- var create = await _service.AddMemberAsync(timelineId, userId);
- return Ok(CommonPutResponse.Create(create));
- }
- catch (UserNotExistException)
- {
- return BadRequest(ErrorResponse.UserCommon.NotExist());
- }
+ var userId = await _userService.GetUserIdByUsernameAsync(member);
+ var create = await _service.AddMemberAsync(timelineId, userId);
+ return Ok(CommonPutResponse.Create(create));
}
/// <summary>
@@ -213,19 +194,13 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermissionAsync(timelineId, this.GetUserId())))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
- try
- {
- var userId = await _userService.GetUserIdByUsernameAsync(member);
- var delete = await _service.RemoveMemberAsync(timelineId, userId);
- return Ok(CommonDeleteResponse.Create(delete));
- }
- catch (UserNotExistException)
- {
- return BadRequest(ErrorResponse.UserCommon.NotExist());
- }
+
+ var userId = await _userService.GetUserIdByUsernameAsync(member);
+ var delete = await _service.RemoveMemberAsync(timelineId, userId);
+ return Ok(CommonDeleteResponse.Create(delete));
}
/// <summary>
@@ -242,16 +217,9 @@ namespace Timeline.Controllers {
var userId = this.GetUserId();
- try
- {
- var timeline = await _service.CreateTimelineAsync(body.Name, userId);
- var result = await Map(timeline);
- return result;
- }
- catch (EntityAlreadyExistException e) when (e.EntityName == EntityNames.Timeline)
- {
- return BadRequest(ErrorResponse.TimelineController.NameConflict());
- }
+ var timeline = await _service.CreateTimelineAsync(body.Name, userId);
+ var result = await Map(timeline);
+ return result;
}
/// <summary>
@@ -271,18 +239,11 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermissionAsync(timelineId, this.GetUserId())))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
- try
- {
- await _service.DeleteTimelineAsync(timelineId);
- return Ok();
- }
- catch (TimelineNotExistException)
- {
- return BadRequest(ErrorResponse.TimelineController.NotExist());
- }
+ await _service.DeleteTimelineAsync(timelineId);
+ return Ok();
}
}
}
diff --git a/BackEnd/Timeline/Controllers/TimelinePostController.cs b/BackEnd/Timeline/Controllers/TimelinePostController.cs index 2e1ed3a9..9f69b59b 100644 --- a/BackEnd/Timeline/Controllers/TimelinePostController.cs +++ b/BackEnd/Timeline/Controllers/TimelinePostController.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Timeline.Entities;
-using Timeline.Filters;
using Timeline.Helpers.Cache;
using Timeline.Models;
using Timeline.Models.Http;
@@ -22,9 +21,6 @@ namespace Timeline.Controllers /// </summary>
[ApiController]
[Route("timelines/{timeline}/posts")]
- [CatchTimelineNotExistException]
- [CatchTimelinePostNotExistException]
- [CatchTimelinePostDataNotExistException]
[ProducesErrorResponseType(typeof(CommonResponse))]
public class TimelinePostController : Controller
{
@@ -35,9 +31,6 @@ namespace Timeline.Controllers private readonly MarkdownProcessor _markdownProcessor;
- /// <summary>
- ///
- /// </summary>
public TimelinePostController(ITimelineService timelineService, ITimelinePostService timelinePostService, IGenericMapper mapper, MarkdownProcessor markdownProcessor)
{
_timelineService = timelineService;
@@ -75,7 +68,7 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _timelineService.HasReadPermissionAsync(timelineId, this.GetOptionalUserId()))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
var posts = await _postService.GetPostsAsync(timelineId, modifiedSince, includeDeleted ?? false);
@@ -100,7 +93,7 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _timelineService.HasReadPermissionAsync(timelineId, this.GetOptionalUserId()))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
var post = await _postService.GetPostAsync(timelineId, postId);
@@ -146,7 +139,7 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _timelineService.HasReadPermissionAsync(timelineId, this.GetOptionalUserId()))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
return await DataCacheHelper.GenerateActionResult(this,
@@ -182,7 +175,7 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _timelineService.IsMemberOfAsync(timelineId, userId))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
var createRequest = new TimelinePostCreateRequest()
@@ -241,7 +234,7 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _postService.HasPostModifyPermissionAsync(timelineId, post, this.GetUserId(), true))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
var entity = await _postService.PatchPostAsync(timelineId, post, new TimelinePostPatchRequest { Time = body.Time, Color = body.Color });
@@ -268,7 +261,7 @@ namespace Timeline.Controllers if (!UserHasAllTimelineManagementPermission && !await _postService.HasPostModifyPermissionAsync(timelineId, post, this.GetUserId(), true))
{
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage();
}
await _postService.DeletePostAsync(timelineId, post);
diff --git a/BackEnd/Timeline/Controllers/TokenController.cs b/BackEnd/Timeline/Controllers/TokenController.cs index e728ae6d..080a4dc4 100644 --- a/BackEnd/Timeline/Controllers/TokenController.cs +++ b/BackEnd/Timeline/Controllers/TokenController.cs @@ -1,17 +1,13 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
using System;
-using System.Globalization;
using System.Threading.Tasks;
-using Timeline.Helpers;
using Timeline.Models.Http;
using Timeline.Services;
using Timeline.Services.Mapper;
using Timeline.Services.Token;
using Timeline.Services.User;
-using static Timeline.Resources.Controllers.TokenController;
namespace Timeline.Controllers
{
@@ -24,15 +20,12 @@ namespace Timeline.Controllers public class TokenController : Controller
{
private readonly IUserTokenManager _userTokenManager;
- private readonly ILogger<TokenController> _logger;
private readonly IGenericMapper _mapper;
private readonly IClock _clock;
- /// <summary></summary>
- public TokenController(IUserTokenManager userTokenManager, ILogger<TokenController> logger, IGenericMapper mapper, IClock clock)
+ public TokenController(IUserTokenManager userTokenManager, IGenericMapper mapper, IClock clock)
{
_userTokenManager = userTokenManager;
- _logger = logger;
_mapper = mapper;
_clock = clock;
}
@@ -47,43 +40,28 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<HttpCreateTokenResponse>> Create([FromBody] HttpCreateTokenRequest request)
{
- void LogFailure(string reason, Exception? e = null)
- {
- _logger.LogInformation(e, Log.Format(LogCreateFailure,
- ("Reason", reason),
- ("Username", request.Username),
- ("Password", request.Password),
- ("Expire (in days)", request.Expire)
- ));
- }
try
{
DateTime? expireTime = null;
- if (request.Expire != null)
+ if (request.Expire is not null)
expireTime = _clock.GetCurrentTime().AddDays(request.Expire.Value);
var result = await _userTokenManager.CreateTokenAsync(request.Username, request.Password, expireTime);
- _logger.LogInformation(Log.Format(LogCreateSuccess,
- ("Username", request.Username),
- ("Expire At", expireTime?.ToString(CultureInfo.CurrentCulture.DateTimeFormat) ?? "default")
- ));
return new HttpCreateTokenResponse
{
Token = result.Token,
User = await _mapper.MapAsync<HttpUser>(result.User, Url, User)
};
}
- catch (UserNotExistException e)
+ catch (EntityNotExistException)
{
- LogFailure(LogUserNotExist, e);
- return BadRequest(ErrorResponse.TokenController.Create_BadCredential());
+ return this.BadRequestWithCommonResponse(ErrorCodes.TokenController.CreateBadCredential, Resource.MessageTokenCreateBadCredential);
}
- catch (BadPasswordException e)
+ catch (BadPasswordException)
{
- LogFailure(LogBadPassword, e);
- return BadRequest(ErrorResponse.TokenController.Create_BadCredential());
+ return this.BadRequestWithCommonResponse(ErrorCodes.TokenController.CreateBadCredential, Resource.MessageTokenCreateBadCredential);
}
}
@@ -97,45 +75,29 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<HttpVerifyTokenResponse>> Verify([FromBody] HttpVerifyTokenRequest request)
{
- void LogFailure(string reason, Exception? e = null, params (string, object?)[] otherProperties)
- {
- var properties = new (string, object?)[2 + otherProperties.Length];
- properties[0] = ("Reason", reason);
- properties[1] = ("Token", request.Token);
- otherProperties.CopyTo(properties, 2);
- _logger.LogInformation(e, Log.Format(LogVerifyFailure, properties));
- }
-
try
{
var result = await _userTokenManager.VerifyTokenAsync(request.Token);
- _logger.LogInformation(Log.Format(LogVerifySuccess,
- ("Username", result.Username), ("Token", request.Token)));
return new HttpVerifyTokenResponse
{
User = await _mapper.MapAsync<HttpUser>(result, Url, User)
};
}
- catch (UserTokenTimeExpiredException e)
+ catch (UserTokenTimeExpiredException)
{
- LogFailure(LogVerifyExpire, e, ("Expire Time", e.ExpireTime), ("Verify Time", e.VerifyTime));
- return BadRequest(ErrorResponse.TokenController.Verify_TimeExpired());
+ return this.BadRequestWithCommonResponse(ErrorCodes.TokenController.VerifyTimeExpired, Resource.MessageTokenVerifyTimeExpired);
}
- catch (UserTokenVersionExpiredException e)
+ catch (UserTokenVersionExpiredException)
{
- LogFailure(LogVerifyOldVersion, e, ("Token Version", e.TokenVersion), ("Required Version", e.RequiredVersion));
- return BadRequest(ErrorResponse.TokenController.Verify_OldVersion());
-
+ return this.BadRequestWithCommonResponse(ErrorCodes.TokenController.VerifyOldVersion, Resource.MessageTokenVerifyOldVersion);
}
- catch (UserTokenBadFormatException e)
+ catch (UserTokenBadFormatException)
{
- LogFailure(LogVerifyBadFormat, e);
- return BadRequest(ErrorResponse.TokenController.Verify_BadFormat());
+ return this.BadRequestWithCommonResponse(ErrorCodes.TokenController.VerifyBadFormat, Resource.MessageTokenVerifyBadFormat);
}
- catch (UserTokenUserNotExistException e)
+ catch (UserTokenUserNotExistException)
{
- LogFailure(LogVerifyUserNotExist, e);
- return BadRequest(ErrorResponse.TokenController.Verify_UserNotExist());
+ return this.BadRequestWithCommonResponse(ErrorCodes.TokenController.VerifyUserNotExist, Resource.MessageTokenVerifyUserNotExist);
}
}
}
diff --git a/BackEnd/Timeline/Controllers/UserAvatarController.cs b/BackEnd/Timeline/Controllers/UserAvatarController.cs index c280f033..47d46a54 100644 --- a/BackEnd/Timeline/Controllers/UserAvatarController.cs +++ b/BackEnd/Timeline/Controllers/UserAvatarController.cs @@ -1,11 +1,8 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
-using System;
using System.Threading.Tasks;
using Timeline.Filters;
-using Timeline.Helpers;
using Timeline.Helpers.Cache;
using Timeline.Models;
using Timeline.Models.Http;
@@ -13,7 +10,6 @@ using Timeline.Models.Validation; using Timeline.Services.Imaging;
using Timeline.Services.User;
using Timeline.Services.User.Avatar;
-using static Timeline.Resources.Controllers.UserAvatarController;
namespace Timeline.Controllers
{
@@ -24,17 +20,11 @@ namespace Timeline.Controllers [ProducesErrorResponseType(typeof(CommonResponse))]
public class UserAvatarController : Controller
{
- private readonly ILogger<UserAvatarController> _logger;
-
private readonly IUserService _userService;
private readonly IUserAvatarService _service;
- /// <summary>
- ///
- /// </summary>
- public UserAvatarController(ILogger<UserAvatarController> logger, IUserService userService, IUserAvatarService service)
+ public UserAvatarController(IUserService userService, IUserAvatarService service)
{
- _logger = logger;
_userService = userService;
_service = service;
}
@@ -53,18 +43,8 @@ namespace Timeline.Controllers public async Task<IActionResult> Get([FromRoute][Username] string username, [FromHeader(Name = "If-None-Match")] string? ifNoneMatch)
{
_ = ifNoneMatch;
- long id;
- try
- {
- id = await _userService.GetUserIdByUsernameAsync(username);
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, Log.Format(LogGetUserNotExist, ("Username", username)));
- return NotFound(ErrorResponse.UserCommon.NotExist());
- }
-
- return await DataCacheHelper.GenerateActionResult(this, () => _service.GetAvatarDigestAsync(id), () => _service.GetAvatarAsync(id));
+ long userId = await _userService.GetUserIdByUsernameAsync(username);
+ return await DataCacheHelper.GenerateActionResult(this, () => _service.GetAvatarDigestAsync(userId), () => _service.GetAvatarAsync(userId));
}
/// <summary>
@@ -84,43 +64,27 @@ namespace Timeline.Controllers {
if (!this.UserHasPermission(UserPermission.UserManagement) && User.Identity!.Name != username)
{
- _logger.LogInformation(Log.Format(LogPutForbid,
- ("Operator Username", User.Identity.Name), ("Username To Put Avatar", username)));
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage(Resource.MessageForbidNotAdministratorOrOwner);
}
- long id;
- try
- {
- id = await _userService.GetUserIdByUsernameAsync(username);
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, Log.Format(LogPutUserNotExist, ("Username", username)));
- return BadRequest(ErrorResponse.UserCommon.NotExist());
- }
+ long id = await _userService.GetUserIdByUsernameAsync(username);
try
{
var digest = await _service.SetAvatarAsync(id, body);
- _logger.LogInformation(Log.Format(LogPutSuccess,
- ("Username", username), ("Mime Type", Request.ContentType)));
-
Response.Headers.Append("ETag", $"\"{digest.ETag}\"");
return Ok();
}
catch (ImageException e)
{
- _logger.LogInformation(e, Log.Format(LogPutUserBadFormat, ("Username", username)));
return BadRequest(e.Error switch
{
- ImageException.ErrorReason.CantDecode => ErrorResponse.UserAvatar.BadFormat_CantDecode(),
- ImageException.ErrorReason.UnmatchedFormat => ErrorResponse.UserAvatar.BadFormat_UnmatchedFormat(),
- ImageException.ErrorReason.BadSize => ErrorResponse.UserAvatar.BadFormat_BadSize(),
- _ =>
- throw new Exception(ExceptionUnknownAvatarFormatError)
+ ImageException.ErrorReason.CantDecode => new CommonResponse(ErrorCodes.Image.CantDecode, Resource.MessageImageDecodeFailed),
+ ImageException.ErrorReason.UnmatchedFormat => new CommonResponse(ErrorCodes.Image.UnmatchedFormat, Resource.MessageImageFormatUnmatch),
+ ImageException.ErrorReason.BadSize => new CommonResponse(ErrorCodes.Image.BadSize, Resource.MessageImageBadSize),
+ _ => new CommonResponse(ErrorCodes.Image.Unknown, Resource.MessageImageUnknownError)
});
}
}
@@ -143,21 +107,10 @@ namespace Timeline.Controllers {
if (!this.UserHasPermission(UserPermission.UserManagement) && User.Identity!.Name != username)
{
- _logger.LogInformation(Log.Format(LogDeleteForbid,
- ("Operator Username", User.Identity!.Name), ("Username To Delete Avatar", username)));
- return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
+ return this.ForbidWithMessage(Resource.MessageForbidNotAdministratorOrOwner);
}
- long id;
- try
- {
- id = await _userService.GetUserIdByUsernameAsync(username);
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, Log.Format(LogDeleteNotExist, ("Username", username)));
- return BadRequest(ErrorResponse.UserCommon.NotExist());
- }
+ long id = await _userService.GetUserIdByUsernameAsync(username);
await _service.DeleteAvatarAsync(id);
return Ok();
diff --git a/BackEnd/Timeline/Controllers/UserController.cs b/BackEnd/Timeline/Controllers/UserController.cs index 615eac2d..ec732caa 100644 --- a/BackEnd/Timeline/Controllers/UserController.cs +++ b/BackEnd/Timeline/Controllers/UserController.cs @@ -1,18 +1,13 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using Timeline.Auth;
-using Timeline.Helpers;
using Timeline.Models.Http;
using Timeline.Models.Validation;
-using Timeline.Services;
using Timeline.Services.Mapper;
using Timeline.Services.User;
-using static Timeline.Resources.Controllers.UserController;
-using static Timeline.Resources.Messages;
namespace Timeline.Controllers
{
@@ -23,16 +18,14 @@ namespace Timeline.Controllers [ProducesErrorResponseType(typeof(CommonResponse))]
public class UserController : Controller
{
- private readonly ILogger<UserController> _logger;
private readonly IUserService _userService;
private readonly IUserPermissionService _userPermissionService;
private readonly IUserDeleteService _userDeleteService;
private readonly IGenericMapper _mapper;
/// <summary></summary>
- public UserController(ILogger<UserController> logger, IUserService userService, IUserPermissionService userPermissionService, IUserDeleteService userDeleteService, IGenericMapper mapper)
+ public UserController(IUserService userService, IUserPermissionService userPermissionService, IUserDeleteService userDeleteService, IGenericMapper mapper)
{
- _logger = logger;
_userService = userService;
_userPermissionService = userPermissionService;
_userDeleteService = userDeleteService;
@@ -65,16 +58,10 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<HttpUser>> Post([FromBody] HttpUserPostRequest body)
{
- try
- {
- var user = await _userService.CreateUserAsync(
- new CreateUserParams(body.Username, body.Password) { Nickname = body.Nickname });
- return await _mapper.MapAsync<HttpUser>(user, Url, User);
- }
- catch (EntityAlreadyExistException e) when (e.EntityName == EntityNames.User)
- {
- return BadRequest(ErrorResponse.UserController.UsernameConflict());
- }
+
+ var user = await _userService.CreateUserAsync(
+ new CreateUserParams(body.Username, body.Password) { Nickname = body.Nickname });
+ return await _mapper.MapAsync<HttpUser>(user, Url, User);
}
/// <summary>
@@ -87,17 +74,9 @@ namespace Timeline.Controllers [ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<HttpUser>> Get([FromRoute][Username] string username)
{
- try
- {
- var id = await _userService.GetUserIdByUsernameAsync(username);
- var user = await _userService.GetUserAsync(id);
- return await _mapper.MapAsync<HttpUser>(user, Url, User);
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, Log.Format(LogGetUserNotExist, ("Username", username)));
- return NotFound(ErrorResponse.UserCommon.NotExist());
- }
+ var id = await _userService.GetUserIdByUsernameAsync(username);
+ var user = await _userService.GetUserAsync(id);
+ return await _mapper.MapAsync<HttpUser>(user, Url, User);
}
/// <summary>
@@ -116,35 +95,20 @@ namespace Timeline.Controllers {
if (UserHasUserManagementPermission)
{
- try
- {
- var id = await _userService.GetUserIdByUsernameAsync(username);
- var user = await _userService.ModifyUserAsync(id, _mapper.AutoMapperMap<ModifyUserParams>(body));
- return await _mapper.MapAsync<HttpUser>(user, Url, User);
- }
- catch (UserNotExistException e)
- {
- _logger.LogInformation(e, Log.Format(LogPatchUserNotExist, ("Username", username)));
- return NotFound(ErrorResponse.UserCommon.NotExist());
- }
- catch (EntityAlreadyExistException e) when (e.EntityName == EntityNames.User)
- {
- return BadRequest(ErrorResponse.UserController.UsernameConflict());
- }
+ var id = await _userService.GetUserIdByUsernameAsync(username);
+ var user = await _userService.ModifyUserAsync(id, _mapper.AutoMapperMap<ModifyUserParams>(body));
+ return await _mapper.MapAsync<HttpUser>(user, Url, User);
}
else
{
if (User.Identity!.Name != username)
- return StatusCode(StatusCodes.Status403Forbidden,
- ErrorResponse.Common.CustomMessage_Forbid(Common_Forbid_NotSelf));
+ return this.ForbidWithMessage(Resource.MessageForbidNotAdministratorOrOwner);
if (body.Username != null)
- return StatusCode(StatusCodes.Status403Forbidden,
- ErrorResponse.Common.CustomMessage_Forbid(UserController_Patch_Forbid_Username));
+ return this.ForbidWithMessage(Resource.MessageForbidNotAdministrator);
if (body.Password != null)
- return StatusCode(StatusCodes.Status403Forbidden,
- ErrorResponse.Common.CustomMessage_Forbid(UserController_Patch_Forbid_Password));
+ return this.ForbidWithMessage(Resource.MessageForbidNotAdministrator);
var user = await _userService.ModifyUserAsync(this.GetUserId(), _mapper.AutoMapperMap<ModifyUserParams>(body));
return await _mapper.MapAsync<HttpUser>(user, Url, User);
@@ -173,7 +137,7 @@ namespace Timeline.Controllers }
catch (InvalidOperationOnRootUserException)
{
- return BadRequest(ErrorResponse.UserController.Delete_RootUser());
+ return this.BadRequestWithCommonResponse(ErrorCodes.UserController.InvalidOperationOnRootUser, Resource.MessageInvalidOperationOnRootUser);
}
}
@@ -191,11 +155,9 @@ namespace Timeline.Controllers await _userService.ChangePassword(this.GetUserId(), request.OldPassword, request.NewPassword);
return Ok();
}
- catch (BadPasswordException e)
+ catch (BadPasswordException)
{
- _logger.LogInformation(e, Log.Format(LogChangePasswordBadPassword,
- ("Username", User.Identity!.Name), ("Old Password", request.OldPassword)));
- return BadRequest(ErrorResponse.UserController.ChangePassword_BadOldPassword());
+ return this.BadRequestWithCommonResponse(ErrorCodes.UserController.ChangePasswordBadOldPassword, Resource.MessageOldPasswordWrong);
}
// User can't be non-existent or the token is bad.
}
@@ -214,13 +176,9 @@ namespace Timeline.Controllers await _userPermissionService.AddPermissionToUserAsync(id, permission);
return Ok();
}
- catch (UserNotExistException)
- {
- return NotFound(ErrorResponse.UserCommon.NotExist());
- }
catch (InvalidOperationOnRootUserException)
{
- return BadRequest(ErrorResponse.UserController.ChangePermission_RootUser());
+ return this.BadRequestWithCommonResponse(ErrorCodes.UserController.InvalidOperationOnRootUser, Resource.MessageInvalidOperationOnRootUser);
}
}
@@ -238,13 +196,9 @@ namespace Timeline.Controllers await _userPermissionService.RemovePermissionFromUserAsync(id, permission);
return Ok();
}
- catch (UserNotExistException)
- {
- return NotFound(ErrorResponse.UserCommon.NotExist());
- }
catch (InvalidOperationOnRootUserException)
{
- return BadRequest(ErrorResponse.UserController.ChangePermission_RootUser());
+ return this.BadRequestWithCommonResponse(ErrorCodes.UserController.InvalidOperationOnRootUser, Resource.MessageInvalidOperationOnRootUser);
}
}
}
|