Skip to content

Commit

Permalink
Simple graph integration to get user data + minor cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Torkelsen committed Oct 1, 2024
1 parent eba0049 commit bab2603
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class ItemController : ControllerBase
{
private readonly ILogger<ItemController> _logger;
private readonly IConfiguration _config;
private readonly CosmosDBService _cosmosDBService;
private readonly CosmosDBService _cosmosDBService;

public ItemController(ILogger<ItemController> logger, IConfiguration config)
{
Expand Down Expand Up @@ -48,9 +48,9 @@ public async Task<ActionResult<List<Item>>> Get()
{
try
{
var sqlQuery = "SELECT * FROM c"; //ORDER BY c.created ? feiler dersom ingen items
var result = await _cosmosDBService.GetByQuery(sqlQuery);
return Ok(result);
var sqlQuery = "SELECT * FROM c"; //ORDER BY c.created ? feiler dersom ingen items
var result = await _cosmosDBService.GetByQuery(sqlQuery);
return Ok(result);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -84,8 +84,8 @@ public async Task<IActionResult> Add(ItemPostDTO item)
{
try
{
var result = await _cosmosDBService.Add(item, GetUsername());
return Ok(result);
var result = await _cosmosDBService.Add(item, GetUsername());
return Ok(result);
}
catch (Exception ex)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using HandlenettAPI.Models;
using Azure.Identity;
using HandlenettAPI.Models;
using HandlenettAPI.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;

namespace HandlenettAPI.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
Expand All @@ -23,33 +26,18 @@ public UserController(ILogger<ItemController> logger, GraphServiceClient graphSe
[HttpGet(Name = "GetUsers")]
public async Task<List<Models.User>> Get()
{
//Get all users, må bare endre til dto
var dbService = new UserService(_config);

//not ready, msal auth issue in graph api
await dbService.AddUserIfNotExists(_graphClient);

return dbService.GetUsers();

try
{
var dbService = new UserService(_config);
await dbService.AddUserIfNotExists(_graphClient);

return dbService.GetUsers(); //endre til dto
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to get users");
throw new Exception("Failed to get users");
}
}


//[HttpGet(Name = "GetUser")]
//public async Task<Microsoft.Graph.User> Get()
//{
// return await _graphServiceClient.Me.Request().GetAsync(); ;
//}

//[HttpGet("Login")]
//public async Task<bool> Login()
//{
// return true;
//}

//[HttpGet("Logout")]
//public async Task<bool> Logout()
//{
// return true;
//}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@
{
public static class AzureSQLSetup
{

private static bool IsRunningInAzure()
{
return Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID") != null;
}


}
}
26 changes: 9 additions & 17 deletions handlenett-backend/web-api/HandlenettAPI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,17 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Azure;
using Microsoft.Graph;
using Microsoft.Graph.ExternalConnectors;
using Microsoft.Identity.Web;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);
var builder = Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(args);

// Swagger configuration
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Handlenett API", Version = "v1" });

// Add JWT Authentication
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Expand All @@ -24,7 +23,6 @@
In = ParameterLocation.Header,
Description = "Enter 'Bearer' [space] and then your token in the text input below.\n\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI...\"",
});

c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
Expand All @@ -44,23 +42,23 @@
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi() // new[] { "https://graph.microsoft.com/.default" }
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();

//TODO: add AzureSQLContext singleton
//builder.Services.AddSingleton(graphClient);

builder.Configuration.AddAzureKeyVault(
new Uri($"https://{builder.Configuration["AzureKeyVaultNameProd"]}.vault.azure.net/"),
new DefaultAzureCredential());
//DefaultAzureCredential() is handled by enabling system assigned identity on container app and creating access policy in kv

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();




//TODO: Fiks dev miljø for key vault
//if (builder.Environment.IsProduction())
//{
// builder.Configuration.AddAzureKeyVault(
Expand All @@ -76,12 +74,9 @@

var app = builder.Build();


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
//app.UseSwaggerUI();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API v1");
Expand All @@ -91,11 +86,8 @@
}

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

ConfigurationHelper.Initialize(app.Configuration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
}
else
{
connectionString = _config.GetConnectionString("AzureSQLDB_Local");
connectionString = _config.GetConnectionString("AzureSQLDBForLocalTesting");

var azureCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace HandlenettAPI.Services
public class CosmosDBService//<T> where T : IBase //Lag generisk, støtte for andre enn Item struktur, basert på containerName?
{
private readonly Container _container;

public CosmosDBService(CosmosClient client, string databaseName, string containerName)
{
_container = client.GetContainer(databaseName, containerName);
Expand Down Expand Up @@ -77,4 +78,4 @@ public async Task<Item> Update (string id, ItemPutDTO item, string username)
return updatedItem;
}
}
}
}
50 changes: 46 additions & 4 deletions handlenett-backend/web-api/HandlenettAPI/Services/UserService.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using HandlenettAPI.Models;
using Microsoft.Data.SqlClient;
using Microsoft.Data.SqlClient;
using Microsoft.Graph;

namespace HandlenettAPI.Services
Expand All @@ -8,7 +7,7 @@ namespace HandlenettAPI.Services
public class UserService
{
private IConfiguration _config;
public UserService(IConfiguration config)
public UserService(IConfiguration config)
{
_config = config;
}
Expand Down Expand Up @@ -37,9 +36,52 @@ public UserService(IConfiguration config)

public async Task<Models.User> AddUserIfNotExists(GraphServiceClient graphServiceClient)
{
await graphServiceClient.Me.Request().GetAsync();
var myUser = await graphServiceClient.Me.Request().GetAsync();

if (myUser == null)
{
throw new Exception("Could not get Ad profile");
}

if (!CheckIfUserExists(new Guid(myUser.Id)))
{
AddUser(myUser);
}

return new Models.User();
}


private bool CheckIfUserExists(Guid userId)
{
using (var db = new AzureSQLContext(_config))
{
var users = db.Users
.Where(u => u.Id == userId)
.FirstOrDefault();

if (users != null)
{
return true;
}
return false;
}
}

private bool AddUser(Microsoft.Graph.User user)
{
using (var db = new AzureSQLContext(_config))
{
var newUser = new Models.User
{
Id = new Guid(user.Id),
FirstName = user.GivenName,
LastName = user.Surname
};
db.Users.Add(newUser);
db.SaveChanges();
return true;
}
}
}
}

0 comments on commit bab2603

Please sign in to comment.