Skip to content

Commit

Permalink
feat: validators for tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
kirinnee committed Oct 25, 2023
1 parent a405c24 commit f55540a
Show file tree
Hide file tree
Showing 16 changed files with 63 additions and 16 deletions.
2 changes: 1 addition & 1 deletion App/Modules/Cyan/API/V1/Mappers/PluginMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static PluginSearch ToDomain(this SearchPluginQuery query) =>
public static PluginPrincipalResp ToResp(this PluginPrincipal principal) =>
new(principal.Id, principal.Record.Name, principal.Metadata.Project,
principal.Metadata.Source, principal.Metadata.Email, principal.Metadata.Tags,
principal.Metadata.Description, principal.Metadata.Readme);
principal.Metadata.Description, principal.Metadata.Readme, principal.UserId);

public static PluginResp ToResp(this Plugin plugin) =>
new(plugin.Principal.ToResp(), plugin.Info.ToResp(), plugin.User.ToResp(),
Expand Down
2 changes: 1 addition & 1 deletion App/Modules/Cyan/API/V1/Mappers/ProcessorMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static ProcessorSearch ToDomain(this SearchProcessorQuery query) =>
public static ProcessorPrincipalResp ToResp(this ProcessorPrincipal principal) =>
new(principal.Id, principal.Record.Name, principal.Metadata.Project,
principal.Metadata.Source, principal.Metadata.Email, principal.Metadata.Tags,
principal.Metadata.Description, principal.Metadata.Readme);
principal.Metadata.Description, principal.Metadata.Readme, principal.UserId);

public static ProcessorResp ToResp(this Processor processor) =>
new(processor.Principal.ToResp(), processor.Info.ToResp(), processor.User.ToResp(),
Expand Down
2 changes: 1 addition & 1 deletion App/Modules/Cyan/API/V1/Mappers/TemplateMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static TemplateSearch ToDomain(this SearchTemplateQuery query) =>
public static TemplatePrincipalResp ToResp(this TemplatePrincipal principal) =>
new(principal.Id, principal.Record.Name, principal.Metadata.Project,
principal.Metadata.Source, principal.Metadata.Email, principal.Metadata.Tags,
principal.Metadata.Description, principal.Metadata.Readme);
principal.Metadata.Description, principal.Metadata.Readme, principal.UserId);

public static TemplateResp ToResp(this Template template) =>
new(template.Principal.ToResp(), template.Info.ToResp(), template.User.ToResp(),
Expand Down
2 changes: 1 addition & 1 deletion App/Modules/Cyan/API/V1/Models/PluginModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public record UpdatePluginReq(string Project, string Source,

public record PluginPrincipalResp(
Guid Id, string Name, string Project, string Source,
string Email, string[] Tags, string Description, string Readme);
string Email, string[] Tags, string Description, string Readme, string UserId);

public record PluginInfoResp(
uint Downloads, uint Dependencies, uint Stars);
Expand Down
2 changes: 1 addition & 1 deletion App/Modules/Cyan/API/V1/Models/ProcessorModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public record UpdateProcessorReq(string Project, string Source,

public record ProcessorPrincipalResp(
Guid Id, string Name, string Project, string Source,
string Email, string[] Tags, string Description, string Readme);
string Email, string[] Tags, string Description, string Readme, string UserId);

public record ProcessorInfoResp(
uint Downloads, uint Dependencies, uint Stars);
Expand Down
2 changes: 1 addition & 1 deletion App/Modules/Cyan/API/V1/Models/TemplateModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public record UpdateTemplateReq(string Project, string Source,

public record TemplatePrincipalResp(
Guid Id, string Name, string Project, string Source,
string Email, string[] Tags, string Description, string Readme);
string Email, string[] Tags, string Description, string Readme, string UserId);

public record TemplateInfoResp(
uint Downloads, uint Stars);
Expand Down
2 changes: 1 addition & 1 deletion App/Modules/Cyan/Data/Mappers/PluginMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static PluginRecord ToRecord(this PluginData data) =>
new() { Name = data.Name };

public static PluginPrincipal ToPrincipal(this PluginData data) =>
new() { Id = data.Id, Metadata = data.ToMetadata(), Record = data.ToRecord(), };
new() { Id = data.Id, Metadata = data.ToMetadata(), Record = data.ToRecord(), UserId = data.UserId };

public static Plugin ToDomain(this PluginData data, PluginInfo info) =>
new()
Expand Down
8 changes: 7 additions & 1 deletion App/Modules/Cyan/Data/Mappers/ProcessorMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,13 @@ public static ProcessorRecord ToRecord(this ProcessorData data) =>
new() { Name = data.Name };

public static ProcessorPrincipal ToPrincipal(this ProcessorData data) =>
new() { Id = data.Id, Metadata = data.ToMetadata(), Record = data.ToRecord(), };
new()
{
Id = data.Id,
Metadata = data.ToMetadata(),
Record = data.ToRecord(),
UserId = data.UserId,
};

public static Processor ToDomain(this ProcessorData data, ProcessorInfo info) =>
new()
Expand Down
1 change: 1 addition & 0 deletions App/Modules/Cyan/Data/Mappers/TemplateMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public static TemplatePrincipal ToPrincipal(this TemplateData data) =>
Id = data.Id,
Metadata = data.ToMetadata(),
Record = data.ToRecord(),
UserId = data.UserId,
};

public static Template ToDomain(this TemplateData data, TemplateInfo info) =>
Expand Down
25 changes: 19 additions & 6 deletions App/Modules/Users/API/V1/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,29 @@ public class UserController : AtomiControllerBase
{
private readonly IUserService _service;
private readonly ITokenService _token;
private readonly ILogger<UserController> _logger;

private readonly CreateUserReqValidator _createUserReqValidator;
private readonly UpdateUserReqValidator _updateUserReqValidator;
private readonly UserSearchQueryValidator _userSearchQueryValidator;

private readonly CreateTokenReqValidator _createTokenReqValidator;
private readonly UpdateTokenReqValidator _updateTokenReqValidator;


public UserController(IUserService service,
CreateUserReqValidator createUserReqValidator, UpdateUserReqValidator updateUserReqValidator,
UserSearchQueryValidator userSearchQueryValidator, ITokenService token)
UserSearchQueryValidator userSearchQueryValidator, ITokenService token, ILogger<UserController> logger,
CreateTokenReqValidator createTokenReqValidator, UpdateTokenReqValidator updateTokenReqValidator)
{
this._service = service;
this._createUserReqValidator = createUserReqValidator;
this._updateUserReqValidator = updateUserReqValidator;
this._userSearchQueryValidator = userSearchQueryValidator;
this._token = token;
this._logger = logger;
this._createTokenReqValidator = createTokenReqValidator;
this._updateTokenReqValidator = updateTokenReqValidator;
}

[Authorize(Policy = AuthPolicies.OnlyAdmin), HttpGet]
Expand All @@ -64,6 +72,7 @@ public async Task<ActionResult<UserResp>> GetById(string id)
.Then(x => (x?.ToResp()).ToResult())
.Then(x =>
{
this._logger.LogInformation("Accessor: {Accessor}, Accessee: {Accessee}", this.Sub(), x?.Principal?.Id);
if (x?.Principal?.Id == this.Sub()) return x.ToResult();
return new Unauthorized("You are not authorized to access this resource")
.ToException();
Expand All @@ -89,9 +98,10 @@ public async Task<ActionResult<UserResp>> GetByUsername(string username)
}

[Authorize, HttpGet("exist/{username}")]
public async Task<ActionResult<bool>> Exist(string username)
public async Task<ActionResult<UserExistResp>> Exist(string username)
{
var exist = await this._service.Exists(username);
var exist = await this._service.Exists(username)
.Then(x => new UserExistResp(x), Errors.MapAll);
return this.ReturnResult(exist);
}

Expand Down Expand Up @@ -164,14 +174,15 @@ public async Task<ActionResult<TokenOTPrincipalResp>> CreateToken(string userId,
return this.ReturnResult(x);
}

var token = await this._token.Create(sub, req.ToRecord())
var token = await this._createTokenReqValidator.ValidateAsyncResult(req, "Invalid CreateTokenReq")
.ThenAwait(r => this._token.Create(sub, r.ToRecord()))
.Then(x => x.ToOTResp(), Errors.MapAll);
return this.ReturnResult(token);
}

[Authorize, HttpPut("{userId}/tokens/{tokenId:guid}")]
public async Task<ActionResult<TokenPrincipalResp>> UpdateToken(string userId, Guid tokenId,
[FromBody] CreateTokenReq req)
[FromBody] UpdateTokenReq req)
{
var sub = this.Sub();
if (sub == null || sub != userId)
Expand All @@ -180,8 +191,10 @@ public async Task<ActionResult<TokenPrincipalResp>> UpdateToken(string userId, G
return this.ReturnResult(x);
}

var token = await this._token.Update(sub, tokenId, req.ToRecord())
var token = await this._updateTokenReqValidator.ValidateAsyncResult(req, "Invalid UpdateTokenReq")
.ThenAwait(r => this._token.Update(sub, tokenId, r.ToRecord()))
.Then(x => x?.ToResp(), Errors.MapAll);

return this.ReturnNullableResult(token,
new EntityNotFound("Cannot update entity that does not exist", typeof(TokenPrincipal), tokenId.ToString())
);
Expand Down
2 changes: 2 additions & 0 deletions App/Modules/Users/API/V1/UserModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ public record UpdateUserReq(string Username);

public record SearchUserQuery(string? Id, string? Username, int? Limit, int? Skip);

public record UserExistResp(bool Exists);

public record UserPrincipalResp(string Id, string Username);

public record UserResp(UserPrincipalResp Principal, IEnumerable<TokenPrincipalResp> Tokens);
22 changes: 22 additions & 0 deletions App/Modules/Users/API/V1/Validators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,25 @@ public UserSearchQueryValidator()
.Skip();
}
}

public class CreateTokenReqValidator : AbstractValidator<CreateTokenReq>
{
public CreateTokenReqValidator()
{
this.RuleFor(x => x.Name)
.NotNull()
.NotEmpty()
.NameValid();
}
}

public class UpdateTokenReqValidator : AbstractValidator<UpdateTokenReq>
{
public UpdateTokenReqValidator()
{
this.RuleFor(x => x.Name)
.NotNull()
.NotEmpty()
.NameValid();
}
}
2 changes: 1 addition & 1 deletion App/Utility/ValidationUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static IRuleBuilderOptions<T, string> UsernameValid<T>(
return ruleBuilder
.Length(1, 256)
.WithMessage("Username has to be between 1 to 256 characters")
.Matches(@"[\w](\-?[\w\d]+)*")
.Matches(@"^[a-z](\-?[a-z0-9]+)*$")
.WithMessage("Username can only contain alphanumeric characters and dashes, and cannot end or start with dashes or numbers");
}

Expand Down
2 changes: 2 additions & 0 deletions Domain/Model/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ public record PluginPrincipal
{
public required Guid Id { get; init; }

public required string UserId { get; init; }

// User Controlled, updatable, metadata
public required PluginMetadata Metadata { get; init; }

Expand Down
1 change: 1 addition & 0 deletions Domain/Model/Processor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public record ProcessorPrincipal
{
public required Guid Id { get; init; }

public required string UserId { get; init; }
// User Controlled, updatable, metadata
public required ProcessorMetadata Metadata { get; init; }

Expand Down
2 changes: 1 addition & 1 deletion Domain/Model/Template.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public record TemplatePrincipal
{
public required Guid Id { get; init; }


public required string UserId { get; init; }
// User Controlled, updatable, metadata
public required TemplateMetadata Metadata { get; init; }

Expand Down

0 comments on commit f55540a

Please sign in to comment.