aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-11-12 23:21:31 +0800
committercrupest <crupest@outlook.com>2020-11-12 23:21:31 +0800
commitd3da412fa7e10db8c721846152a2c056dd4ccbcf (patch)
tree4cd665209dc63fb8f9c658e9562481e32f7d3986 /BackEnd/Timeline
parentee1b2b5b100268aa510257a1a2cd4cd03f9fc72b (diff)
downloadtimeline-d3da412fa7e10db8c721846152a2c056dd4ccbcf.tar.gz
timeline-d3da412fa7e10db8c721846152a2c056dd4ccbcf.tar.bz2
timeline-d3da412fa7e10db8c721846152a2c056dd4ccbcf.zip
...
Diffstat (limited to 'BackEnd/Timeline')
-rw-r--r--BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs5
-rw-r--r--BackEnd/Timeline/Controllers/TimelineController.cs20
-rw-r--r--BackEnd/Timeline/Controllers/UserAvatarController.cs6
-rw-r--r--BackEnd/Timeline/Controllers/UserController.cs24
-rw-r--r--BackEnd/Timeline/Models/Http/UserController.cs21
-rw-r--r--BackEnd/Timeline/Services/TimelineService.cs14
-rw-r--r--BackEnd/Timeline/Services/UserService.cs4
7 files changed, 39 insertions, 55 deletions
diff --git a/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs b/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs
index 00a65454..9096978d 100644
--- a/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs
+++ b/BackEnd/Timeline/Controllers/ControllerAuthExtensions.cs
@@ -2,15 +2,16 @@
using System;
using System.Security.Claims;
using Timeline.Auth;
+using Timeline.Services;
using static Timeline.Resources.Controllers.ControllerAuthExtensions;
namespace Timeline.Controllers
{
public static class ControllerAuthExtensions
{
- public static bool IsAdministrator(this ControllerBase controller)
+ public static bool UserHasPermission(this ControllerBase controller, UserPermission permission)
{
- return controller.User != null && controller.User.IsAdministrator();
+ return controller.User != null && controller.User.HasPermission(permission);
}
public static long GetUserId(this ControllerBase controller)
diff --git a/BackEnd/Timeline/Controllers/TimelineController.cs b/BackEnd/Timeline/Controllers/TimelineController.cs
index 9a3147ea..45060b5d 100644
--- a/BackEnd/Timeline/Controllers/TimelineController.cs
+++ b/BackEnd/Timeline/Controllers/TimelineController.cs
@@ -43,6 +43,8 @@ namespace Timeline.Controllers
_mapper = mapper;
}
+ private bool UserHasAllTimelineManagementPermission => this.UserHasPermission(UserPermission.AllTimelineManagement);
+
/// <summary>
/// List all timelines.
/// </summary>
@@ -180,7 +182,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<List<TimelinePostInfo>>> PostListGet([FromRoute][GeneralTimelineName] string name, [FromQuery] DateTime? modifiedSince, [FromQuery] bool? includeDeleted)
{
- if (!this.IsAdministrator() && !await _service.HasReadPermission(name, this.GetOptionalUserId()))
+ if (!UserHasAllTimelineManagementPermission && !await _service.HasReadPermission(name, this.GetOptionalUserId()))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -208,7 +210,7 @@ namespace Timeline.Controllers
public async Task<IActionResult> PostDataGet([FromRoute][GeneralTimelineName] string name, [FromRoute] long id, [FromHeader(Name = "If-None-Match")] string? ifNoneMatch)
{
_ = ifNoneMatch;
- if (!this.IsAdministrator() && !await _service.HasReadPermission(name, this.GetOptionalUserId()))
+ if (!UserHasAllTimelineManagementPermission && !await _service.HasReadPermission(name, this.GetOptionalUserId()))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -246,7 +248,7 @@ namespace Timeline.Controllers
public async Task<ActionResult<TimelinePostInfo>> PostPost([FromRoute][GeneralTimelineName] string name, [FromBody] TimelinePostCreateRequest body)
{
var id = this.GetUserId();
- if (!this.IsAdministrator() && !await _service.IsMemberOf(name, id))
+ if (!UserHasAllTimelineManagementPermission && !await _service.IsMemberOf(name, id))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -313,7 +315,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<CommonDeleteResponse>> PostDelete([FromRoute][GeneralTimelineName] string name, [FromRoute] long id)
{
- if (!this.IsAdministrator() && !await _service.HasPostModifyPermission(name, id, this.GetUserId()))
+ if (!UserHasAllTimelineManagementPermission && !await _service.HasPostModifyPermission(name, id, this.GetUserId()))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -342,7 +344,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<TimelineInfo>> TimelinePatch([FromRoute][GeneralTimelineName] string name, [FromBody] TimelinePatchRequest body)
{
- if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
+ if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId())))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -365,7 +367,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult> TimelineMemberPut([FromRoute][GeneralTimelineName] string name, [FromRoute][Username] string member)
{
- if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
+ if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId())))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -393,7 +395,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult> TimelineMemberDelete([FromRoute][GeneralTimelineName] string name, [FromRoute][Username] string member)
{
- if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
+ if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId())))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -448,7 +450,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<CommonDeleteResponse>> TimelineDelete([FromRoute][TimelineName] string name)
{
- if (!this.IsAdministrator() && !(await _service.HasManagePermission(name, this.GetUserId())))
+ if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(name, this.GetUserId())))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
@@ -472,7 +474,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<TimelineInfo>> TimelineOpChangeName([FromBody] TimelineChangeNameRequest body)
{
- if (!this.IsAdministrator() && !(await _service.HasManagePermission(body.OldName, this.GetUserId())))
+ if (!UserHasAllTimelineManagementPermission && !(await _service.HasManagePermission(body.OldName, this.GetUserId())))
{
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
diff --git a/BackEnd/Timeline/Controllers/UserAvatarController.cs b/BackEnd/Timeline/Controllers/UserAvatarController.cs
index bc4afa30..44d45b76 100644
--- a/BackEnd/Timeline/Controllers/UserAvatarController.cs
+++ b/BackEnd/Timeline/Controllers/UserAvatarController.cs
@@ -86,7 +86,7 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<IActionResult> Put([FromRoute][Username] string username, [FromBody] ByteData body)
{
- if (!User.IsAdministrator() && User.Identity.Name != username)
+ if (!this.UserHasPermission(UserPermission.UserManagement) && User.Identity!.Name != username)
{
_logger.LogInformation(Log.Format(LogPutForbid,
("Operator Username", User.Identity.Name), ("Username To Put Avatar", username)));
@@ -149,10 +149,10 @@ namespace Timeline.Controllers
[Authorize]
public async Task<IActionResult> Delete([FromRoute][Username] string username)
{
- if (!User.IsAdministrator() && User.Identity.Name != username)
+ if (!this.UserHasPermission(UserPermission.UserManagement) && User.Identity!.Name != username)
{
_logger.LogInformation(Log.Format(LogDeleteForbid,
- ("Operator Username", User.Identity.Name), ("Username To Delete Avatar", username)));
+ ("Operator Username", User.Identity!.Name), ("Username To Delete Avatar", username)));
return StatusCode(StatusCodes.Status403Forbidden, ErrorResponse.Common.Forbid());
}
diff --git a/BackEnd/Timeline/Controllers/UserController.cs b/BackEnd/Timeline/Controllers/UserController.cs
index 02c09aab..524e5559 100644
--- a/BackEnd/Timeline/Controllers/UserController.cs
+++ b/BackEnd/Timeline/Controllers/UserController.cs
@@ -65,7 +65,8 @@ namespace Timeline.Controllers
{
try
{
- var user = await _userService.GetUserByUsername(username);
+ var id = await _userService.GetUserIdByUsername(username);
+ var user = await _userService.GetUser(id);
return Ok(ConvertToUserInfo(user));
}
catch (UserNotExistException e)
@@ -89,11 +90,12 @@ namespace Timeline.Controllers
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserInfo>> Patch([FromBody] UserPatchRequest body, [FromRoute][Username] string username)
{
- if (this.IsAdministrator())
+ if (this.UserHasPermission(UserPermission.UserManagement))
{
try
{
- var user = await _userService.ModifyUser(username, _mapper.Map<User>(body));
+ var id = await _userService.GetUserIdByUsername(username);
+ var user = await _userService.ModifyUser(id, _mapper.Map<ModifyUserParams>(body));
return Ok(ConvertToUserInfo(user));
}
catch (UserNotExistException e)
@@ -108,7 +110,7 @@ namespace Timeline.Controllers
}
else
{
- if (User.Identity.Name != username)
+ if (User.Identity!.Name != username)
return StatusCode(StatusCodes.Status403Forbidden,
ErrorResponse.Common.CustomMessage_Forbid(Common_Forbid_NotSelf));
@@ -120,11 +122,7 @@ namespace Timeline.Controllers
return StatusCode(StatusCodes.Status403Forbidden,
ErrorResponse.Common.CustomMessage_Forbid(UserController_Patch_Forbid_Password));
- if (body.Administrator != null)
- return StatusCode(StatusCodes.Status403Forbidden,
- ErrorResponse.Common.CustomMessage_Forbid(UserController_Patch_Forbid_Administrator));
-
- var user = await _userService.ModifyUser(this.GetUserId(), _mapper.Map<User>(body));
+ var user = await _userService.ModifyUser(this.GetUserId(), _mapper.Map<ModifyUserParams>(body));
return Ok(ConvertToUserInfo(user));
}
}
@@ -134,7 +132,7 @@ namespace Timeline.Controllers
/// </summary>
/// <param name="username">Username of the user to delete.</param>
/// <returns>Info of deletion.</returns>
- [HttpDelete("users/{username}"), AdminAuthorize]
+ [HttpDelete("users/{username}"), PermissionAuthorize(UserPermission.UserManagement)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
@@ -151,7 +149,7 @@ namespace Timeline.Controllers
/// Create a new user. You have to be administrator.
/// </summary>
/// <returns>The new user's info.</returns>
- [HttpPost("userop/createuser"), AdminAuthorize]
+ [HttpPost("userop/createuser"), PermissionAuthorize(UserPermission.UserManagement)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
@@ -160,7 +158,7 @@ namespace Timeline.Controllers
{
try
{
- var user = await _userService.CreateUser(_mapper.Map<User>(body));
+ var user = await _userService.CreateUser(body.Username, body.Password);
return Ok(ConvertToUserInfo(user));
}
catch (EntityAlreadyExistException e) when (e.EntityName == EntityNames.User)
@@ -186,7 +184,7 @@ namespace Timeline.Controllers
catch (BadPasswordException e)
{
_logger.LogInformation(e, Log.Format(LogChangePasswordBadPassword,
- ("Username", User.Identity.Name), ("Old Password", request.OldPassword)));
+ ("Username", User.Identity!.Name), ("Old Password", request.OldPassword)));
return BadRequest(ErrorResponse.UserController.ChangePassword_BadOldPassword());
}
// User can't be non-existent or the token is bad.
diff --git a/BackEnd/Timeline/Models/Http/UserController.cs b/BackEnd/Timeline/Models/Http/UserController.cs
index 6bc5a66e..92a63874 100644
--- a/BackEnd/Timeline/Models/Http/UserController.cs
+++ b/BackEnd/Timeline/Models/Http/UserController.cs
@@ -2,6 +2,7 @@ using AutoMapper;
using System.ComponentModel.DataAnnotations;
using Timeline.Controllers;
using Timeline.Models.Validation;
+using Timeline.Services;
namespace Timeline.Models.Http
{
@@ -27,11 +28,6 @@ namespace Timeline.Models.Http
/// </summary>
[Nickname]
public string? Nickname { get; set; }
-
- /// <summary>
- /// Whether to be administrator. Null if not change. Need to be administrator.
- /// </summary>
- public bool? Administrator { get; set; }
}
/// <summary>
@@ -50,18 +46,6 @@ namespace Timeline.Models.Http
/// </summary>
[Required, MinLength(1)]
public string Password { get; set; } = default!;
-
- /// <summary>
- /// Whether the new user is administrator.
- /// </summary>
- [Required]
- public bool? Administrator { get; set; }
-
- /// <summary>
- /// Nickname of the new user.
- /// </summary>
- [Nickname]
- public string? Nickname { get; set; }
}
/// <summary>
@@ -86,8 +70,7 @@ namespace Timeline.Models.Http
{
public UserControllerAutoMapperProfile()
{
- CreateMap<UserPatchRequest, User>(MemberList.Source);
- CreateMap<CreateUserRequest, User>(MemberList.Source);
+ CreateMap<UserPatchRequest, ModifyUserParams>();
}
}
}
diff --git a/BackEnd/Timeline/Services/TimelineService.cs b/BackEnd/Timeline/Services/TimelineService.cs
index 4bcae596..04870dcf 100644
--- a/BackEnd/Timeline/Services/TimelineService.cs
+++ b/BackEnd/Timeline/Services/TimelineService.cs
@@ -414,12 +414,12 @@ namespace Timeline.Services
/// Remember to include Members when query.
private async Task<Models.Timeline> MapTimelineFromEntity(TimelineEntity entity)
{
- var owner = await _userService.GetUserById(entity.OwnerId);
+ var owner = await _userService.GetUser(entity.OwnerId);
var members = new List<User>();
foreach (var memberEntity in entity.Members)
{
- members.Add(await _userService.GetUserById(memberEntity.UserId));
+ members.Add(await _userService.GetUser(memberEntity.UserId));
}
var name = entity.Name ?? ("@" + owner.Username);
@@ -441,7 +441,7 @@ namespace Timeline.Services
private async Task<TimelinePost> MapTimelinePostFromEntity(TimelinePostEntity entity, string timelineName)
{
- User? author = entity.AuthorId.HasValue ? await _userService.GetUserById(entity.AuthorId.Value) : null;
+ User? author = entity.AuthorId.HasValue ? await _userService.GetUser(entity.AuthorId.Value) : null;
ITimelinePostContent? content = null;
@@ -699,7 +699,7 @@ namespace Timeline.Services
var timelineId = await FindTimelineId(timelineName);
var timelineEntity = await _database.Timelines.Where(t => t.Id == timelineId).SingleAsync();
- var author = await _userService.GetUserById(authorId);
+ var author = await _userService.GetUser(authorId);
var currentTime = _clock.GetCurrentTime();
var finalTime = time ?? currentTime;
@@ -742,7 +742,7 @@ namespace Timeline.Services
var timelineId = await FindTimelineId(timelineName);
var timelineEntity = await _database.Timelines.Where(t => t.Id == timelineId).SingleAsync();
- var author = await _userService.GetUserById(authorId);
+ var author = await _userService.GetUser(authorId);
var imageFormat = await _imageValidator.Validate(data);
@@ -1098,14 +1098,14 @@ namespace Timeline.Services
ValidateTimelineName(name, nameof(name));
- var user = await _userService.GetUserById(owner);
+ var user = await _userService.GetUser(owner);
var conflict = await _database.Timelines.AnyAsync(t => t.Name == name);
if (conflict)
throw new EntityAlreadyExistException(EntityNames.Timeline, null, ExceptionTimelineNameConflict);
- var newEntity = CreateNewTimelineEntity(name, user.Id!.Value);
+ var newEntity = CreateNewTimelineEntity(name, user.Id);
_database.Timelines.Add(newEntity);
await _database.SaveChangesAsync();
diff --git a/BackEnd/Timeline/Services/UserService.cs b/BackEnd/Timeline/Services/UserService.cs
index ed637ba3..b925742e 100644
--- a/BackEnd/Timeline/Services/UserService.cs
+++ b/BackEnd/Timeline/Services/UserService.cs
@@ -17,7 +17,7 @@ namespace Timeline.Services
/// <summary>
/// Null means not change.
/// </summary>
- public record ModifyUserParams(string? Username, string? Password, string? Nickname);
+ public record ModifyUserParams(string? Username = null, string? Password = null, string? Nickname = null);
public interface IUserService
{
@@ -74,7 +74,7 @@ namespace Timeline.Services
/// <param name="id">The id of the user.</param>
/// <param name="param">The new information.</param>
/// <returns>The new user info.</returns>
- /// <exception cref="ArgumentException">Thrown when some fields in <paramref name="info"/> is bad.</exception>
+ /// <exception cref="ArgumentException">Thrown when some fields in <paramref name="param"/> is bad.</exception>
/// <exception cref="UserNotExistException">Thrown when user with given id does not exist.</exception>
/// <remarks>
/// Version will increase if password is changed.