Skip to content

Commit

Permalink
Refactor Azure Bicep scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
tomaszprasolek committed Mar 3, 2024
1 parent 80d3c98 commit 67e473e
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<PackageReference Include="Azure.Identity" Version="1.10.4" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.5.0" />
<PackageReference Include="Azure.Storage.Blobs" Version="12.19.1" />
<PackageReference Include="Flurl" Version="4.0.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.31.2" />
<PackageReference Include="Microsoft.Identity.Web.DownstreamApi" Version="2.16.1" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="2.16.1" />
Expand Down
39 changes: 23 additions & 16 deletions AZ204-DocumentVault/AZ204-DocumentVault/Pages/Upload.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using AZ204_DocumentVault.Services;
using AZ204_DocumentVault.Services.Models;
using Azure.Storage.Blobs.Models;
using Flurl;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
Expand All @@ -13,6 +14,8 @@ public class Upload : PageModel
private readonly ILogger<IndexModel> _logger;
private readonly ICosmosDbService _cosmosDbService;
private readonly IStorageAccountService _storageAccountService;
private readonly HttpClient _httpClient;
private readonly AzureConfig _azureConfig;

public string Message { get; set; } = string.Empty;
public string DocumentName { get; set; } = string.Empty;
Expand All @@ -21,30 +24,21 @@ public class Upload : PageModel
public List<Document> Documents { get; set; } = new();
public string? DocumentDownloadLink { get; set; }

// TODO: check if this is needed. Maybe it is null on every request
private string _userId;
private string UserId => User.GetObjectId()!;

private string UserId
{
get
{
if (string.IsNullOrWhiteSpace(_userId))
_userId = User.GetObjectId()!;

return _userId;
}
}

public Upload(ILogger<IndexModel> logger,
IOptions<AzureConfig> azureConfig,
ICosmosDbService cosmosDbService,
IStorageAccountService storageAccountService
IStorageAccountService storageAccountService,
IHttpClientFactory httpClientFactory
)
{
_logger = logger;
_cosmosDbService = cosmosDbService;
_storageAccountService = storageAccountService;

_httpClient = httpClientFactory.CreateClient("AzureFunctionsClient");
_azureConfig = azureConfig.Value;

}

public async Task<IActionResult> OnGet()
Expand All @@ -62,7 +56,20 @@ public async Task<IActionResult> OnPostDownloadFile(string fileName)

public async Task<IActionResult> OnPostGenerateLink(string id, string fileName, int hoursToBeExpired)
{
DocumentDownloadLink = await _storageAccountService.GenerateDownloadLink(fileName, hoursToBeExpired);
// DocumentDownloadLink = await _storageAccountService.GenerateDownloadLink(fileName, hoursToBeExpired);

string url = _azureConfig.FunctionApp.GenerateDownloadFunctionLink
.SetQueryParam("code", _azureConfig.FunctionApp.GenerateDownloadMethodFunctionKey);

HttpResponseMessage response = await _httpClient.PostAsJsonAsync(url,
new
{
FileName = fileName,
HoursToBeExpired = hoursToBeExpired
});

DownloadLink? link = await response.Content.ReadFromJsonAsync<DownloadLink>();
DocumentDownloadLink = link!.Value;

await _cosmosDbService.UpdateDocument<Document>(id, UserId, fileName, hoursToBeExpired);

Expand Down
6 changes: 6 additions & 0 deletions AZ204-DocumentVault/AZ204-DocumentVault/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@
builder.Services.Configure<AzureConfig>(
builder.Configuration.GetSection(nameof(AzureConfig)));

builder.Services.AddHttpClient("AzureFunctionsClient", client =>
{
client.BaseAddress = new Uri(builder.Configuration.GetValue<string>("AzureConfig:FunctionApp:BaseUrl")!);
client.DefaultRequestHeaders.Clear();
});

// ----------------
// BUILD APP
// ----------------
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
namespace AZ204_DocumentVault.Services.Models;

public class AzureConfig
public sealed class AzureConfig
{
public string StorageAccountName { get; set; } = string.Empty;
public string StorageAccountKey { get; set; } = string.Empty;
public string ContainerName { get; set; } = string.Empty;
public string KeyVaultUri { get; set; } = string.Empty;
public string CosmosDbUri { get; set; } = string.Empty;
public string Test { get; set; } = string.Empty;
public FunctionApp FunctionApp { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Text.Json.Serialization;

namespace AZ204_DocumentVault.Services.Models;

public class DownloadLink
{
[JsonPropertyName("DownloadLink")]
public string Value { get; set; } = string.Empty;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace AZ204_DocumentVault.Services.Models;

public sealed class FunctionApp
{
public string BaseUrl { get; set; }
public string GenerateDownloadFunctionLink { get; set; }

public string GenerateDownloadMethodFunctionKey { get; set; }
}
6 changes: 6 additions & 0 deletions AZ204-DocumentVault/AZ204-DocumentVault/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
"ContainerName": "documents",
"KeyVaultUri": "https://documentskeyvault.vault.azure.net/",
"CosmosDbUri": "https://cosdb-documentvault-ne.documents.azure.com:443/",
"FunctionApp":
{
"BaseUrl": "https://functionapp-app.azurewebsites.net/api",
"GenerateDownloadFunctionLink": "GenerateDownloadLink",
"GenerateDownloadMethodFunctionKey": "todo"
},
"Test": "__TOKEN__"
},
"AzureAd": {
Expand Down
2 changes: 2 additions & 0 deletions AZ204-DocumentVault/Bicep/FunctionApp/functionApp.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,5 @@ resource azFunctionApp 'Microsoft.Web/sites@2021-03-01' = {
}
}
}

output outFunctionAppObjectId string = azFunctionApp.identity.principalId
2 changes: 2 additions & 0 deletions AZ204-DocumentVault/Bicep/FunctionApp/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ module modFunctionApp 'functionApp.bicep' = {
parStorageAccountName: parStorageAccountName
}
}

output outFunctionAppObjectId string = modFunctionApp.outputs.outFunctionAppObjectId
33 changes: 33 additions & 0 deletions AZ204-DocumentVault/Bicep/keyVault-accessPolicies.bicep
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Parameters
param parKeyVaultName string
param parAppServiceObjectId string
param parFunctionAppObjectId string

// Variables
var varTenantId = subscription().tenantId

resource resAccessPolicies 'Microsoft.KeyVault/vaults/accessPolicies@2023-07-01' = {
name: '${parKeyVaultName}/add'
properties: {
accessPolicies: [
{
objectId: parAppServiceObjectId
tenantId: varTenantId
permissions: {
secrets: [
'get'
]
}
}
{
objectId: parFunctionAppObjectId
tenantId: varTenantId
permissions: {
secrets: [
'get'
]
}
}
]
}
}
Empty file.
46 changes: 1 addition & 45 deletions AZ204-DocumentVault/Bicep/keyVault.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ param parLocation string = resourceGroup().location
@description('The Azure user object-id')
param parPrincipalId string

param parAppServiceObjectId string
param parStorageAccountName string
param parCosmosDbName string

// Variables
var varTenantId = subscription().tenantId

Expand All @@ -21,17 +17,6 @@ resource resKeyVault 'Microsoft.KeyVault/vaults@2023-07-01' = {
name: 'standard'
}
tenantId: varTenantId
accessPolicies: [
{
objectId: parAppServiceObjectId
permissions: {
secrets: [
'get'
]
}
tenantId: varTenantId
}
]
}
}

Expand All @@ -47,34 +32,5 @@ resource resRegistryRoleAssignment 'Microsoft.Authorization/roleAssignments@2022
}
}

// -------------------
// Add secrets
// -------------------

// Storage account
resource resStorageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' existing = {
name: parStorageAccountName
}

resource resSecret 'Microsoft.KeyVault/vaults/secrets@2021-11-01-preview' = {
parent: resKeyVault
name: 'StorageAccountKey'
properties: {
value: resStorageAccount.listKeys().keys[0].value
}
}

// Cosmos Db
resource resCosmosDb 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' existing = {
name: parCosmosDbName
}

resource resSecretCosmosDbKey 'Microsoft.KeyVault/vaults/secrets@2021-11-01-preview' = {
parent: resKeyVault
name: 'CosmosDbKey'
properties: {
value: resCosmosDb.listKeys().primaryMasterKey
}
}

output keyVaultName string = resKeyVault.name
output keyVaultUri string = resKeyVault.properties.vaultUri
23 changes: 20 additions & 3 deletions AZ204-DocumentVault/Bicep/main.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ module modKeyVault 'keyVault.bicep' = {
params: {
parLocation: parLocation
parPrincipalId: parPrincipalId
parAppServiceObjectId: modAppService.outputs.outAppServiceObjectId
parStorageAccountName: modStorageAccount.outputs.storageAccountName
parCosmosDbName: modCosmosDb.outputs.cosmosDbName
}
}

Expand All @@ -50,3 +47,23 @@ module modFunctionApp 'FunctionApp/main.bicep' = {
parStorageAccountName: modStorageAccount.outputs.storageAccountName
}
}

// Key vault - add access policies
module modAccessPolicies 'keyVault-accessPolicies.bicep' = {
name: 'accessPolicies'
params: {
parAppServiceObjectId: modAppService.outputs.outAppServiceObjectId
parFunctionAppObjectId: modFunctionApp.outputs.outFunctionAppObjectId
parKeyVaultName: modKeyVault.outputs.keyVaultName
}
}

// Key vault - add secrets
module modSecrets 'keyVault-secrets.bicep' = {
name: 'modSecrets'
params: {
parCosmosDbName: modCosmosDb.outputs.cosmosDbName
parKeyVaultName: modKeyVault.outputs.keyVaultName
parStorageAccountName: modStorageAccount.outputs.storageAccountName
}
}

0 comments on commit 67e473e

Please sign in to comment.