registration and authorization

This commit is contained in:
Вячеслав 2025-04-17 01:06:08 +05:00
parent 2b5f468b84
commit 4423dc360f
12 changed files with 136 additions and 6 deletions

View file

@ -1,5 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using SurveyBackend.DTOs;
using SurveyBackend.Infrastructure.Services;
using SurveyBackend.Mappers.UserDTOs;
namespace SurveyBackend.Controllers;
@ -7,9 +9,32 @@ namespace SurveyBackend.Controllers;
[Route("auth")]
public class AuthController : ControllerBase
{
[HttpPost("login")]
public async Task<IActionResult> GetToken([FromBody] UserLoginDto loginData)
private readonly AuthorizationService _authorizationService;
public AuthController(AuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
[HttpPost("login")]
public async Task<IActionResult> LogIn([FromBody] UserLoginDto loginData)
{
var token = await _authorizationService.LogInUser(loginData.Email, loginData.Password);
return token is null ? Unauthorized() : Ok(new { token = token });
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] UserRegistrationDto registerData)
{
try
{
await _authorizationService.RegisterUser(UserRegistrationMapper.UserRegistrationToModel(registerData));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
}

View file

@ -0,0 +1,17 @@
using SurveyBackend.Core.Models;
using SurveyBackend.Core.Services;
using SurveyBackend.DTOs;
using SurveyBackend.Infrastructure.Services;
namespace SurveyBackend.Mappers.UserDTOs;
public static class UserRegistrationMapper
{
public static User UserRegistrationToModel(UserRegistrationDto dto) => new User
{
Email = dto.Email,
FirstName = dto.FirstName,
LastName = dto.LastName,
Password = dto.Password,
};
}

View file

@ -2,8 +2,12 @@ using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using SurveyBackend.Core.Repositories;
using SurveyBackend.Core.Services;
using SurveyBackend.Infrastructure;
using SurveyBackend.Infrastructure.Data;
using SurveyBackend.Infrastructure.Repositories;
using SurveyBackend.Infrastructure.Services;
using SurveyLib.Core.Repositories;
using SurveyLib.Core.Services;
using SurveyLib.Infrastructure.EFCore.Data;
@ -27,6 +31,13 @@ public class Program
builder.Services.AddScoped<SurveyDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IPasswordHasher, Sha256PasswordHasher>();
builder.Services.AddScoped<AuthorizationService>();
builder.Services.AddScoped<ISurveyRepository, SurveyRepository>();
builder.Services.AddScoped<ISurveyService, SurveyService>();