Created
May 14, 2020 04:23
-
-
Save JeremyLikness/fcb62c9e6b55f3ead624e354998f003a to your computer and use it in GitHub Desktop.
Cosmos token controllerr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Threading.Tasks; | |
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration; | |
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Azure.Cosmos; | |
using BlazorCosmosWasm.Shared; | |
using Microsoft.AspNetCore.Identity; | |
using BlazorCosmosWasm.Server.Models; | |
namespace BlazorCosmosWasm.Server.Controllers | |
{ | |
[Authorize] | |
[Route("api/[controller]")] | |
[ApiController] | |
public class CosmosController : ControllerBase | |
{ | |
private readonly UserManager<ApplicationUser> Manager; | |
public CosmosController(IConfiguration config, UserManager<ApplicationUser> manager) | |
{ | |
Config = config; | |
Manager = manager; | |
Client = config.CreateCosmosClientFromConfig(); | |
} | |
private CosmosClient Client { get; } | |
public IConfiguration Config { get; set; } | |
[HttpGet] | |
public async Task<IActionResult> Get() | |
{ | |
var user = await User.GetEmailAsync(Manager); | |
if (user == null) | |
{ | |
return NotFound(); | |
} | |
var db = Client.GetDatabase(BlogContext.DatabaseName); | |
var container = db.GetContainer(nameof(BlogContext)); | |
var cosmosUser = db.GetUser(user); | |
var permissionId = $"Permission-{user}-blogs"; | |
await cosmosUser.UpsertPermissionAsync(new PermissionProperties( | |
id: permissionId, | |
permissionMode: PermissionMode.Read, | |
container: container)); | |
var token = await cosmosUser.GetPermission(permissionId).ReadAsync(); | |
return Ok( | |
new CosmosCredentials | |
{ | |
EndPoint = Client.Endpoint.ToString(), | |
Key = token.Resource.Token | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment