mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 19:54:55 +00:00
AuthController work
This commit is contained in:
@@ -6,7 +6,7 @@ using Microsoft.AspNetCore.Mvc;
|
||||
namespace Govor.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
private IAccountService _accountService;
|
||||
@@ -18,7 +18,7 @@ public class AuthController : Controller
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
[HttpPost("register")]// api/auth/register
|
||||
[RequireHttps]
|
||||
public async Task<IActionResult> Register([FromBody] UserDto userDto)
|
||||
{
|
||||
@@ -29,8 +29,9 @@ public class AuthController : Controller
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
await _accountService.RegistrationAsync(userDto.Name, userDto.Password);
|
||||
return Ok(new { Message = "User registered successfully" });
|
||||
var token = await _accountService.RegistrationAsync(userDto.Name, userDto.Password);
|
||||
_logger.LogInformation($"Register request for {userDto.Name}");
|
||||
return Ok(new { token });
|
||||
}
|
||||
catch (UserAlreadyExistException ex)
|
||||
{
|
||||
@@ -44,7 +45,7 @@ public class AuthController : Controller
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
[HttpPost("login")]// api/auth/login
|
||||
[RequireHttps]
|
||||
public async Task<IActionResult> Login([FromBody] UserDto userDto)
|
||||
{
|
||||
@@ -55,8 +56,9 @@ public class AuthController : Controller
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
await _accountService.LoginAsync(userDto.Name, userDto.Password);
|
||||
return Ok(new { Message = "User login successfully" });
|
||||
var token = await _accountService.LoginAsync(userDto.Name, userDto.Password);
|
||||
_logger.LogInformation($"Login request for {userDto.Name}");
|
||||
return Ok(new { token });
|
||||
}
|
||||
catch (UserNotRegisteredException ex)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Govor.Core.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Govor.API.Controllers;
|
||||
@@ -13,8 +14,9 @@ public class InviteController : ControllerBase
|
||||
{
|
||||
_groupService = groupService;
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("{code}")]
|
||||
[Authorize]
|
||||
public IActionResult JoinGroup(string code)
|
||||
{
|
||||
var group = _groupService.GetGroupByInvite(code);
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.6" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.6" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6">
|
||||
@@ -15,6 +16,8 @@
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
||||
<PackageReference Include="NSwag.AspNetCore" Version="14.4.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="9.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
+38
-5
@@ -1,16 +1,41 @@
|
||||
using Govor.API.Services;
|
||||
using Govor.API.Services.Authentication;
|
||||
using Govor.Core.Infrastructure.Extensions;
|
||||
using Govor.Core.Infrastructure.Validators;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Repositories;
|
||||
using Govor.Core.Repositories.Users;
|
||||
using Govor.Core.Services;
|
||||
using Govor.Data;
|
||||
using Govor.Data.Repositories;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
var configuration = builder.Configuration;
|
||||
var services = builder.Services;
|
||||
|
||||
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
|
||||
builder.Services.Configure<JwtOption>(configuration.GetSection(nameof(JwtOption)));
|
||||
|
||||
// Add services
|
||||
|
||||
builder.Services.AddSignalR();
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddAuthentication("Bearer")
|
||||
.AddJwtBearer();
|
||||
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
builder.Services.AddScoped<IPasswordHasher, PasswordHasher>();
|
||||
builder.Services.AddScoped<IJwtService, JwtService>();
|
||||
builder.Services.AddScoped<IAccountService, AuthService>();
|
||||
builder.Services.AddScoped<IUsersRepository, UsersRepository>();
|
||||
builder.Services.AddScoped<IObjectValidator<User>, UserValidator>();
|
||||
|
||||
builder.Services.AddDbContext<GovorDbContext>(
|
||||
options =>
|
||||
{
|
||||
@@ -19,22 +44,30 @@ builder.Services.AddDbContext<GovorDbContext>(
|
||||
);
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddSwaggerGen();
|
||||
//builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
//app.MapOpenApi();
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Map("/hello", [Authorize]() => "Hello World!");
|
||||
app.Map("/", () => "Not for browser");
|
||||
|
||||
app.Run();
|
||||
@@ -1,5 +1,8 @@
|
||||
using Govor.Core;
|
||||
using Govor.Core.Infrastructure.Extensions;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Repositories;
|
||||
using Govor.Core.Repositories.Users;
|
||||
using Govor.Core.Services;
|
||||
|
||||
namespace Govor.API.Services.Authentication;
|
||||
@@ -7,27 +10,56 @@ namespace Govor.API.Services.Authentication;
|
||||
public class AuthService : IAccountService
|
||||
{
|
||||
private readonly IPasswordHasher _passwordHasher;
|
||||
private readonly IJwtService _jwtService;
|
||||
private readonly IUsersRepository _usersRepository;
|
||||
|
||||
public AuthService(IUsersRepository usersRepository, IPasswordHasher passwordHasher)
|
||||
|
||||
public AuthService(IUsersRepository usersRepository, IJwtService jwtService, IPasswordHasher passwordHasher)
|
||||
{
|
||||
_usersRepository = usersRepository;
|
||||
_jwtService = jwtService;
|
||||
_passwordHasher = passwordHasher;
|
||||
}
|
||||
public Task RegistrationAsync(string name, string password)
|
||||
|
||||
public async Task<string> RegistrationAsync(string name, string password)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
if (await _usersRepository.ExistsUsernameAsync(name))
|
||||
throw new UserAlreadyExistException(name);
|
||||
|
||||
var passwordHash = _passwordHasher.Hash(password);
|
||||
|
||||
var user = new User
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = name,
|
||||
Description = string.Empty,
|
||||
PasswordHash = passwordHash,
|
||||
CreatedOn = DateOnly.FromDateTime(DateTime.Now),
|
||||
IconId = Guid.NewGuid(),
|
||||
WasOnline = DateTime.UtcNow
|
||||
//Role = role == "Admin" ? "Admin" : "User" // Ограничение ролей
|
||||
};
|
||||
|
||||
//await _usersRepository.AddAsync(user);
|
||||
|
||||
return _jwtService.GenerateJwtToken(user);
|
||||
}
|
||||
|
||||
public async Task<string> LoginAsync(string name, string password)
|
||||
{
|
||||
if (await _usersRepository.ExistsUsernameAsync(name) == false)
|
||||
throw new UserNotRegisteredException(name);
|
||||
|
||||
throw new NotImplementedException();
|
||||
|
||||
var user = await _usersRepository.FindByUsernameAsync(name);
|
||||
|
||||
if (_passwordHasher.Verify(password, user.PasswordHash) == false)
|
||||
throw new LoginUserException();
|
||||
|
||||
return _jwtService.GenerateJwtToken(user);
|
||||
}
|
||||
}
|
||||
|
||||
public class UserAlreadyExistException(string username) : Exception($"{username} is already exists!") { }
|
||||
public class LoginUserException : GovorCoreException { }
|
||||
|
||||
public class UserNotRegisteredException(string username) : Exception($"{username} is not registered!") { }
|
||||
public class UserAlreadyExistException(string username) : GovorCoreException($"{username} is already exists!") { }
|
||||
|
||||
public class UserNotRegisteredException(string username) : GovorCoreException($"{username} is not registered!") { }
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Govor.API.Services.Authentication;
|
||||
|
||||
public class JwtOption
|
||||
{
|
||||
public string SecretKeу {get; set;}
|
||||
public int Hours { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Govor.Core.Models;
|
||||
using Govor.Core.Services;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Govor.API.Services.Authentication;
|
||||
|
||||
public class JwtService : IJwtService
|
||||
{
|
||||
private JwtOption _jwtOption;
|
||||
|
||||
public JwtService(IOptions<JwtOption> options)
|
||||
{
|
||||
_jwtOption = options.Value;
|
||||
}
|
||||
public string GenerateJwtToken(User user)
|
||||
{
|
||||
Claim[] claims = [new("userID", user.Id.ToString())];
|
||||
|
||||
var singing = new SigningCredentials(
|
||||
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SecretKeу)),
|
||||
SecurityAlgorithms.HmacSha256Signature);
|
||||
|
||||
var token = new JwtSecurityToken(signingCredentials: singing,
|
||||
expires: DateTime.UtcNow.AddHours(_jwtOption.Hours));
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,9 @@
|
||||
"ConnectionStrings": {
|
||||
"GovorDbContext": "Host=localhost;Port=5432;Database=DbGovor;Username=postgres;Password=stalcker;"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"JwtOption": {
|
||||
"SecretKeу": "MY VERY SECRET KEY asdasdpafjhasofafpajsfj",
|
||||
"Hours": "24"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user