DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/AuthController.cs
2021-10-19 15:22:18 +05:00

105 lines
4.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers
{
[Route("/auth")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IAuthService authService;
public AuthController(IAuthService authService)
{
this.authService = authService;
}
/// <summary>
/// Аутентификация пользователя
/// </summary>
/// <param name="auth"></param>
/// <param name="token">Токен отмены задачи</param>
/// <response code="200">новый токен</response>
/// <response code="400">логин и пароль не подходят</response>
[AllowAnonymous]
[HttpPost("login")]
[SwaggerOperation(OperationId = "login")]
[ProducesResponseType(typeof(UserTokenDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> LoginAsync([FromBody] AuthDto auth, CancellationToken token = default)
{
var userToken = await authService.LoginAsync(auth.Login,
auth.Password, token).ConfigureAwait(false);
if (userToken is null)
BadRequest();//"wrong login or password"
return Ok(userToken);
}
/// <summary>
/// Продление срока действия токена
/// </summary>
/// <returns code="200">новый токен</returns>
[Authorize]
[HttpGet("refresh")]
public IActionResult Refresh()
{
var newToken = authService.Refresh(User);
return Ok(newToken);
}
/// <summary>
/// Регистрация пользователя. Доступна администратору
/// </summary>
/// <returns code="200">Ок</returns>
[Authorize]
[HttpPost]
public IActionResult Register(UserDto user)
{
const string roleName = "Администратор";
if (!User.IsInRole(roleName))
return Forbid($"You mast be an {roleName}.");
var code = authService.Register(user);
return code switch
{
0 => Ok(),
-1 => BadRequest("Логин должен быть длиннее 3х знаков."),
-2 => BadRequest("Пароль должен быть длиннее 3х знаков."),
-3 => BadRequest("Email не должен быть длиннее 255 знаков."),
-4 => BadRequest("Телефон не должен быть длиннее 50 знаков."),
-5 => BadRequest("Название должности не должно быть длиннее 255 символов."),
_ => BadRequest(),
};
}
/// <summary>
/// Смена пароля пользователя. Доступна пользователю и администратору
/// </summary>
/// <returns code="200">Ок</returns>
[Authorize]
[HttpPut("{idUser}/ChangePassword")]
public IActionResult ChangePassword([FromRoute]int idUser, [FromBody]string newPassword)
{
const string roleName = "Администратор";
var allow = (User.GetUserId() == idUser) || User.IsInRole(roleName);
if (!allow)
return Forbid($"You mast be an {roleName} or user with id:{idUser}.");
var code = authService.ChangePassword(idUser, newPassword);
return code switch
{
0 => Ok(),
-1 => BadRequest("Нет такого пользователя"),
_ => BadRequest(),
};
}
}
}