74 lines
2.8 KiB
C#
74 lines
2.8 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Net;
|
|
using Amazon.IdentityManagement;
|
|
using Amazon.IdentityManagement.Model;
|
|
using Amazon.Runtime;
|
|
using InnovEnergy.Lib.S3Utils.DataTypes;
|
|
using InnovEnergy.Lib.Utils;
|
|
|
|
namespace InnovEnergy.Lib.S3Utils;
|
|
|
|
public static class Iam
|
|
{
|
|
|
|
// TODO
|
|
|
|
|
|
|
|
private static readonly ConcurrentDictionary<S3Region, AmazonIdentityManagementServiceClient> AimClientCache = new();
|
|
|
|
public static AmazonIdentityManagementServiceClient GetIamClient(this S3Url url ) => url.Bucket.GetIamClient();
|
|
public static AmazonIdentityManagementServiceClient GetIamClient(this S3Bucket bucket) => bucket.Region.GetIamClient();
|
|
public static AmazonIdentityManagementServiceClient GetIamClient(this S3Region region)
|
|
{
|
|
return AimClientCache.GetOrAdd(region, CreateIamClient); // Memoize
|
|
}
|
|
|
|
private static AmazonIdentityManagementServiceClient CreateIamClient(S3Region region) => new
|
|
(
|
|
credentials: new BasicAWSCredentials(region.Credentials.Key, region.Credentials.Secret),
|
|
clientConfig: new() { ServiceURL = region.Name.EnsureStartsWith("https://") }
|
|
);
|
|
|
|
public static async Task<User> CreateUserAsync(AmazonIdentityManagementServiceClient iamService,String userName)
|
|
{
|
|
var response = await iamService.CreateUserAsync(new CreateUserRequest { UserName = userName });
|
|
return response.User;
|
|
}
|
|
|
|
public static async Task<Boolean> PutUserPolicyAsync(AmazonIdentityManagementServiceClient iamService, String userName, String policyName, String policyDocument)
|
|
{
|
|
var request = new PutUserPolicyRequest()
|
|
{
|
|
UserName = userName,
|
|
PolicyName = policyName,
|
|
PolicyDocument = policyDocument
|
|
};
|
|
|
|
var response = await iamService.PutUserPolicyAsync(request);
|
|
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
|
|
}
|
|
|
|
public static async Task<AccessKey> CreateAccessKeyAsync(AmazonIdentityManagementServiceClient iamService, String userName)
|
|
{
|
|
var response = await iamService.CreateAccessKeyAsync(new CreateAccessKeyRequest
|
|
{
|
|
UserName = userName,
|
|
});
|
|
|
|
return response.AccessKey;
|
|
|
|
}
|
|
|
|
public static async Task<Boolean> UserExists(AmazonIdentityManagementServiceClient iamService, String userName)
|
|
{
|
|
var response = await iamService.GetUserAsync(new GetUserRequest { UserName = userName });
|
|
return response.HttpStatusCode == HttpStatusCode.OK;
|
|
}
|
|
|
|
public static async Task<Boolean> RevokeAccessKey(AmazonIdentityManagementServiceClient iamService, String userName)
|
|
{
|
|
var response = await iamService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest{ AccessKeyId = userName });
|
|
return response.HttpStatusCode == HttpStatusCode.OK;
|
|
}
|
|
} |