Skip to content

Commit

Permalink
check allowing to publish workload packages
Browse files Browse the repository at this point in the history
  • Loading branch information
0xF6 committed Aug 3, 2024
1 parent 4cba866 commit 5d5dbfd
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 32 deletions.
20 changes: 20 additions & 0 deletions src/logic/entities/ApiKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@ public class ApiKey
[FirestoreProperty, JsonProperty("name")]
public string Name { get; set; }
}


[FirestoreData]
public class UserDetails
{
[FirestoreDocumentId, JsonProperty("uid")]
public string UID { get; set; }

[FirestoreProperty("owner"), JsonProperty]
public string UserOwner { get; set; }

[FirestoreDocumentCreateTimestamp, JsonProperty("creationDate")]
public DateTimeOffset CreationDate { get; set; }

[FirestoreProperty, JsonProperty("isAllowedPublishWorkloads")]
public bool IsAllowedPublishWorkloads { get; set; }

[FirestoreProperty, JsonProperty("isAllowedPublishServicePackage")]
public bool IsAllowedPublishServicePackage { get; set; }
}


public class TimeSpanConverter : IFirestoreConverter<TimeSpan>
Expand Down
7 changes: 6 additions & 1 deletion src/logic/services/PackageIndexingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ public class PackageIndexingService(
ISearchIndexer search,
SystemTime time,
IOptionsSnapshot<RegistryOptions> options,
ILogger<PackageIndexingService> logger,
ILogger<PackageIndexingService> logger,
IUserService userService,
IMapper mapper)
: IPackageIndexingService
{
Expand All @@ -32,6 +33,10 @@ public class PackageIndexingService(
{
var packageReader = await Shard.OpenAsync(packageStream, true, token);
var manifest = await packageReader.GetManifestAsync(token);

if (manifest.IsWorkload && !await userService.UserAllowedPublishWorkloads())
return (PackageIndexingResult.InvalidPackage, "You cannot publish workload package!");

package = mapper.Map<Package>(manifest);
package.Published = _time.UtcNow;
package.Listed = true;
Expand Down
69 changes: 38 additions & 31 deletions src/logic/services/firebase/FirebaseUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,16 @@ namespace core.services;
using Google.Cloud.Firestore;
using searchs;

public class FirebaseUserService : IUserService, ILoggerAccessor
public class FirebaseUserService(
IHttpContextAccessor ctx,
IPackageService packageService,
FirestoreDb operationBuilder,
ILogger<FirebaseUserService> logger,
IConfiguration config)
: IUserService, ILoggerAccessor
{
private readonly IHttpContextAccessor _ctx;
private readonly IPackageService _packageService;
private readonly FirestoreDb _operationBuilder;
private readonly ILogger<FirebaseUserService> _logger;
private readonly IConfiguration _config;

public FirebaseUserService(
IHttpContextAccessor ctx,
IPackageService packageService,
FirestoreDb operationBuilder,
ILogger<FirebaseUserService> logger,
IConfiguration config)
{
_ctx = ctx;
_packageService = packageService;
_operationBuilder = operationBuilder;
_logger = logger;
_config = config;
}
private readonly IConfiguration _config = config;

[Interceptor("Failed generate api key by '{0}' name. [eol: {1}]")]
public async ValueTask<ApiKey> GenerateApiKeyAsync(string name, TimeSpan endOfLife)
{
Expand All @@ -42,7 +31,7 @@ public async ValueTask<ApiKey> GenerateApiKeyAsync(string name, TimeSpan endOfLi
apiKey.UserOwner = me.Uid;
apiKey.UID = $"{Guid.NewGuid()}";

await _operationBuilder.Collection("apiKeys")
await operationBuilder.Collection("apiKeys")
.Document($"{apiKey.UID}")
.CreateAsync(apiKey);

Expand All @@ -54,42 +43,58 @@ public async Task<IReadOnlyCollection<ApiKey>> GetApiKeysAsync()
{
var me = await GetMeAsync();

var list = await _operationBuilder.Collection("apiKeys")
var list = await operationBuilder.Collection("apiKeys")
.ListDocumentsAsync()
.SelectAwait(async x => await x.GetSnapshotAsync())
.Where(x => x.GetValue<string>("owner").Equals(me.Uid))
.ToListAsync();

return list.Select(x => x.ConvertTo<ApiKey>()).ToList().AsReadOnly();
}

[Interceptor("Failed get access details for user")]
public async Task<bool> UserAllowedPublishWorkloads()
{
var me = await GetMeAsync();

var user = await operationBuilder.Collection("users")
.Document(me.Uid)
.GetSnapshotAsync();

if (user.Exists)
return false;
var userData = user.ConvertTo<UserDetails>();

return userData.IsAllowedPublishWorkloads;
}

[Interceptor("Failed remove api key.")]
public async Task DeleteApiKeyAsync(string uid)
{
var me = await GetMeAsync();

await _operationBuilder.Collection("apiKeys")
await operationBuilder.Collection("apiKeys")
.Document(uid)
.DeleteAsync();
}

[Interceptor("Failed get current user.")]
public async ValueTask<UserRecord?> GetMeAsync(CancellationToken token = default)
{
var subKey = _ctx.HttpContext!.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
var apiKey = (string)_ctx.HttpContext.Request.Headers["X-VEIN-API-KEY"];
var subKey = ctx.HttpContext!.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
var apiKey = (string)ctx.HttpContext.Request.Headers["X-VEIN-API-KEY"];

if (apiKey is not null)
{
var keyData = await _operationBuilder.Collection("apiKeys")
var keyData = await operationBuilder.Collection("apiKeys")
.ListDocumentsAsync()
.FirstOrDefaultAsync(x => x.Id.Equals(apiKey));
.FirstOrDefaultAsync(x => x.Id.Equals(apiKey), cancellationToken: token);

if (keyData is null)
return null;
var val = (await keyData.GetSnapshotAsync()).ConvertTo<ApiKey>();
var val = (await keyData.GetSnapshotAsync(token)).ConvertTo<ApiKey>();

return await FirebaseAuth.DefaultInstance.GetUserAsync(val.UserOwner);
return await FirebaseAuth.DefaultInstance.GetUserAsync(val.UserOwner, token);
}

if (subKey is null)
Expand Down Expand Up @@ -139,12 +144,12 @@ public async ValueTask<IReadOnlyCollection<Package>> GetPackagesAsync(Cancellati
{
var me = await GetMeAsync(cancellationToken);

return await _packageService.FindForUserAsync(me.Uid, cancellationToken);
return await packageService.FindForUserAsync(me.Uid, cancellationToken);
}

[Interceptor("Failed index package.")]
public ValueTask IndexPackageAsync(Package package) => throw new NotImplementedException();
ILogger ILoggerAccessor.GetLogger() => _logger;
ILogger ILoggerAccessor.GetLogger() => logger;
}


Expand All @@ -161,4 +166,6 @@ public interface IUserService
public ValueTask<IReadOnlyCollection<Package>> GetPackagesAsync(CancellationToken cancellationToken = default);

public ValueTask IndexPackageAsync(Package package);

public Task<bool> UserAllowedPublishWorkloads();
}

0 comments on commit 5d5dbfd

Please sign in to comment.