using FindAndDrive.Domain.Helpers; using FindAndDrive.Domain.Interfaces.Providers; using FindAndDrive.Domain.Interfaces.Repositories; using FindAndDrive.Domain.Interfaces.Services; using FindAndDrive.Domain.Mappers; using FindAndDrive.Domain.Models.DTO; using FindAndDrive.Domain.Models.DTO.Response; using FindAndDrive.Domain.Models.Entities; namespace FindAndDrive.Domain.Services; public class ApiKeyService : IApiKeyService { private readonly IApiKeyRepository _apiKeyRepository; private readonly IDateTimeProvider _dateTimeProvider; public ApiKeyService(IApiKeyRepository apiKeyRepository, IDateTimeProvider dateTimeProvider) { _apiKeyRepository = apiKeyRepository; _dateTimeProvider = dateTimeProvider; } public async Task CreateApiKey(Guid clientId, Guid roleId) { var response = GetNewApikey(); if (response.ResponseObject is null) throw new Exception("Generate key secrets failed"); var apiKey = new ApiKey { Revoked = false, ClientId = clientId, CreatedAt = _dateTimeProvider.GetSouthAfricanDateTime(), ModifiedAt = null, RoleId = roleId, KeySecretHash = response.ResponseObject.SecretHash, }; var apiKeyResponse = await _apiKeyRepository.Create(apiKey); return new ApiKeyCreateResponse { RoleId = apiKeyResponse.RoleId, ClientId = apiKeyResponse.ClientId, CreatedAt = apiKeyResponse.CreatedAt, ApiKeyId = apiKeyResponse.ApiKeyId, KeySecret = response.ResponseObject.KeySecret, }; } private ServiceResponse GetNewApikey() { var apiKeySecret = ApiKeyHelper.GenerateApiKey(); var secretHash = ApiKeyHelper.HashString(apiKeySecret); var response = new ApiKeySecret { KeySecret = apiKeySecret, SecretHash = secretHash, }; return new ServiceResponse(true, "Random key generated", response); } public List GetApiKeys(Guid clientId) { var keys = _apiKeyRepository.Find(w => w.ClientId == clientId); return keys.Select(ApiKeyMapper.Map).ToList(); } public async Task GetApiKey(Guid apiKeyId) { return await _apiKeyRepository.FindFirst(w => w.ApiKeyId == apiKeyId && !w.Revoked); } public async Task GetApiKey(string apiKeyId) { var apiKeyGuid = Guid.Parse(apiKeyId); return await _apiKeyRepository.FindFirst(w => w.ApiKeyId == apiKeyGuid && !w.Revoked); } public async Task IsNotRevoked(Guid apiKeyId) { return await _apiKeyRepository.Exists(f => f.ApiKeyId == apiKeyId && !f.Revoked); } public async Task RevokeApiKey(Guid apiKeyId) { var apiKey = await _apiKeyRepository.FindFirst(w => w.ApiKeyId == apiKeyId); apiKey.Revoked = true; apiKey.ModifiedAt = _dateTimeProvider.GetSouthAfricanDateTime(); await _apiKeyRepository.Update(); } public async Task ReinstateApiKey(Guid apiKeyId) { var apiKey = await _apiKeyRepository.FindFirst(w => w.ApiKeyId == apiKeyId); apiKey.Revoked = false; apiKey.ModifiedAt = _dateTimeProvider.GetSouthAfricanDateTime(); await _apiKeyRepository.Update(); } }