Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 40 additions & 8 deletions API/Controller/Tokens/GetTokenSelf.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
using Microsoft.AspNetCore.Authorization;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenShock.API.Models.Response;
using OpenShock.Common.Authentication;
using OpenShock.Common.Authentication.ControllerBase;
using OpenShock.Common.Authentication.Services;
using OpenShock.Common.OpenShockDb;

namespace OpenShock.API.Controller.Tokens;

[ApiController]
[Tags("API Tokens")]
[Route("/{version:apiVersion}/tokens")]
[Authorize(AuthenticationSchemes = OpenShockAuthSchemes.ApiToken)]
[ApiVersion("1"), ApiVersion("2")]
public sealed partial class TokensSelfController : AuthenticatedSessionControllerBase
{
/// <summary>
Expand All @@ -20,16 +23,35 @@ public sealed partial class TokensSelfController : AuthenticatedSessionControlle
/// <returns></returns>
/// <exception cref="Exception"></exception>
[HttpGet("self")]
[MapToApiVersion("1")]
public TokenResponse GetSelfToken([FromServices] IUserReferenceService userReferenceService)
{
var x = userReferenceService.AuthReference;

if (x is null) throw new Exception("This should not be reachable due to AuthenticatedSession requirement");
if (!x.Value.IsT1) throw new Exception("This should not be reachable due to the [TokenOnly] attribute");

var token = x.Value.AsT1;

var token = GetSelfTokenDto(userReferenceService);

return new TokenResponse
{
CreatedOn = token.CreatedAt,
ValidUntil = token.ValidUntil,
LastUsed = token.LastUsed ?? default,
Permissions = token.Permissions,
Name = token.Name,
Id = token.Id
};
}

/// <summary>
/// Gets information about the current token used to access this endpoint
/// </summary>
/// <param name="userReferenceService"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[HttpGet("self")]
[MapToApiVersion("2")]
public TokenResponseV2 GetSelfTokenV2([FromServices] IUserReferenceService userReferenceService)
{
var token = GetSelfTokenDto(userReferenceService);

return new TokenResponseV2
{
CreatedOn = token.CreatedAt,
ValidUntil = token.ValidUntil,
Expand All @@ -39,4 +61,14 @@ public TokenResponse GetSelfToken([FromServices] IUserReferenceService userRefer
Id = token.Id
};
}

private static ApiToken GetSelfTokenDto(IUserReferenceService userReferenceService)
{
var x = userReferenceService.AuthReference;

if (x is null) throw new Exception("This should not be reachable due to AuthenticatedSession requirement");
if (!x.Value.IsT1) throw new Exception("This should not be reachable due to the [TokenOnly] attribute");

return x.Value.AsT1;
}
}
107 changes: 79 additions & 28 deletions API/Controller/Tokens/Tokens.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Linq.Expressions;
using System.Net.Mime;
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OpenShock.API.Models.Requests;
Expand All @@ -13,25 +15,57 @@ namespace OpenShock.API.Controller.Tokens;

public sealed partial class TokensController
{
private static readonly Expression<Func<ApiToken, TokenResponse>> ToTokenResponse = x => new TokenResponse
{
CreatedOn = x.CreatedAt,
ValidUntil = x.ValidUntil,
LastUsed = x.LastUsed ?? default,
Permissions = x.Permissions,
Name = x.Name,
Id = x.Id
};

private static readonly Expression<Func<ApiToken, TokenResponseV2>> ToTokenResponseV2 = x => new TokenResponseV2
{
CreatedOn = x.CreatedAt,
ValidUntil = x.ValidUntil,
LastUsed = x.LastUsed,
Permissions = x.Permissions,
Name = x.Name,
Id = x.Id
};

/// <summary>
/// Tokens belonging to the current user that have not expired.
/// </summary>
private IQueryable<ApiToken> CurrentUserValidTokens => _db.ApiTokens
.Where(x => x.UserId == CurrentUser.Id && (x.ValidUntil == null || x.ValidUntil > DateTime.UtcNow));

/// <summary>
/// List all tokens for the current user
/// </summary>
/// <response code="200">All tokens for the current user</response>
[HttpGet]
[MapToApiVersion("1")]
public IAsyncEnumerable<TokenResponse> ListTokens()
{
return _db.ApiTokens
.Where(x => x.UserId == CurrentUser.Id && (x.ValidUntil == null || x.ValidUntil > DateTime.UtcNow))
return CurrentUserValidTokens
.OrderBy(x => x.CreatedAt)
.Select(ToTokenResponse)
.AsAsyncEnumerable();
}

/// <summary>
/// List all tokens for the current user
/// </summary>
/// <response code="200">All tokens for the current user</response>
[HttpGet]
[MapToApiVersion("2")]
public IAsyncEnumerable<TokenResponseV2> ListTokensV2()
{
return CurrentUserValidTokens
.OrderBy(x => x.CreatedAt)
.Select(x => new TokenResponse
{
CreatedOn = x.CreatedAt,
ValidUntil = x.ValidUntil,
LastUsed = x.LastUsed,
Permissions = x.Permissions,
Name = x.Name,
Id = x.Id
})
.Select(ToTokenResponseV2)
.AsAsyncEnumerable();
}

Expand All @@ -43,23 +77,39 @@ public IAsyncEnumerable<TokenResponse> ListTokens()
/// <response code="404">The token does not exist or you do not have access to it.</response>
[HttpGet("{tokenId}")]
[ProducesResponseType<TokenResponse>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // ApiTokenNotFound
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // ApiTokenNotFound
[MapToApiVersion("1")]
public async Task<IActionResult> GetTokenById([FromRoute] Guid tokenId)
{
var apiToken = await _db.ApiTokens
.Where(x => x.UserId == CurrentUser.Id && x.Id == tokenId && (x.ValidUntil == null || x.ValidUntil > DateTime.UtcNow))
.Select(x => new TokenResponse
{
CreatedOn = x.CreatedAt,
ValidUntil = x.ValidUntil,
Permissions = x.Permissions,
LastUsed = x.LastUsed,
Name = x.Name,
Id = x.Id
}).FirstOrDefaultAsync();

var apiToken = await CurrentUserValidTokens
.Where(x => x.Id == tokenId)
.Select(ToTokenResponse)
.FirstOrDefaultAsync();

if (apiToken is null) return Problem(ApiTokenError.ApiTokenNotFound);


return Ok(apiToken);
}

/// <summary>
/// Get a token by id
/// </summary>
/// <param name="tokenId"></param>
/// <response code="200">The token</response>
/// <response code="404">The token does not exist or you do not have access to it.</response>
[HttpGet("{tokenId}")]
[ProducesResponseType<TokenResponseV2>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // ApiTokenNotFound
[MapToApiVersion("2")]
public async Task<IActionResult> GetTokenByIdV2([FromRoute] Guid tokenId)
{
var apiToken = await CurrentUserValidTokens
.Where(x => x.Id == tokenId)
.Select(ToTokenResponseV2)
.FirstOrDefaultAsync();

if (apiToken is null) return Problem(ApiTokenError.ApiTokenNotFound);

return Ok(apiToken);
}

Expand All @@ -71,6 +121,7 @@ public async Task<IActionResult> GetTokenById([FromRoute] Guid tokenId)
[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[Produces(MediaTypeNames.Application.Json)]
[MapToApiVersion("1")]
public async Task<TokenCreatedResponse> CreateToken([FromBody] CreateTokenRequest body)
{
var token = CryptoUtils.RandomAlphaNumericString(AuthConstants.ApiTokenLength);
Expand All @@ -95,7 +146,7 @@ public async Task<TokenCreatedResponse> CreateToken([FromBody] CreateTokenReques
Token = token,
CreatedAt = tokenDto.CreatedAt,
ValidUntil = tokenDto.ValidUntil,
LastUsed = tokenDto.LastUsed,
LastUsed = tokenDto.LastUsed ?? default,
Permissions = tokenDto.Permissions
};
}
Expand All @@ -111,10 +162,10 @@ public async Task<TokenCreatedResponse> CreateToken([FromBody] CreateTokenReques
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status404NotFound, MediaTypeNames.Application.ProblemJson)] // ApiTokenNotFound
[MapToApiVersion("1")]
public async Task<IActionResult> EditToken([FromRoute] Guid tokenId, [FromBody] EditTokenRequest body)
{
var token = await _db.ApiTokens
.FirstOrDefaultAsync(x => x.UserId == CurrentUser.Id && x.Id == tokenId && (x.ValidUntil == null || x.ValidUntil > DateTime.UtcNow));
var token = await CurrentUserValidTokens.FirstOrDefaultAsync(x => x.Id == tokenId);
if (token is null) return Problem(ApiTokenError.ApiTokenNotFound);

token.Name = body.Name;
Expand Down
4 changes: 3 additions & 1 deletion API/Controller/Tokens/_ApiController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenShock.Common.Authentication;
using OpenShock.Common.Authentication.ControllerBase;
Expand All @@ -10,6 +11,7 @@ namespace OpenShock.API.Controller.Tokens;
[Tags("API Tokens")]
[Route("/{version:apiVersion}/tokens")]
[Authorize(AuthenticationSchemes = OpenShockAuthSchemes.UserSessionCookie)]
[ApiVersion("1"), ApiVersion("2")]
public sealed partial class TokensController : AuthenticatedSessionControllerBase
{
private readonly OpenShockContext _db;
Expand Down
18 changes: 18 additions & 0 deletions API/Models/Response/TokenResponseV2.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using OpenShock.Common.Models;

namespace OpenShock.API.Models.Response;

public sealed class TokenResponseV2
{
public required Guid Id { get; init; }

public required string Name { get; init; }

public required DateTime CreatedOn { get; init; }

public required DateTime? ValidUntil { get; init; }

public required DateTime? LastUsed { get; init; }

public required List<PermissionType> Permissions { get; init; }
}
Loading
Loading