Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
using FileService.Service.ApiModels.FileDocumentModels;
using FileService.Service.Dtos.FileDocumentDtos;
using FileService.Service.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace FileService.Api.Controllers
{
// [Authorize]
// [Authorize(Policy = "Permission")]
// [Authorize(Roles = "ADMIN")]
[Route("file/api/[controller]")]
[ApiController]
public class FileDocumentController : BaseApiController
Expand Down
4 changes: 4 additions & 0 deletions FileService/FileService.Api/Middlewares/AuthenMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
using FileService.Core.ApiModels;
using System.Security.Claims;

namespace FileService.Api.Middlewares
{
public class AuthenMiddleware
{
private readonly RequestDelegate _next;


public AuthenMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
//lấy userId và sessionId từ claims
var userId = httpContext.User.Claims.FirstOrDefault(c => c.Type == "userId")?.Value;
var sessionId = httpContext.User.Claims.FirstOrDefault(c => c.Type == "sessionId")?.Value;

Expand Down
18 changes: 8 additions & 10 deletions FileService/FileService.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
using FileService.Service.Implementation;
using FileService.Service.Interfaces;
using Microsoft.Extensions.FileProviders;
using System.Security.Claims;

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

Expand All @@ -39,7 +40,7 @@

var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Console.WriteLine($"ASPNETCORE_ENVIRONMENT: {env}");
builder.Services.Configure<MinioConfig>(builder.Configuration.GetSection("MinioConfig"));
//builder.Services.Configure<MinioConfig>(builder.Configuration.GetSection("MinioConfig"));

builder.Services.Configure<MongoDbSettings>(builder.Configuration.GetSection("MongoDbSettings"));
builder.Services.Configure<FfmpegSettings>(builder.Configuration.GetSection("FfmpegSettings"));
Expand Down Expand Up @@ -98,7 +99,11 @@
ValidateIssuerSigningKey = true,
ValidIssuer = appSettings.Jwt.Issuer,
ValidAudience = appSettings.Jwt.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Jwt.Key))
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Jwt.Key)),

// Cấu hình claim để nhận Role
RoleClaimType = ClaimTypes.Role

};
});

Expand Down Expand Up @@ -173,12 +178,6 @@
app.UseSwaggerUI();
}

using (var scope = app.Services.CreateScope())
{
var minioService = scope.ServiceProvider.GetRequiredService<IMinioService>();
await minioService.EnsureBucketExistsAsync();
}

//kích hoạt CORS policy
app.UseCors(MyAllowSpecificOrigins);

Expand All @@ -192,6 +191,5 @@

app.MapControllers();


await app.RunAsync();
app.Run();

8 changes: 4 additions & 4 deletions FileService/FileService.Api/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
"OtpHoursAvailable": 24
},
"Jwt": {
"Key": "uifhjcnsqbhwbAMKXjdt123gdritocet",
"Issuer": "http://localhost:38946",
"Audience": "http://localhost:38946",
"Key": "1TjXchw5FloESb63Kc+DFhTARvpWL4jUGCwfGWxuG5SIf/1y/LgJxHnMqaF6A/ij",
"Issuer": "Code Campus",
"Audience": "Code Campus",
"AccessTokenExpiresTime": 60,
"RefreshTokenExpiresTime": 3
"RefreshTokenExpiresTime": 300
},
"Admin": {
"OtpMaxAttempted": 3,
Expand Down
6 changes: 3 additions & 3 deletions FileService/FileService.Api/appsettings.Staging.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
"OtpHoursAvailable": 24
},
"Jwt": {
"Key": "uifhjcnsqbhwbAMKXjdt123gdritocet",
"Issuer": "http://localhost:38946",
"Audience": "http://localhost:38946",
"Key": "1TjXchw5FloESb63Kc+DFhTARvpWL4jUGCwfGWxuGSSIf/1y/LgJxHnMqaF6A/ij",
"Issuer": "Code Campus",
"Audience": "Code Campus",
"AccessTokenExpiresTime": 60,
"RefreshTokenExpiresTime": 3
},
Expand Down
51 changes: 43 additions & 8 deletions FileService/FileService.Service/Implementation/MinioService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,60 @@ public class MinioService : BaseService, IMinioService
private readonly IMinioClient _minioClient;
private readonly MinioConfig _config;

public MinioService(AppSettings appSettings, UserContext userContext) : base(appSettings, userContext)
public MinioService(IOptions<MinioConfig> options, AppSettings appSettings, UserContext userContext) : base(appSettings, userContext)
{
_config = appSettings.MinioConfig ?? throw new ArgumentNullException(nameof(appSettings.MinioConfig));
_config = options.Value ?? throw new ArgumentNullException(nameof(options.Value));

_minioClient = new MinioClient()
.WithEndpoint(_config.Endpoint, _config.Port)
.WithCredentials(_config.AccessKey, _config.SecretKey)
.WithSSL(_config.Secure)
.Build();
Console.WriteLine($"MinioConfig: Endpoint={_config.Endpoint}, Port={_config.Port}, AccessKey length={_config.AccessKey?.Length ?? 0}, Secure={_config.Secure}");

if (string.IsNullOrWhiteSpace(_config.Endpoint) || _config.Port <= 0 || string.IsNullOrWhiteSpace(_config.AccessKey) || string.IsNullOrWhiteSpace(_config.SecretKey))
{
throw new InvalidOperationException("Minio configuration is invalid or incomplete.");
}
try
{
Console.WriteLine("Attempting to build MinioClient...");
_minioClient = new MinioClient()
.WithEndpoint(_config.Endpoint, _config.Port)
.WithCredentials(_config.AccessKey, _config.SecretKey)
.WithSSL(_config.Secure)
.Build();
if (_minioClient == null)
{
throw new InvalidOperationException("Failed to initialize MinioClient.");
}
// Kiểm tra kết nối thực tế
Console.WriteLine("Testing MinioClient connection...");
var buckets = _minioClient.ListBucketsAsync().GetAwaiter().GetResult(); // Kiểm tra nhanh
Console.WriteLine("MinioClient initialized and connection tested successfully.");
}
catch (MinioException ex)
{
Console.WriteLine($"MinioException: {ex.Message}");
throw new InvalidOperationException($"Minio initialization failed: {ex.Message}", ex);
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
throw new InvalidOperationException($"Failed to initialize MinioClient: {ex.Message}", ex);
}
}

public async Task EnsureBucketExistsAsync()
{
var bucketExistsArgs = new BucketExistsArgs().WithBucket(_config.BucketName);
if (_minioClient == null)
{
throw new InvalidOperationException("MinioClient is not initialized.");
}

if (string.IsNullOrWhiteSpace(_config.BucketName))
{
throw new InvalidOperationException("Bucket name is not configured.");
}
var bucketExistsArgs = new BucketExistsArgs().WithBucket(_config.BucketName);

bool found = await _minioClient.BucketExistsAsync(bucketExistsArgs);

if (!found)
{
var makeBucketArgs = new MakeBucketArgs().WithBucket(_config.BucketName);
Expand Down