Compare commits

..

8 Commits

14 changed files with 202 additions and 25 deletions
+3
View File
@@ -1,3 +1,6 @@
POSTGRES_USER=app
POSTGRES_PASSWORD=app
POSTGRES_DB=appdb
JWT_SECRET_KEY=mysecretkeyqwertyuiopasdfghjklzxcvbnm
JWT_EXPIRES=00:01:00
+5
View File
@@ -31,6 +31,9 @@ cp .env.example .env
POSTGRES_USER=app
POSTGRES_PASSWORD=app
POSTGRES_DB=appdb
JWT_SECRET_KEY=mysecretkeyqwertyuiopasdfghjklzxcvbnm
JWT_EXPIRES=00:01:00
```
### Настройка `docker-compose.yml`
@@ -52,6 +55,8 @@ services:
- db
environment:
ConnectionStrings__DefaultConnection: Host=db;Database=${POSTGRES_DB};Username=${POSTGRES_USER};Password=${POSTGRES_PASSWORD}
AuthSettings__SecretKey: ${JWT_SECRET_KEY}
AuthSettings__Expires: "${JWT_EXPIRES}"
db:
image: postgres:17
@@ -3,6 +3,9 @@ using Microsoft.EntityFrameworkCore;
using URL_Shortener.DTO;
using URL_Shortener.Models;
using HashidsNet;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using URL_Shortener.Extensions;
namespace URL_Shortener.Controllers
{
@@ -38,13 +41,15 @@ namespace URL_Shortener.Controllers
}
[HttpPost]
[Authorize]
public async Task<IActionResult> CreateShortUrlAsync(CreateShortUrlDto dto)
{
var shortUrl = new ShortUrl
{
OriginalUrl = dto.OriginalUrl,
ExpirationDateTime = dto.ExpirationDateTime,
ClickLimit = dto.ClickLimit
ClickLimit = dto.ClickLimit,
UserId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!)
};
await _db.ShortUrls.AddAsync(shortUrl);
await _db.SaveChangesAsync();
@@ -55,12 +60,16 @@ namespace URL_Shortener.Controllers
}
[HttpPatch("{id:int}")]
[Authorize]
public async Task<IActionResult> UpdateShortUrlAsync(int id, UpdateShortUrlDto dto)
{
var shortUrl = await _db.ShortUrls.FindAsync(id);
if (shortUrl == null)
return NotFound("Short URL not found");
if (!User.CompareId(shortUrl.UserId))
throw new Exception("Not authorized");
if (!string.IsNullOrEmpty(dto.OriginalUrl))
shortUrl.OriginalUrl = dto.OriginalUrl;
if (dto.ExpirationDateTime.HasValue)
@@ -78,12 +87,16 @@ namespace URL_Shortener.Controllers
}
[HttpDelete("{id:int}")]
[Authorize]
public async Task<IActionResult> DeleteShortUrlByIdAsync(int id)
{
var shortUrl = await _db.ShortUrls.FindAsync(id);
if (shortUrl == null)
return NotFound();
if (!User.CompareId(shortUrl.UserId))
throw new Exception("Not authorized");
_db.ShortUrls.Remove(shortUrl);
var clickInfos = _db.ClickInfos.Where(c => c.ShortUrlId == id);
+13 -10
View File
@@ -1,24 +1,27 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using URL_Shortener.Models;
using URL_Shortener.DTO;
using URL_Shortener.Services;
namespace URL_Shortener.Controllers
{
[ApiController]
[Route("user")]
public class UserController(AppDbContext db) : ControllerBase
public class UserController(UserService userService) : ControllerBase
{
private readonly AppDbContext _db = db;
private readonly UserService _userService = userService;
[HttpGet("email")]
public async Task<IActionResult> GetUserByEmailAsync(string email)
[HttpPost("register")]
public async Task<IActionResult> RegisterAsync(RegisterUserDTO dto)
{
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == email);
if (user == null)
return NotFound("User not found");
var jwt = await _userService.RegisterAsync(dto.Name, dto.Email, dto.Password);
return Ok(jwt);
}
return Ok(user);
[HttpPost("login")]
public async Task<IActionResult> LoginAsync(LoginUserDTO dto)
{
var jwt = await _userService.LoginAsync(dto.Email, dto.Password);
return Ok(jwt);
}
}
}
+12
View File
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace URL_Shortener.DTO
{
public class LoginUserDTO
{
[Required, EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
}
}
+14
View File
@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
namespace URL_Shortener.DTO
{
public class RegisterUserDTO
{
[Required]
public string Name { get; set; } = string.Empty;
[Required, EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
}
}
@@ -0,0 +1,12 @@
using System.Security.Claims;
namespace URL_Shortener.Extensions;
public static class ClaimsPrincipalExtensions
{
public static bool CompareId(this ClaimsPrincipal claimsPrincipal, int userId)
{
return int.TryParse(claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier), out int id) &&
id == userId;
}
}
+39 -4
View File
@@ -1,5 +1,11 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using URL_Shortener;
using URL_Shortener.Services;
using URL_Shortener.Settings;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
@@ -10,11 +16,41 @@ builder.Services.AddControllers();
builder.Services.AddOpenApi();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("bearer", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "JWT Authorization header using the Bearer scheme."
});
options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference("bearer", document)] = []
});
});
// Чтобы короткие коды генерировать
builder.Services.AddSingleton<HashidsNet.Hashids>();
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<JwtService>();
var authSettings = builder.Configuration.GetSection("AuthSettings");
builder.Services.Configure<AuthSettings>(authSettings);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o => o.TokenValidationParameters = new()
{
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
authSettings.Get<AuthSettings>()!.SecretKey))
});
builder.Services.AddDbContext<AppDbContext>(options =>
{
var connString = builder.Configuration.GetConnectionString("DefaultConnection");
@@ -40,8 +76,7 @@ using (var scope = app.Services.CreateScope())
retry.Execute(db.Database.Migrate);
}
//app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
+32
View File
@@ -0,0 +1,32 @@
using URL_Shortener.Models;
using System.IdentityModel.Tokens.Jwt;
using URL_Shortener.Settings;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace URL_Shortener.Services
{
public class JwtService(IOptions<AuthSettings> options)
{
public string GenerateToken(User user)
{
var claims = new List<Claim>() {
new(ClaimTypes.Name, user.Name),
new(ClaimTypes.Email, user.Email),
new(ClaimTypes.NameIdentifier, user.Id.ToString())
};
var jwt = new JwtSecurityToken(
expires: DateTime.UtcNow.Add(options.Value.Expires),
claims: claims,
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Value.SecretKey)),
SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(jwt);
}
}
}
+36 -4
View File
@@ -1,10 +1,42 @@
namespace URL_Shortener.Services
using URL_Shortener.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace URL_Shortener.Services
{
public class UserService
public class UserService(AppDbContext db, JwtService jwtService)
{
public async Task Register(string userName, string email, string hashedPassword)
private readonly AppDbContext _db = db;
private readonly JwtService _jwtService = jwtService;
public async Task<string> RegisterAsync(string userName, string email, string password, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
if (await _db.Users.FirstOrDefaultAsync(u => u.Email == email, cancellationToken) != null)
throw new Exception("This user already exists.");
var user = new User()
{
Name = userName,
Email = email
};
user.HashedPassword = new PasswordHasher<User>().HashPassword(user, password);
await _db.Users.AddAsync(user, cancellationToken);
await _db.SaveChangesAsync(cancellationToken);
return _jwtService.GenerateToken(user);
}
public async Task<string> LoginAsync(string email, string password, CancellationToken cancellationToken = default)
{
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == email, cancellationToken) ??
throw new Exception("User not found.");
var res = new PasswordHasher<User>().VerifyHashedPassword(user, user.HashedPassword, password);
if (res == PasswordVerificationResult.Failed)
throw new Exception("Incorrect password.");
return _jwtService.GenerateToken(user);
}
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace URL_Shortener.Settings
{
public class AuthSettings
{
public string SecretKey { get; set; } = string.Empty;
public TimeSpan Expires { get; set; }
}
}
+8 -6
View File
@@ -11,19 +11,21 @@
<ItemGroup>
<PackageReference Include="Hashids.net" Version="1.7.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.7">
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.7">
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.19.1" />
</ItemGroup>
</Project>
+4
View File
@@ -8,5 +8,9 @@
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=appdb;Username=postgres;Password=app"
},
"AuthSettings": {
"SecretKey": "mysecretkeyqwertyuiopasdfghjklzxcvbnm",
"Expires": "00:01:00"
}
}
+2
View File
@@ -9,6 +9,8 @@ services:
- db
environment:
ConnectionStrings__DefaultConnection: Host=db;Database=${POSTGRES_DB};Username=${POSTGRES_USER};Password=${POSTGRES_PASSWORD}
AuthSettings__SecretKey: ${JWT_SECRET_KEY}
AuthSettings__Expires: "${JWT_EXPIRES}"
db:
image: postgres:17