Taylohtio/IDP/webapi/webapi.Infrastructure.Common/Repositories/UserAuthRepository.cs

216 lines
8.3 KiB
C#

using Microsoft.Azure.CosmosDB.Table;
using Microsoft.Azure.Storage;
using Serilog;
using System;
using System.Linq;
using System.Threading.Tasks;
using webapi.Domain.Events;
using webapi.Domain.Model;
using webapi.Exceptions;
using webapi.Infractructure.Core;
using webapi.Infrastructure.Core;
namespace webapi.Infrastructure.Repositories
{
public class UserAuthRepository: BaseAzureRepository<UserAuth>, IUserAuthRepository
{
//public static CloudStorageAccount CreateStorageAccountFromConnectionString(string storageConnectionString)
//{
// CloudStorageAccount storageAccount;
// try
// {
// storageAccount = CloudStorageAccount.Parse(storageConnectionString);
// }
// catch (FormatException)
// {
// Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the application.");
// throw;
// }
// catch (ArgumentException)
// {
// Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample.");
// Console.ReadLine();
// throw;
// }
// return storageAccount;
//}
//public static async Task<CloudTable> CreateTableAsync(string tableName)
//{
// string storageConnectionString = ConfigurationManager.ConnectionStrings["AzureProdConnectionString"].ConnectionString; //AppSettings.LoadAppSettings().StorageConnectionString;
// // Retrieve storage account information from connection string.
// CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString);
// // Create a table client for interacting with the table service
// CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableConnectionPolicy() { UseDirectMode = false }); // new TableClientConfiguration());
// // Create a table client for interacting with the table service
// CloudTable table = tableClient.GetTableReference(tableName);
// if (await table.CreateIfNotExistsAsync())
// {
// //Console.WriteLine("Created Table named: {0}", tableName);
// }
// else
// {
// //Console.WriteLine("Table {0} already exists", tableName);
// }
// return table;
//}
public UserAuthRepository(ILogger log, string storageConnectionString, EventsHandlerFactory eventsFactory) :
base(log, storageConnectionString, eventsFactory)
{}
public UserAuth GetUserByTaloyhtioUserId(Guid taloyhtioUserId) {
_log.Information($"Start GetUserByTaloyhtioUserId");
if (Guid.Empty.Equals(taloyhtioUserId)) throw new ArgumentNullException(nameof(taloyhtioUserId));
try
{
var query = _table.CreateQuery<UserAuth>()
.Where(d => d.TaloyhtioUserId == taloyhtioUserId);
_log.Information($"End GetUserByTaloyhtioUserId");
return query.FirstOrDefault();
}
catch (StorageException e)
{
throw e;
}
}
public async Task<UserAuth> RetrieveEntityUsingPointQueryAsync(string partitionKey, string rowKey)
{
try
{
TableOperation retrieveOperation = TableOperation.Retrieve<UserAuth>(partitionKey, rowKey);
TableResult result = await _table.ExecuteAsync(retrieveOperation);
UserAuth userAuth = result.Result as UserAuth;
if (userAuth != null)
{
//Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);
}
// Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB
//if (result.RequestCharge.HasValue)
//{
// //Console.WriteLine("Request Charge of Retrieve Operation: " + result.RequestCharge);
//}
return userAuth;
}
catch (StorageException e)
{
//Console.WriteLine(e.Message);
//Console.ReadLine();
throw e;
}
}
public async Task<UserAuth> InsertOrMergeEntityAsync(UserAuth entity)
{
_log.Information($"Start InsertOrMergeEntityAsync");
if (entity == null)
{
_log.Error($"{nameof(entity)} is null");
throw new ArgumentNullException(nameof(entity));
}
try
{
//Imlemented in base class
//_log.Information($"Check UserAuth table");
//await UserAuthRepository.CreateTableAsync(typeof(UserAuth).Name);
// Create the InsertOrReplace table operation
TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);
_log.Information($"Execute the operation.");
TableResult result = await _table.ExecuteAsync(insertOrMergeOperation);
var insertedCustomer = result.Result as UserAuth;
_log.Information($"End InsertOrMergeEntityAsync");
// Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure Cosmos DB
//if (result.RequestCharge.HasValue)
//{
// Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
//}
return insertedCustomer;
}
catch (StorageException e)
{
_log.Error($"Error InsertOrMergeEntityAsync StorageException {e.Message} {e.StackTrace} {e.InnerException}", e.Message);
throw e;
}
catch (Exception e)
{
_log.Error($"Error InsertOrMergeEntityAsync Exception {e.Message} {e.StackTrace} {e.InnerException}", e.Message);
throw e;
}
}
public UserAuth GetUserByPIN(string pin)
{
_log.Information($"Start GetUserByPIN");
if (string.IsNullOrEmpty(pin)) throw new ArgumentNullException(nameof(pin));
try
{
var query = _table.CreateQuery<UserAuth>()
.Where(d => pin.Equals(d.PINId));
_log.Information($"End GetUserByPIN");
return query.FirstOrDefault();
}
catch (StorageException e)
{
throw e;
}
}
public UserAuth GetByUserId(Guid userId)
{
_log.Information($"Start GetByUserId");
if (Guid.Empty.Equals(userId)) throw new WarningException(nameof(userId));
try
{
var query = _table.CreateQuery<UserAuth>()
.Where(d => userId.Equals(d.Id));
_log.Information($"End GetByUserId");
return query.FirstOrDefault();
}
catch (StorageException e)
{
throw e;
}
}
public UserAuth GetUserByEmail(string username)
{
//string sql = "select UserID from aspnet_Users where [LoweredUserName] = @username";
//string user_id = string.Empty;
//using (var cmd = Constants.Connection.CreateCommand())
//{
// cmd.CommandText = sql;
// cmd.Parameters.AddWithValue("@username", username);
// using (var reader = cmd.ExecuteReader())
// {
// if (!reader.Read())
// {
// return null;
// }
// user_id = reader["UserID"].ToString();
// }
//}
//return GetUserByTaloyhtioUserId(Guid.Parse(user_id));
return null;
}
}
}