From 484f59f9c954fdced635c24c5ab49840c3022d93 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 30 Apr 2019 19:49:27 +0800 Subject: Add avatar upload function. --- Timeline/Controllers/UserController.cs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) (limited to 'Timeline/Controllers/UserController.cs') diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index eaa205de..a18e36e9 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -1,6 +1,8 @@ using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; +using System.IO; using System.Threading.Tasks; using Timeline.Entities; using Timeline.Entities.Http; @@ -82,14 +84,38 @@ namespace Timeline.Controllers [HttpGet("user/{username}/avatar"), Authorize] public async Task GetAvatar([FromRoute] string username) { - var existence = (await _userService.GetUser(username)) != null; - if (!existence) - return NotFound(); - var url = await _userService.GetAvatarUrl(username); + if (url == null) + return NotFound(); return Redirect(url); } + [HttpPut("user/{username}/avatar"), Authorize] + [Consumes("image/png", "image/gif", "image/jpeg", "image/svg+xml")] + public async Task PutAvatar([FromRoute] string username, [FromHeader(Name="Content-Type")] string contentType) + { + bool isAdmin = User.IsInRole("admin"); + if (!isAdmin) + { + if (username != User.Identity.Name) + return StatusCode(StatusCodes.Status403Forbidden, PutAvatarResponse.Forbidden); + } + + var stream = new MemoryStream(); + await Request.Body.CopyToAsync(stream); + var result = await _userService.PutAvatar(username, stream.ToArray(), contentType); + switch (result) + { + case PutAvatarResult.Success: + return Ok(PutAvatarResponse.Success); + case PutAvatarResult.UserNotExists: + return BadRequest(PutAvatarResponse.NotExists); + default: + throw new Exception("Unknown put avatar result."); + } + } + + [HttpPost("userop/changepassword"), Authorize] public async Task ChangePassword([FromBody] ChangePasswordRequest request) { -- cgit v1.2.3