Files
magman/MagMan.Data.Admin/DbAdmin.cs
T
2024-01-11 17:26:49 +01:00

93 lines
2.6 KiB
C#

using Microsoft.EntityFrameworkCore;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagMan.Data.Admin
{
/// <summary>
/// Classe amministrazione Db principale:
/// - creazione utenti sul Server MySql
/// - gestione DB/Tabele x identity & gestione multi-tenant
/// </summary>
public class DbAdmin : IDisposable
{
#region Private Fields
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
#region Public Constructors
public DbAdmin()
{
}
#endregion Public Constructors
#region Public Methods
public static bool CheckCreateUser(string username, string pwd, string dbName)
{
bool answ = false;
using (ServerAdminContext adbCtx = new ServerAdminContext())
{
// ricerca utente...
var numUser = adbCtx
.UserList
.Where(x => x.User == username)
.ToList()
.Count;
if (numUser > 0)
{
answ = true;
}
if (!answ)
{
// creo utente
string sqlCommand = "FLUSH PRIVILEGES;";
adbCtx.Database.ExecuteSqlRaw(sqlCommand);
sqlCommand = $"CREATE USER '{username}'@'localhost' IDENTIFIED BY '{pwd}';";
adbCtx.Database.ExecuteSqlRaw(sqlCommand);
sqlCommand = $"GRANT ALL ON *.* TO '{username}'@'localhost';";
adbCtx.Database.ExecuteSqlRaw(sqlCommand);
sqlCommand = "FLUSH PRIVILEGES;";
adbCtx.Database.ExecuteSqlRaw(sqlCommand);
}
}
return answ;
}
public static async Task<bool> MigrateDbIdentity()
{
bool answ = false;
using (IdentityContext dbCtx = new IdentityContext())
{
await dbCtx.Database.MigrateAsync();
answ = true;
}
return answ;
}
public static async Task<bool> MigrateDbMultiTenant()
{
bool answ = false;
using (MultiTenantContext dbCtx = new MultiTenantContext())
{
await dbCtx.Database.MigrateAsync();
answ = true;
}
return answ;
}
public void Dispose()
{
}
#endregion Public Methods
}
}