Doxy, -Wall -Werror, other cleanup and organization first round

This commit is contained in:
2023-08-19 20:46:31 -04:00
parent 1fedd4d016
commit 49de8aa8d7
43 changed files with 728 additions and 354 deletions

View File

@ -1,9 +1,9 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace IO.Swagger.Attributes namespace IO.Swagger.Attributes
{ {
@ -19,8 +19,7 @@ namespace IO.Swagger.Attributes
public override void OnActionExecuting(ActionExecutingContext context) public override void OnActionExecuting(ActionExecutingContext context)
{ {
// Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/ // Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
var descriptor = context.ActionDescriptor as ControllerActionDescriptor; if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
if (descriptor != null)
{ {
foreach (var parameter in descriptor.MethodInfo.GetParameters()) foreach (var parameter in descriptor.MethodInfo.GetParameters())
{ {
@ -40,14 +39,13 @@ namespace IO.Swagger.Attributes
} }
} }
private void ValidateAttributes(ParameterInfo parameter, object args, ModelStateDictionary modelState) private static void ValidateAttributes(ParameterInfo parameter, object args, ModelStateDictionary modelState)
{ {
foreach (var attributeData in parameter.CustomAttributes) foreach (var attributeData in parameter.CustomAttributes)
{ {
var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType); var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType);
var validationAttribute = attributeInstance as ValidationAttribute; if (attributeInstance is ValidationAttribute validationAttribute)
if (validationAttribute != null)
{ {
var isValid = validationAttribute.IsValid(args); var isValid = validationAttribute.IsValid(args);
if (!isValid) if (!isValid)

View File

@ -7,24 +7,21 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System; using AutoMapper;
using System.Collections.Generic; using IO.Swagger.Attributes;
using IO.Swagger.Models.RequestDto;
using IO.Swagger.Models.ResponseDto;
using IO.Swagger.Repositories;
using IO.Swagger.Security;
using IO.Swagger.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations; using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen; using System;
using Newtonsoft.Json; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes;
using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization;
using IO.Swagger.Models.dto;
using IO.Swagger.Repositories;
using System.Threading.Tasks;
using System.Linq; using System.Linq;
using IO.Swagger.Services;
using System.Security.Claims; using System.Security.Claims;
using AutoMapper; using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
@ -85,12 +82,12 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("LoginUser")] [SwaggerOperation("LoginUser")]
[ProducesResponseType(typeof(TokenDto), 200)] [ProducesResponseType(typeof(TokenDto), 200)]
[ProducesResponseType(typeof(IEnumerable<string>), 400)] [ProducesResponseType(typeof(IEnumerable<string>), 400)]
public virtual async Task<IActionResult> LoginUser([FromBody]AuthLoginBody body) public virtual async Task<IActionResult> LoginUser([FromBody] AuthLoginBody body)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage))); return BadRequest(ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage)));
var user = await repository.LoginUser(body); var user = await repository.LoginUser(body);
return user == null ? Unauthorized() : Ok(new TokenDto{ Token = jwt.GenerateJwt(user.Id) }); return user == null ? Unauthorized() : Ok(new TokenDto { Token = jwt.GenerateJwt(user.Id) });
} }
/// <summary> /// <summary>
@ -107,13 +104,13 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("RegisterUser")] [SwaggerOperation("RegisterUser")]
[ProducesResponseType(typeof(TokenDto), 200)] [ProducesResponseType(typeof(TokenDto), 200)]
[ProducesResponseType(typeof(IEnumerable<string>), 400)] [ProducesResponseType(typeof(IEnumerable<string>), 400)]
public async Task<IActionResult> RegisterUser([FromBody]AuthRegisterBody body) public async Task<IActionResult> RegisterUser([FromBody] AuthRegisterBody body)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage))); return BadRequest(ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage)));
var user = await repository.RegisterUser(body); var user = await repository.RegisterUser(body);
return user == null ? StatusCode(409) : Ok(new TokenDto{ Token = jwt.GenerateJwt(user.Id) }); return user == null ? StatusCode(409) : Ok(new TokenDto { Token = jwt.GenerateJwt(user.Id) });
} }
} }
} }

View File

@ -7,34 +7,43 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System; using AutoMapper;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes; using IO.Swagger.Attributes;
using IO.Swagger.Models.RequestDto;
using IO.Swagger.Models.ResponseDto;
using IO.Swagger.Repositories;
using IO.Swagger.Security; using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using IO.Swagger.Models.dto; using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using IO.Swagger.Repositories;
using AutoMapper;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
/// <summary> /// <summary>
/// ///
/// </summary> /// </summary>
/// <seealso cref="Microsoft.AspNetCore.Mvc.ControllerBase" />
[ApiController] [ApiController]
public class CurrencyApiController : ControllerBase public class CurrencyApiController : ControllerBase
{ {
private readonly ICurrencyRepository repo; private readonly ICurrencyRepository repo;
private readonly IMapper mapper; private readonly IMapper mapper;
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyApiController"/> class.
/// </summary>
/// <param name="repo">The repo.</param>
/// <param name="mapper">The mapper.</param>
/// <exception cref="System.ArgumentNullException">
/// repo
/// or
/// mapper
/// </exception>
public CurrencyApiController(ICurrencyRepository repo, IMapper mapper) public CurrencyApiController(ICurrencyRepository repo, IMapper mapper)
{ {
this.repo = repo ?? throw new ArgumentNullException(nameof(repo)); this.repo = repo ?? throw new ArgumentNullException(nameof(repo));
@ -53,7 +62,7 @@ namespace IO.Swagger.Controllers
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("AddDigitalAssetToCollection")] [SwaggerOperation("AddDigitalAssetToCollection")]
public virtual IActionResult AddDigitalAssetToCollection([FromBody]CurrencyAddAssetBody body) public virtual IActionResult AddDigitalAssetToCollection([FromBody] CurrencyAddAssetBody body)
{ {
//TODO: Uncomment the next line to return response 201 or use other options such as return this.NotFound(), return this.BadRequest(..), ... //TODO: Uncomment the next line to return response 201 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(201); // return StatusCode(201);
@ -79,7 +88,7 @@ namespace IO.Swagger.Controllers
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("CreateAssetCollection")] [SwaggerOperation("CreateAssetCollection")]
public virtual IActionResult CreateAssetCollection([FromBody]CurrencyCreateCollectionBody body) public virtual IActionResult CreateAssetCollection([FromBody] CurrencyCreateCollectionBody body)
{ {
//TODO: Uncomment the next line to return response 201 or use other options such as return this.NotFound(), return this.BadRequest(..), ... //TODO: Uncomment the next line to return response 201 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(201); // return StatusCode(201);
@ -96,7 +105,7 @@ namespace IO.Swagger.Controllers
/// <summary> /// <summary>
/// Create a new currency type /// Create a new currency type
/// </summary> /// </summary>
/// <param name="body"></param> /// <param name="body">The currency to create</param>
/// <response code="201">Currency type created successfully</response> /// <response code="201">Currency type created successfully</response>
/// <response code="400">Bad Request</response> /// <response code="400">Bad Request</response>
/// <response code="401">Unauthorized</response> /// <response code="401">Unauthorized</response>
@ -107,7 +116,7 @@ namespace IO.Swagger.Controllers
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("CreateCurrency")] [SwaggerOperation("CreateCurrency")]
[ProducesResponseType(typeof(IEnumerable<string>), 400)] [ProducesResponseType(typeof(IEnumerable<string>), 400)]
public virtual async Task<IActionResult> CreateCurrency([FromBody]CurrencyCreateBody body) public virtual async Task<IActionResult> CreateCurrency([FromBody] CurrencyCreateBody body)
{ {
var userIdString = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value; var userIdString = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
if (!int.TryParse(userIdString, out int userId)) if (!int.TryParse(userIdString, out int userId))
@ -123,7 +132,7 @@ namespace IO.Swagger.Controllers
/// <summary> /// <summary>
/// Mint additional units of a currency /// Mint additional units of a currency
/// </summary> /// </summary>
/// <param name="body"></param> /// <param name="body">The information on the currency to mint</param>
/// <response code="200">Successful minting</response> /// <response code="200">Successful minting</response>
/// <response code="400">Bad Request</response> /// <response code="400">Bad Request</response>
/// <response code="401">Unauthorized</response> /// <response code="401">Unauthorized</response>
@ -134,7 +143,7 @@ namespace IO.Swagger.Controllers
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("MintCurrency")] [SwaggerOperation("MintCurrency")]
[ProducesResponseType(typeof(IEnumerable<string>), 400)] [ProducesResponseType(typeof(IEnumerable<string>), 400)]
public virtual async Task<IActionResult> MintCurrency([FromBody]CurrencyMintBody body) public virtual async Task<IActionResult> MintCurrency([FromBody] CurrencyMintBody body)
{ {
var userIdString = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value; var userIdString = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
if (!int.TryParse(userIdString, out int userId)) if (!int.TryParse(userIdString, out int userId))
@ -151,7 +160,7 @@ namespace IO.Swagger.Controllers
/// </summary> /// </summary>
/// <response code="200">Returns all known currencies</response> /// <response code="200">Returns all known currencies</response>
/// <response code="401">Unauthorized</response> /// <response code="401">Unauthorized</response>
[HttpPost] [HttpGet]
[Route("/v1/api/currency/getAll")] [Route("/v1/api/currency/getAll")]
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]

View File

@ -7,27 +7,25 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System; using AutoMapper;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using IO.Swagger.Attributes; using IO.Swagger.Attributes;
using IO.Swagger.Models.RequestDto;
using IO.Swagger.Models.ResponseDto;
using IO.Swagger.Repositories;
using IO.Swagger.Security; using IO.Swagger.Security;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using IO.Swagger.Models.dto; using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using IO.Swagger.Repositories;
using System.Threading.Tasks; using System.Threading.Tasks;
using AutoMapper;
namespace IO.Swagger.Controllers namespace IO.Swagger.Controllers
{ {
/// <summary> /// <summary>
/// /// The controller for accessing routes for wallet management
/// </summary> /// </summary>
[ApiController] [ApiController]
public class WalletApiController : ControllerBase public class WalletApiController : ControllerBase
@ -35,6 +33,16 @@ namespace IO.Swagger.Controllers
private readonly ITransactionRepository transactionRepository; private readonly ITransactionRepository transactionRepository;
private readonly IMapper mapper; private readonly IMapper mapper;
/// <summary>
/// Initializes a new instance of the <see cref="WalletApiController"/> class.
/// </summary>
/// <param name="transactionRepository">The transaction repository.</param>
/// <param name="mapper">The mapper.</param>
/// <exception cref="System.ArgumentNullException">
/// transactionRepository
/// or
/// mapper
/// </exception>
public WalletApiController(ITransactionRepository transactionRepository, IMapper mapper) public WalletApiController(ITransactionRepository transactionRepository, IMapper mapper)
{ {
this.transactionRepository = transactionRepository ?? throw new ArgumentNullException(nameof(transactionRepository)); this.transactionRepository = transactionRepository ?? throw new ArgumentNullException(nameof(transactionRepository));
@ -102,7 +110,7 @@ namespace IO.Swagger.Controllers
[Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)] [Authorize(AuthenticationSchemes = BearerAuthenticationHandler.SchemeName)]
[ValidateModelState] [ValidateModelState]
[SwaggerOperation("TransferDigitalAsset")] [SwaggerOperation("TransferDigitalAsset")]
public virtual IActionResult TransferDigitalAsset([FromBody]WalletTransferDigitalBody body) public virtual IActionResult TransferDigitalAsset([FromBody] WalletTransferDigitalBody body)
{ {
//TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ... //TODO: Uncomment the next line to return response 200 or use other options such as return this.NotFound(), return this.BadRequest(..), ...
// return StatusCode(200); // return StatusCode(200);
@ -130,7 +138,7 @@ namespace IO.Swagger.Controllers
[SwaggerOperation("TransferPhysicalCurrency")] [SwaggerOperation("TransferPhysicalCurrency")]
[ProducesResponseType(typeof(IEnumerable<string>), 400)] [ProducesResponseType(typeof(IEnumerable<string>), 400)]
[ProducesResponseType(typeof(TransactionReturnCode), 409)] [ProducesResponseType(typeof(TransactionReturnCode), 409)]
public virtual async Task<IActionResult> TransferPhysicalCurrency([FromBody]WalletTransferPhysicalBody body) public virtual async Task<IActionResult> TransferPhysicalCurrency([FromBody] WalletTransferPhysicalBody body)
{ {
var userIdString = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value; var userIdString = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
if (!int.TryParse(userIdString, out int userId)) if (!int.TryParse(userIdString, out int userId))

View File

@ -1,8 +1,7 @@
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;
namespace IO.Swagger.Filters namespace IO.Swagger.Filters
{ {

View File

@ -1,8 +1,8 @@
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace IO.Swagger.Filters namespace IO.Swagger.Filters
{ {
@ -42,7 +42,7 @@ namespace IO.Swagger.Filters
string regex = (string)regexAttr.ConstructorArguments[0].Value; string regex = (string)regexAttr.ConstructorArguments[0].Value;
if (swaggerParam is OpenApiParameter) if (swaggerParam is OpenApiParameter)
{ {
((OpenApiParameter)swaggerParam).Schema.Pattern = regex; swaggerParam.Schema.Pattern = regex;
} }
} }
@ -72,8 +72,8 @@ namespace IO.Swagger.Filters
if (swaggerParam is OpenApiParameter) if (swaggerParam is OpenApiParameter)
{ {
((OpenApiParameter)swaggerParam).Schema.MinLength = minLenght; swaggerParam.Schema.MinLength = minLenght;
((OpenApiParameter)swaggerParam).Schema.MaxLength = maxLength; swaggerParam.Schema.MaxLength = maxLength;
} }
// Range [Range] // Range [Range]
@ -85,8 +85,8 @@ namespace IO.Swagger.Filters
if (swaggerParam is OpenApiParameter) if (swaggerParam is OpenApiParameter)
{ {
((OpenApiParameter)swaggerParam).Schema.Minimum = rangeMin; swaggerParam.Schema.Minimum = rangeMin;
((OpenApiParameter)swaggerParam).Schema.Maximum = rangeMax; swaggerParam.Schema.Maximum = rangeMax;
} }
} }
} }

View File

@ -8,6 +8,14 @@
<AssemblyName>IO.Swagger</AssemblyName> <AssemblyName>IO.Swagger</AssemblyName>
<PackageId>IO.Swagger</PackageId> <PackageId>IO.Swagger</PackageId>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<WarningLevel>9999</WarningLevel>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<WarningLevel>9999</WarningLevel>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" /> <PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.10" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.10" />

View File

@ -1,5 +1,5 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations; using System;
#nullable disable #nullable disable

View File

@ -7,18 +7,12 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
using System;
using System.Runtime.Serialization;
using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///
@ -48,8 +42,8 @@ namespace IO.Swagger.Models.dto
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class AuthLoginBody {\n"); sb.Append("class AuthLoginBody {\n");
sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" Email: ").Append(Email).Append('\n');
sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" Password: ").Append(Password).Append('\n');
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }
@ -70,7 +64,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((AuthLoginBody)obj); return obj.GetType() == GetType() && Equals((AuthLoginBody)obj);
} }
@ -82,7 +76,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public bool Equals(AuthLoginBody other) public bool Equals(AuthLoginBody other)
{ {
if (ReferenceEquals(null, other)) return false; if (other is null) return false;
if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(this, other)) return true;
return return

View File

@ -7,18 +7,13 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using Newtonsoft.Json;
using System; using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///

View File

@ -7,18 +7,13 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using Newtonsoft.Json;
using System; using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///

View File

@ -7,18 +7,13 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using Newtonsoft.Json;
using System; using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///
@ -50,8 +45,8 @@ namespace IO.Swagger.Models.dto
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class CurrencyCreateBody {\n"); sb.Append("class CurrencyCreateBody {\n");
sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Name: ").Append(Name).Append('\n');
sb.Append(" Symbol: ").Append(Symbol).Append("\n"); sb.Append(" Symbol: ").Append(Symbol).Append('\n');
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }
@ -72,7 +67,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((CurrencyCreateBody)obj); return obj.GetType() == GetType() && Equals((CurrencyCreateBody)obj);
} }
@ -84,7 +79,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public bool Equals(CurrencyCreateBody other) public bool Equals(CurrencyCreateBody other)
{ {
if (ReferenceEquals(null, other)) return false; if (other is null) return false;
if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(this, other)) return true;
return return

View File

@ -7,18 +7,12 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
using System;
using System.Runtime.Serialization;
using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///

View File

@ -7,18 +7,13 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using Newtonsoft.Json;
using System; using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///
@ -50,8 +45,8 @@ namespace IO.Swagger.Models.dto
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class CurrencyMintBody {\n"); sb.Append("class CurrencyMintBody {\n");
sb.Append(" CurrencyId: ").Append(CurrencyId).Append("\n"); sb.Append(" CurrencyId: ").Append(CurrencyId).Append('\n');
sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" Amount: ").Append(Amount).Append('\n');
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }
@ -72,7 +67,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((CurrencyMintBody)obj); return obj.GetType() == GetType() && Equals((CurrencyMintBody)obj);
} }
@ -84,18 +79,16 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public bool Equals(CurrencyMintBody other) public bool Equals(CurrencyMintBody other)
{ {
if (ReferenceEquals(null, other)) return false; if (other is null) return false;
if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(this, other)) return true;
return return
( (
CurrencyId == other.CurrencyId || CurrencyId == other.CurrencyId ||
CurrencyId != null &&
CurrencyId.Equals(other.CurrencyId) CurrencyId.Equals(other.CurrencyId)
) && ) &&
( (
Amount == other.Amount || Amount == other.Amount ||
Amount != null &&
Amount.Equals(other.Amount) Amount.Equals(other.Amount)
); );
} }
@ -106,16 +99,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Hash code</returns> /// <returns>Hash code</returns>
public override int GetHashCode() public override int GetHashCode()
{ {
unchecked // Overflow is fine, just wrap return HashCode.Combine(CurrencyId, Amount);
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (CurrencyId != null)
hashCode = hashCode * 59 + CurrencyId.GetHashCode();
if (Amount != null)
hashCode = hashCode * 59 + Amount.GetHashCode();
return hashCode;
}
} }
#region Operators #region Operators

View File

@ -7,18 +7,12 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
using System;
using System.Runtime.Serialization;
using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///

View File

@ -7,18 +7,13 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using Newtonsoft.Json;
using System; using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using System.Text;
namespace IO.Swagger.Models.dto namespace IO.Swagger.Models.RequestDto
{ {
/// <summary> /// <summary>
/// ///
@ -34,19 +29,25 @@ namespace IO.Swagger.Models.dto
public string DestUserEmail { get; set; } public string DestUserEmail { get; set; }
/// <summary> /// <summary>
/// Gets or Sets Amount /// Gets or Sets Amount of the transaction
/// </summary> /// </summary>
[Range(0.1, float.MaxValue, ErrorMessage="Please enter a valid transfer amount")] [Range(0.1, float.MaxValue, ErrorMessage = "Please enter a valid transfer amount")]
[DataMember(Name = "amount")] [DataMember(Name = "amount")]
public float Amount { get; set; } public float Amount { get; set; }
/// <summary> /// <summary>
/// Gets or Sets CurrencyId /// Gets or Sets CurrencyId the transaction will be performed with
/// </summary> /// </summary>
[Required] [Required]
[DataMember(Name = "currencyId")] [DataMember(Name = "currencyId")]
public int CurrencyId { get; set; } public int CurrencyId { get; set; }
/// <summary>
/// Gets or sets the memo of the transaction.
/// </summary>
/// <value>
/// The memo.
/// </value>
[DataMember(Name = "memo")] [DataMember(Name = "memo")]
[StringLength(32, MinimumLength = 2)] [StringLength(32, MinimumLength = 2)]
[Required] [Required]
@ -60,9 +61,9 @@ namespace IO.Swagger.Models.dto
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class WalletTransferPhysicalBody {\n"); sb.Append("class WalletTransferPhysicalBody {\n");
sb.Append(" DestUserEmail: ").Append(DestUserEmail).Append("\n"); sb.Append(" DestUserEmail: ").Append(DestUserEmail).Append('\n');
sb.Append(" Amount: ").Append(Amount).Append("\n"); sb.Append(" Amount: ").Append(Amount).Append('\n');
sb.Append(" CurrencyId: ").Append(CurrencyId).Append("\n"); sb.Append(" CurrencyId: ").Append(CurrencyId).Append('\n');
sb.Append("}\n"); sb.Append("}\n");
return sb.ToString(); return sb.ToString();
} }
@ -83,7 +84,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (ReferenceEquals(null, obj)) return false; if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true; if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((WalletTransferPhysicalBody)obj); return obj.GetType() == GetType() && Equals((WalletTransferPhysicalBody)obj);
} }
@ -95,7 +96,7 @@ namespace IO.Swagger.Models.dto
/// <returns>Boolean</returns> /// <returns>Boolean</returns>
public bool Equals(WalletTransferPhysicalBody other) public bool Equals(WalletTransferPhysicalBody other)
{ {
if (ReferenceEquals(null, other)) return false; if (other is null) return false;
if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(this, other)) return true;
return return
@ -106,12 +107,10 @@ namespace IO.Swagger.Models.dto
) && ) &&
( (
Amount == other.Amount || Amount == other.Amount ||
Amount != null &&
Amount.Equals(other.Amount) Amount.Equals(other.Amount)
) && ) &&
( (
CurrencyId == other.CurrencyId || CurrencyId == other.CurrencyId ||
CurrencyId != null &&
CurrencyId.Equals(other.CurrencyId) CurrencyId.Equals(other.CurrencyId)
); );
} }
@ -128,10 +127,8 @@ namespace IO.Swagger.Models.dto
// Suitable nullity checks etc, of course :) // Suitable nullity checks etc, of course :)
if (DestUserEmail != null) if (DestUserEmail != null)
hashCode = hashCode * 59 + DestUserEmail.GetHashCode(); hashCode = hashCode * 59 + DestUserEmail.GetHashCode();
if (Amount != null) hashCode = hashCode * 59 + Amount.GetHashCode();
hashCode = hashCode * 59 + Amount.GetHashCode(); hashCode = hashCode * 59 + CurrencyId.GetHashCode();
if (CurrencyId != null)
hashCode = hashCode * 59 + CurrencyId.GetHashCode();
return hashCode; return hashCode;
} }
} }

View File

@ -0,0 +1,34 @@
using System.ComponentModel.DataAnnotations;
namespace IO.Swagger.Models.ResponseDto
{
/// <summary>
/// The output DTO for basic currency information
/// </summary>
public class CurrencyDto
{
/// <summary>
/// Gets or sets the currency identifier.
/// </summary>
/// <value>
/// The currency identifier.
/// </value>
public int CurrencyId { get; set; }
/// <summary>
/// Gets or sets the name of the currency.
/// </summary>
/// <value>
/// The name.
/// </value>
[StringLength(32, MinimumLength = 1)]
public string Name { get; set; }
/// <summary>
/// Gets or sets the symbol of the currency.
/// </summary>
/// <value>
/// The symbol.
/// </value>
[StringLength(4, MinimumLength = 1)]
public string Symbol { get; set; }
}
}

View File

@ -0,0 +1,31 @@
namespace IO.Swagger.Models.ResponseDto
{
/// <summary>
/// The DTO for returning detailed currency information
/// </summary>
/// <seealso cref="IO.Swagger.Models.ResponseDto.CurrencyDto" />
public class CurrencyInfoDto : CurrencyDto
{
/// <summary>
/// Gets or sets the currency owner.
/// </summary>
/// <value>
/// The currency owner.
/// </value>
public UserDto CurrencyOwner { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this logged in user is the owner of this currency.
/// </summary>
/// <value>
/// <c>true</c> if this instance is owner; otherwise, <c>false</c>.
/// </value>
public bool IsOwner { get; set; }
/// <summary>
/// Gets or sets the amount in circulation of this currency.
/// </summary>
/// <value>
/// The amount in circulation.
/// </value>
public float AmountInCirculation { get; set; }
}
}

View File

@ -0,0 +1,16 @@
namespace IO.Swagger.Models.ResponseDto
{
/// <summary>
/// The DTO returned when a JWT is requested
/// </summary>
public class TokenDto
{
/// <summary>
/// Gets or sets the valid JWT that can be used for accessing other API routes.
/// </summary>
/// <value>
/// The token.
/// </value>
public string Token { get; set; }
}
}

View File

@ -0,0 +1,54 @@
using System;
namespace IO.Swagger.Models.ResponseDto
{
/// <summary>
/// The DTO that is return when transactions are requested
/// </summary>
public class TransactionDto
{
/// <summary>
/// Gets or sets the user that originated the transaction.
/// </summary>
/// <value>
/// From user.
/// </value>
public UserDto FromUser { get; set; }
/// <summary>
/// Gets or sets the user that received the transaction.
/// </summary>
/// <value>
/// From user.
/// </value>
public UserDto ToUser { get; set; }
/// <summary>
/// Gets or sets the amount of the transaction.
/// </summary>
/// <value>
/// The amount.
/// </value>
public float Amount { get; set; }
/// <summary>
/// Gets or sets the currency the transaction was performed with.
/// </summary>
/// <value>
/// The currency.
/// </value>
public CurrencyDto Currency { get; set; }
/// <summary>
/// Gets or sets the memo of the transaction.
/// </summary>
/// <value>
/// The memo.
/// </value>
public string Memo { get; set; }
/// <summary>
/// Gets or sets the time the transaction occurred.
/// </summary>
/// <value>
/// The transaction time.
/// </value>
public DateTime TransactionTime { get; set; }
}
}

View File

@ -0,0 +1,30 @@
namespace IO.Swagger.Models.ResponseDto
{
/// <summary>
/// The dto for returning user information
/// </summary>
public class UserDto
{
/// <summary>
/// Gets or sets the email of the user.
/// </summary>
/// <value>
/// The email.
/// </value>
public string Email { get; set; }
/// <summary>
/// Gets or sets the first name of the user.
/// </summary>
/// <value>
/// The first name.
/// </value>
public string FirstName { get; set; }
/// <summary>
/// Gets or sets the last name of the user.
/// </summary>
/// <value>
/// The last name.
/// </value>
public string LastName { get; set; }
}
}

View File

@ -0,0 +1,23 @@
namespace IO.Swagger.Models.ResponseDto
{
/// <summary>
/// The DTP returned for the balance of a single currency type in a wallet.
/// </summary>
public class WalletBalanceDto
{
/// <summary>
/// Gets or sets the currency the balance is in.
/// </summary>
/// <value>
/// The currency.
/// </value>
public CurrencyDto Currency { get; set; }
/// <summary>
/// Gets or sets the amount of the currency.
/// </summary>
/// <value>
/// The balance.
/// </value>
public float Balance { get; set; }
}
}

View File

@ -1,23 +1,59 @@
using System.Collections; using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace IO.Swagger.Models.db namespace IO.Swagger.Models.db
{ {
/// <summary>
/// The basic representation of currency
/// </summary>
public class Currency public class Currency
{ {
/// <summary>
/// Gets or sets the currency identifier.
/// </summary>
/// <value>
/// The currency identifier.
/// </value>
public int CurrencyId { get; set; } public int CurrencyId { get; set; }
/// <summary>
/// Gets or sets the name of the currency.
/// </summary>
/// <value>
/// The name.
/// </value>
[StringLength(32, MinimumLength = 1)] [StringLength(32, MinimumLength = 1)]
public string Name { get; set; } public string Name { get; set; }
/// <summary>
/// Gets or sets the symbol to use for shorthand representation of the currency.
/// </summary>
/// <value>
/// The symbol.
/// </value>
[StringLength(4, MinimumLength = 1)] [StringLength(4, MinimumLength = 1)]
public string Symbol { get; set; } public string Symbol { get; set; }
/// <summary>
/// Gets or sets the user identifier that created the currency.
/// </summary>
/// <value>
/// The user identifier.
/// </value>
[ForeignKey("FK_Currency_UserId")] [ForeignKey("FK_Currency_UserId")]
public int UserId { get; set; } public int UserId { get; set; }
/// <summary>
/// Gets or sets the user that created the currency.
/// </summary>
/// <value>
/// The user.
/// </value>
public User User { get; set; } public User User { get; set; }
/// <summary>
/// Gets or sets the transactions that have been performed with this currency.
/// </summary>
/// <value>
/// The transactions.
/// </value>
public ICollection<Transaction> Transactions { get; set; } public ICollection<Transaction> Transactions { get; set; }
} }
} }

View File

@ -1,29 +1,88 @@
using Microsoft.EntityFrameworkCore; using System;
using Microsoft.VisualBasic;
using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace IO.Swagger.Models.db namespace IO.Swagger.Models.db
{ {
/// <summary>
/// The basic unit of a transaction
/// </summary>
public class Transaction public class Transaction
{ {
/// <summary>
/// Gets or sets the transaction identifier.
/// </summary>
/// <value>
/// The transaction identifier.
/// </value>
public int TransactionId { get; set; } public int TransactionId { get; set; }
/// <summary>
/// Gets or sets the user identifier of the wallet the money came from.
/// </summary>
/// <value>
/// From user identifier.
/// </value>
public int FromUserId { get; set; } public int FromUserId { get; set; }
/// <summary>
/// Gets or sets the user that the money came from.
/// </summary>
/// <value>
/// From user.
/// </value>
public User FromUser { get; set; } public User FromUser { get; set; }
/// <summary>
/// Gets or sets the user identifier of the wallet the money went to.
/// </summary>
/// <value>
/// From user identifier.
/// </value>
public int ToUserId { get; set; } public int ToUserId { get; set; }
/// <summary>
/// Gets or sets the user that the money went to.
/// </summary>
/// <value>
/// From user.
/// </value>
public User ToUser { get; set; } public User ToUser { get; set; }
/// <summary>
/// Gets or sets the amount exchanged in the transaction.
/// </summary>
/// <value>
/// The amount.
/// </value>
[Range(0.01, float.MaxValue)] [Range(0.01, float.MaxValue)]
public float Amount { get; set; } public float Amount { get; set; }
/// <summary>
/// Gets or sets the memo of the transaction.
/// </summary>
/// <value>
/// The memo.
/// </value>
[Required] [Required]
[StringLength(32, MinimumLength = 2)] [StringLength(32, MinimumLength = 2)]
public string Memo { get; set; } public string Memo { get; set; }
/// <summary>
/// Gets or sets the currency the transaction amount was issued in.
/// </summary>
/// <value>
/// The currency.
/// </value>
public Currency Currency { get; set; } public Currency Currency { get; set; }
/// <summary>
/// Gets or sets the currency identifier the transaction amount was issued in.
/// </summary>
/// <value>
/// The currency identifier.
/// </value>
public int CurrencyId { get; set; } public int CurrencyId { get; set; }
/// <summary>
/// Gets or sets the time the transaction occured.
/// </summary>
/// <value>
/// The transaction time.
/// </value>
public DateTime TransactionTime { get; set; } = DateTime.UtcNow; public DateTime TransactionTime { get; set; } = DateTime.UtcNow;
} }
} }

View File

@ -1,23 +1,77 @@
using System.Collections; using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace IO.Swagger.Models.db namespace IO.Swagger.Models.db
{ {
/// <summary>
/// The basic representation of a user
/// </summary>
public class User public class User
{ {
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>
/// The identifier.
/// </value>
public int Id { get; set; } public int Id { get; set; }
/// <summary>
/// Gets or sets the email of the user.
/// </summary>
/// <value>
/// The email.
/// </value>
public string Email { get; set; } public string Email { get; set; }
/// <summary>
/// Gets or sets the first name of the user.
/// </summary>
/// <value>
/// The first name.
/// </value>
[StringLength(32, MinimumLength = 3)] [StringLength(32, MinimumLength = 3)]
public string FirstName { get; set; } public string FirstName { get; set; }
/// <summary>
/// Gets or sets the last name of the user.
/// </summary>
/// <value>
/// The last name.
/// </value>
[StringLength(32, MinimumLength = 3)] [StringLength(32, MinimumLength = 3)]
public string LastName { get; set; } public string LastName { get; set; }
/// <summary>
/// Gets or sets the hashed and salted equivalent of the users password.
/// </summary>
/// <value>
/// The password hash.
/// </value>
public string PasswordHash { get; set; } public string PasswordHash { get; set; }
/// <summary>
/// Gets or sets the randomly generated salt of the users password.
/// </summary>
/// <value>
/// The salt.
/// </value>
public string Salt { get; set; } public string Salt { get; set; }
/// <summary>
/// Gets or sets the currencies the user has created.
/// </summary>
/// <value>
/// The currencies.
/// </value>
public ICollection<Currency> Currencies { get; set; } public ICollection<Currency> Currencies { get; set; }
/// <summary>
/// Gets or sets the transactions from the user.
/// </summary>
/// <value>
/// The transactions from.
/// </value>
public ICollection<Transaction> TransactionsFrom { get; set; } public ICollection<Transaction> TransactionsFrom { get; set; }
/// <summary>
/// Gets or sets the transactions to the user.
/// </summary>
/// <value>
/// The transactions to.
/// </value>
public ICollection<Transaction> TransactionsTo { get; set; } public ICollection<Transaction> TransactionsTo { get; set; }
} }

View File

@ -1,13 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace IO.Swagger.Models.dto
{
public class CurrencyDto
{
public int CurrencyId { get; set; }
[StringLength(32, MinimumLength = 1)]
public string Name { get; set; }
[StringLength(4, MinimumLength = 1)]
public string Symbol { get; set; }
}
}

View File

@ -1,9 +0,0 @@
namespace IO.Swagger.Models.dto
{
public class CurrencyInfoDto : CurrencyDto
{
public UserDto CurrencyOwner { get; set; }
public bool IsOwner { get; set; }
public float AmountInCirculation { get; set; }
}
}

View File

@ -1,7 +0,0 @@
namespace IO.Swagger.Models.dto
{
public class TokenDto
{
public string Token { get; set; }
}
}

View File

@ -1,16 +0,0 @@
using Microsoft.SqlServer.Server;
using Microsoft.VisualBasic;
using System;
namespace IO.Swagger.Models.dto
{
public class TransactionDto
{
public UserDto FromUser { get; set; }
public UserDto ToUser { get; set; }
public float Amount { get; set; }
public CurrencyDto Currency { get; set; }
public string Memo { get; set; }
public DateTime TransactionTime { get; set; }
}
}

View File

@ -1,13 +0,0 @@
using IO.Swagger.Models.db;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace IO.Swagger.Models.dto
{
public class UserDto
{
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace IO.Swagger.Models.dto
{
public class WalletBalanceDto
{
public CurrencyDto Currency { get; set; }
public float Balance { get; set; }
}
}

View File

@ -1,5 +1,5 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace IO.Swagger namespace IO.Swagger
{ {

View File

@ -1,28 +1,38 @@
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using IO.Swagger.Models.dto; using IO.Swagger.Models.RequestDto;
using IO.Swagger.Services; using IO.Swagger.Services;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace IO.Swagger.Repositories namespace IO.Swagger.Repositories
{ {
/// <summary>
/// The EF implementation of this interface
/// </summary>
/// <seealso cref="ICurrencyRepository" />
public class CurrencyRepository : ICurrencyRepository public class CurrencyRepository : ICurrencyRepository
{ {
BankDbContext context; private readonly BankDbContext context;
/// <summary>
/// Initializes a new instance of the <see cref="CurrencyRepository"/> class.
/// </summary>
/// <param name="context">The db context.</param>
/// <exception cref="ArgumentNullException">context</exception>
public CurrencyRepository(BankDbContext context) public CurrencyRepository(BankDbContext context)
{ {
this.context = context ?? throw new ArgumentNullException(nameof(context)); this.context = context ?? throw new ArgumentNullException(nameof(context));
} }
/// <inheritdoc/>
public async Task<List<Currency>> GetAllCurrencies() public async Task<List<Currency>> GetAllCurrencies()
{ {
return await context.Currencies.Include(c => c.User).Include(c=>c.Transactions).ToListAsync(); return await context.Currencies.Include(c => c.User).Include(c => c.Transactions).ToListAsync();
} }
/// <inheritdoc/>
public async Task<bool> CreateCurrency(CurrencyCreateBody request, int userId) public async Task<bool> CreateCurrency(CurrencyCreateBody request, int userId)
{ {
request.Symbol = request.Symbol.Trim(); request.Symbol = request.Symbol.Trim();
@ -40,6 +50,7 @@ namespace IO.Swagger.Repositories
return await context.SaveChangesAsync() > 0; return await context.SaveChangesAsync() > 0;
} }
/// <inheritdoc/>
public async Task<bool> MintCurrency(CurrencyMintBody request, int userId) public async Task<bool> MintCurrency(CurrencyMintBody request, int userId)
{ {
var existsAndIsOwner = await context.Currencies.AnyAsync(c => c.CurrencyId == request.CurrencyId && c.UserId == userId); var existsAndIsOwner = await context.Currencies.AnyAsync(c => c.CurrencyId == request.CurrencyId && c.UserId == userId);

View File

@ -1,14 +1,33 @@
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using IO.Swagger.Models.dto; using IO.Swagger.Models.RequestDto;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace IO.Swagger.Repositories namespace IO.Swagger.Repositories
{ {
/// <summary>
/// The interface defining all currency management activities
/// </summary>
public interface ICurrencyRepository public interface ICurrencyRepository
{ {
Task<bool> CreateCurrency(CurrencyCreateBody request, int userId); /// <summary>
/// Gets all currencies.
/// </summary>
/// <returns>A list of all known currencies</returns>
Task<List<Currency>> GetAllCurrencies(); Task<List<Currency>> GetAllCurrencies();
/// <summary>
/// Creates the currency.
/// </summary>
/// <param name="request">The currency to create.</param>
/// <param name="userId">The user id creating the currency.</param>
/// <returns>True if the creation was successful, false otherwise.</returns>
Task<bool> CreateCurrency(CurrencyCreateBody request, int userId);
/// <summary>
/// Mints the supplied amount of the supplied currency.
/// </summary>
/// <param name="request">The currency to mint and how much.</param>
/// <param name="userId">The user id mintung the currency.</param>
/// <returns>True if the currency was minted, false otherwise.</returns>
Task<bool> MintCurrency(CurrencyMintBody request, int userId); Task<bool> MintCurrency(CurrencyMintBody request, int userId);
} }
} }

View File

@ -1,23 +1,57 @@
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using IO.Swagger.Models.dto; using IO.Swagger.Models.RequestDto;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace IO.Swagger.Repositories namespace IO.Swagger.Repositories
{ {
/// <summary>
/// The enum defining transaction creation results
/// </summary>
public enum TransactionReturnCode public enum TransactionReturnCode
{ {
/// <summary>
/// The success code
/// </summary>
Success, Success,
/// <summary>
/// The transaction had insufficient funds
/// </summary>
InsufficientFunds, InsufficientFunds,
/// <summary>
/// The the transaction had unknown destination user
/// </summary>
UnknownDestinationUser, UnknownDestinationUser,
/// <summary>
/// The transaction encountered database error
/// </summary>
DbError DbError
} }
/// <summary>
/// The interface defining all transaction actions
/// </summary>
public interface ITransactionRepository public interface ITransactionRepository
{ {
/// <summary>
/// Gets the balances for user.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>The currencies and associated balance of that currency</returns>
Task<List<Tuple<Currency, float>>> GetBalancesForUser(int userId); Task<List<Tuple<Currency, float>>> GetBalancesForUser(int userId);
/// <summary>
/// Gets the transactions for user.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>A list of all transactions the user has performed in time descending order.</returns>
Task<List<Transaction>> GetTransactionsForUser(int userId); Task<List<Transaction>> GetTransactionsForUser(int userId);
/// <summary>
/// Transfers the physical currency from one account to another.
/// </summary>
/// <param name="request">The transfer request.</param>
/// <param name="fromUserId">From user identifier.</param>
/// <returns>The TransactionReturnCode corresponding to action that was performed.</returns>
Task<TransactionReturnCode> TransferPhysical(WalletTransferPhysicalBody request, int fromUserId); Task<TransactionReturnCode> TransferPhysical(WalletTransferPhysicalBody request, int fromUserId);
} }
} }

View File

@ -1,13 +1,31 @@
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using IO.Swagger.Models.dto; using IO.Swagger.Models.RequestDto;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace IO.Swagger.Repositories namespace IO.Swagger.Repositories
{ {
/// <summary>
/// The repository governing how to access user data
/// </summary>
public interface IUserRepository public interface IUserRepository
{ {
/// <summary>
/// Logins the user.
/// </summary>
/// <param name="request">The login request.</param>
/// <returns>The user if login was successful, null otherwise</returns>
Task<User> LoginUser(AuthLoginBody request); Task<User> LoginUser(AuthLoginBody request);
/// <summary>
/// Registers the user.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The user if registration was successful, null otherwise</returns>
Task<User> RegisterUser(AuthRegisterBody request); Task<User> RegisterUser(AuthRegisterBody request);
/// <summary>
/// Retrieves the information about the user.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>The users information if it exists, null otherwise.</returns>
Task<User> RetrieveUser(int userId); Task<User> RetrieveUser(int userId);
} }
} }

View File

@ -1,5 +1,5 @@
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using IO.Swagger.Models.dto; using IO.Swagger.Models.RequestDto;
using IO.Swagger.Services; using IO.Swagger.Services;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System; using System;
@ -9,16 +9,25 @@ using System.Threading.Tasks;
namespace IO.Swagger.Repositories namespace IO.Swagger.Repositories
{ {
/// <summary>
/// The EF implementation of this interface
/// </summary>
/// <seealso cref="IO.Swagger.Repositories.ITransactionRepository" />
public class TransactionRepository : ITransactionRepository public class TransactionRepository : ITransactionRepository
{ {
BankDbContext context; private readonly BankDbContext context;
/// <summary>
/// Initializes a new instance of the <see cref="TransactionRepository"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <exception cref="System.ArgumentNullException">context</exception>
public TransactionRepository(BankDbContext context) public TransactionRepository(BankDbContext context)
{ {
this.context = context ?? throw new ArgumentNullException(nameof(context)); this.context = context ?? throw new ArgumentNullException(nameof(context));
} }
/// <inheritdoc/>
public async Task<List<Transaction>> GetTransactionsForUser(int userId) public async Task<List<Transaction>> GetTransactionsForUser(int userId)
{ {
var transactions = await context.Transactions.Where(t => t.ToUserId == userId || t.FromUserId == userId) var transactions = await context.Transactions.Where(t => t.ToUserId == userId || t.FromUserId == userId)
@ -34,6 +43,8 @@ namespace IO.Swagger.Repositories
return transactions; return transactions;
} }
/// <inheritdoc/>
public async Task<List<Tuple<Currency, float>>> GetBalancesForUser(int userId) public async Task<List<Tuple<Currency, float>>> GetBalancesForUser(int userId)
{ {
var transactions = await context.Transactions.Where(t => t.ToUserId == userId || t.FromUserId == userId) var transactions = await context.Transactions.Where(t => t.ToUserId == userId || t.FromUserId == userId)
@ -41,7 +52,7 @@ namespace IO.Swagger.Repositories
.GroupBy(t => t.Currency) .GroupBy(t => t.Currency)
.Select(g => Tuple.Create( .Select(g => Tuple.Create(
g.Key, g.Key,
g.Sum(t =>t.ToUserId != t.FromUserId && t.FromUserId == userId g.Sum(t => t.ToUserId != t.FromUserId && t.FromUserId == userId
? -t.Amount ? -t.Amount
: t.Amount : t.Amount
) )
@ -52,6 +63,8 @@ namespace IO.Swagger.Repositories
return transactions; return transactions;
} }
/// <inheritdoc/>
public async Task<TransactionReturnCode> TransferPhysical(WalletTransferPhysicalBody request, int fromUserId) public async Task<TransactionReturnCode> TransferPhysical(WalletTransferPhysicalBody request, int fromUserId)
{ {
var trimmedDest = request.DestUserEmail.Trim().ToLower(); var trimmedDest = request.DestUserEmail.Trim().ToLower();

View File

@ -1,23 +1,31 @@
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using System.Security.Cryptography; using IO.Swagger.Models.RequestDto;
using System;
using IO.Swagger.Services; using IO.Swagger.Services;
using IO.Swagger.Models.dto;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Linq; using System;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace IO.Swagger.Repositories namespace IO.Swagger.Repositories
{ {
/// <summary>
/// The EF implementation of this interface
/// </summary>
/// <seealso cref="IO.Swagger.Repositories.IUserRepository" />
public class UserRepository : IUserRepository public class UserRepository : IUserRepository
{ {
private readonly BankDbContext bankDbContext; private readonly BankDbContext bankDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="UserRepository"/> class.
/// </summary>
/// <param name="bankDbContext">The bank database context.</param>
public UserRepository(BankDbContext bankDbContext) public UserRepository(BankDbContext bankDbContext)
{ {
this.bankDbContext = bankDbContext; this.bankDbContext = bankDbContext;
} }
/// <inheritdoc/>
public async Task<User> RegisterUser(AuthRegisterBody request) public async Task<User> RegisterUser(AuthRegisterBody request)
{ {
request.Email = request.Email.ToLower(); request.Email = request.Email.ToLower();
@ -25,15 +33,14 @@ namespace IO.Swagger.Repositories
return null; return null;
// Generate a random salt // Generate a random salt
byte[] saltBytes = new byte[16]; byte[] saltBytes = RandomNumberGenerator.GetBytes(16);
new RNGCryptoServiceProvider().GetBytes(saltBytes);
string salt = Convert.ToBase64String(saltBytes); string salt = Convert.ToBase64String(saltBytes);
// Hash the password along with the salt // Hash the password along with the salt
string password = request.Password; string password = request.Password;
string saltedPassword = password + salt; string saltedPassword = password + salt;
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword); byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword);
byte[] hashedBytes = new SHA256Managed().ComputeHash(passwordBytes); byte[] hashedBytes = SHA256.HashData(passwordBytes);
string hashedPassword = Convert.ToBase64String(hashedBytes); string hashedPassword = Convert.ToBase64String(hashedBytes);
// Create and insert the user // Create and insert the user
@ -51,6 +58,7 @@ namespace IO.Swagger.Repositories
return newUser; return newUser;
} }
/// <inheritdoc/>
public async Task<User> LoginUser(AuthLoginBody request) public async Task<User> LoginUser(AuthLoginBody request)
{ {
request.Email = request.Email.ToLower(); request.Email = request.Email.ToLower();
@ -62,13 +70,14 @@ namespace IO.Swagger.Repositories
string password = request.Password; string password = request.Password;
string saltedPassword = password + user.Salt; string saltedPassword = password + user.Salt;
byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword); byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword);
byte[] hashedBytes = new SHA256Managed().ComputeHash(passwordBytes); byte[] hashedBytes = SHA256.HashData(passwordBytes);
string hashedPassword = Convert.ToBase64String(hashedBytes); string hashedPassword = Convert.ToBase64String(hashedBytes);
if (hashedPassword != user.PasswordHash) if (hashedPassword != user.PasswordHash)
return null; return null;
return user; return user;
} }
/// <inheritdoc/>
public async Task<User> RetrieveUser(int userId) public async Task<User> RetrieveUser(int userId)
{ {
return await bankDbContext.Users.FirstOrDefaultAsync(u => u.Id == userId); return await bankDbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);

View File

@ -1,16 +1,14 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System; using System;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
namespace IO.Swagger.Security namespace IO.Swagger.Security
{ {
@ -19,6 +17,7 @@ namespace IO.Swagger.Security
/// </summary> /// </summary>
public class BearerAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> public class BearerAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{ {
//TODO: Clean this up and use the service for it
private readonly string secretKey; private readonly string secretKey;
private readonly byte[] secretBytes; private readonly byte[] secretBytes;
@ -27,6 +26,7 @@ namespace IO.Swagger.Security
/// </summary> /// </summary>
public const string SchemeName = "Bearer"; public const string SchemeName = "Bearer";
/// <inheritdoc/>
public BearerAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) public BearerAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{ {
secretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY"); secretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY");
@ -36,54 +36,54 @@ namespace IO.Swagger.Security
/// <summary> /// <summary>
/// verify that require authorization header exists. /// verify that require authorization header exists.
/// </summary> /// </summary>
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{ {
if (!Request.Headers.ContainsKey("Authorization")) return Task.Run(() =>
{ {
return AuthenticateResult.Fail("Missing Authorization Header"); if (!Request.Headers.ContainsKey("Authorization"))
}
try
{
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{ {
ValidateIssuerSigningKey = true, return AuthenticateResult.Fail("Missing Authorization Header");
IssuerSigningKey = new SymmetricSecurityKey(secretBytes), }
ValidateIssuer = false,
ValidateAudience = false
};
try try
{ {
var claimsPrincipal = tokenHandler.ValidateToken(authHeader.Parameter, validationParameters, out _); var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId)) var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{ {
var claims = new[]{ new Claim(ClaimTypes.NameIdentifier, userId.ToString()) }; ValidateIssuerSigningKey = true,
var identity = new ClaimsIdentity(claims, SchemeName); IssuerSigningKey = new SymmetricSecurityKey(secretBytes),
var principal = new ClaimsPrincipal(identity); ValidateIssuer = false,
var ticket = new AuthenticationTicket(principal, Scheme.Name); ValidateAudience = false
};
return AuthenticateResult.Success(ticket); try
{
var claimsPrincipal = tokenHandler.ValidateToken(authHeader.Parameter, validationParameters, out _);
var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim != null && int.TryParse(userIdClaim.Value, out int userId))
{
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId.ToString()) };
var identity = new ClaimsIdentity(claims, SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
catch (Exception)
{
return AuthenticateResult.Fail("Invalid Auth Token");
} }
} }
catch (Exception) catch
{ {
return AuthenticateResult.Fail("Invalid Auth Token"); return AuthenticateResult.Fail("Invalid Authorization Header");
} }
return AuthenticateResult.Fail("Missing Authorization Header");
});
}
catch
{
return AuthenticateResult.Fail("Invalid Authorization Header");
}
return AuthenticateResult.Fail("Missing Authorization Header");
} }
} }
} }

View File

@ -3,18 +3,40 @@ using Microsoft.EntityFrameworkCore;
namespace IO.Swagger.Services namespace IO.Swagger.Services
{ {
/// <summary>
/// The EF DbContext that owns all connections and interactions
/// </summary>
/// <seealso cref="Microsoft.EntityFrameworkCore.DbContext" />
public class BankDbContext : DbContext public class BankDbContext : DbContext
{ {
/// <inheritdoc/>
public BankDbContext(DbContextOptions options) : base(options) public BankDbContext(DbContextOptions options) : base(options)
{ {
} }
/// <summary>
/// Gets or sets the collections of users.
/// </summary>
/// <value>
/// The users.
/// </value>
public DbSet<User> Users { get; set; } public DbSet<User> Users { get; set; }
/// <summary>
/// Gets or sets the collection of currencies.
/// </summary>
/// <value>
/// The currencies.
/// </value>
public DbSet<Currency> Currencies { get; set; } public DbSet<Currency> Currencies { get; set; }
/// <summary>
/// Gets or sets the collection of transactions.
/// </summary>
/// <value>
/// The transactions.
/// </value>
public DbSet<Transaction> Transactions { get; set; } public DbSet<Transaction> Transactions { get; set; }
/// <inheritdoc/>
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);

View File

@ -1,28 +1,38 @@
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System;
namespace IO.Swagger.Services namespace IO.Swagger.Services
{ {
/// <summary>
/// The internal service for creating and reading JWTs
/// </summary>
public class JwtService public class JwtService
{ {
private readonly string secretKey; private readonly string secretKey;
private readonly byte[] secretBytes; private readonly byte[] secretBytes;
/// <summary>
/// Initializes a new instance of the <see cref="JwtService"/> class.
/// </summary>
public JwtService() public JwtService()
{ {
secretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY"); secretKey = Environment.GetEnvironmentVariable("JWT_SECRET_KEY");
secretBytes = Encoding.UTF8.GetBytes(secretKey); secretBytes = Encoding.UTF8.GetBytes(secretKey);
} }
/// <summary>
/// Generates the JWT.
/// </summary>
/// <param name="userId">The user identifier.</param>
/// <returns>A JWT that will expire in 1hr from time of issue enconding the user id supplied</returns>
public string GenerateJwt(int userId) public string GenerateJwt(int userId)
{ {
var claims = new[] var claims = new[]
{ {
new Claim(ClaimTypes.NameIdentifier, userId.ToString()) new Claim(ClaimTypes.NameIdentifier, userId.ToString())
// You can add more claims as needed
}; };
var tokenHandler = new JwtSecurityTokenHandler(); var tokenHandler = new JwtSecurityTokenHandler();
@ -36,11 +46,5 @@ namespace IO.Swagger.Services
var token = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token); return tokenHandler.WriteToken(token);
} }
public int GetUserIdFromJwt(string jwtToken)
{
return -1; // Return -1 if user ID extraction fails
}
} }
} }

View File

@ -1,12 +1,19 @@
using AutoMapper; using AutoMapper;
using IO.Swagger.Models.db; using IO.Swagger.Models.db;
using IO.Swagger.Models.dto; using IO.Swagger.Models.ResponseDto;
using System.Linq; using System.Linq;
namespace IO.Swagger.Services namespace IO.Swagger.Services
{ {
/// <summary>
/// The configuration of all automapper profiles
/// </summary>
/// <seealso cref="AutoMapper.Profile" />
public class MapperProfile : Profile public class MapperProfile : Profile
{ {
/// <summary>
/// Initializes a new instance of the <see cref="MapperProfile"/> class.
/// </summary>
public MapperProfile() public MapperProfile()
{ {
CreateMap<User, UserDto>(); CreateMap<User, UserDto>();

View File

@ -7,11 +7,15 @@
* *
* Generated by: https://github.com/swagger-api/swagger-codegen.git * Generated by: https://github.com/swagger-api/swagger-codegen.git
*/ */
using System; using AutoMapper;
using System.IO; using IO.Swagger.Filters;
using IO.Swagger.Repositories;
using IO.Swagger.Security;
using IO.Swagger.Services;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
@ -19,14 +23,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters; using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Swagger; using System;
using Swashbuckle.AspNetCore.SwaggerGen; using System.IO;
using IO.Swagger.Filters;
using IO.Swagger.Security;
using IO.Swagger.Repositories;
using IO.Swagger.Services;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
namespace IO.Swagger namespace IO.Swagger
{ {
@ -118,7 +116,7 @@ namespace IO.Swagger
Id="bearerAuth" Id="bearerAuth"
} }
}, },
new string[]{} Array.Empty<string>()
} }
}); });
}); });
@ -131,7 +129,8 @@ namespace IO.Swagger
// CORS sucks // CORS sucks
services.AddCors(opt => { services.AddCors(opt =>
{
opt.AddDefaultPolicy(po => opt.AddDefaultPolicy(po =>
{ {
po.AllowAnyHeader() po.AllowAnyHeader()