76 lines
2.5 KiB
C#
76 lines
2.5 KiB
C#
using Core.Entities.Users;
|
|
using Insight.Database;
|
|
using System.Data;
|
|
|
|
namespace Database.IdentitySystem
|
|
{
|
|
public class UserService
|
|
{
|
|
private readonly IDbConnection _db;
|
|
|
|
public UserService(IDbConnection db)
|
|
{
|
|
_db = db;
|
|
}
|
|
|
|
public async Task CreateUserWithTenant(string email, string password, string tenantConnectionString)
|
|
{
|
|
var schema = "dev";
|
|
|
|
if (_db.State != ConnectionState.Open)
|
|
_db.Open();
|
|
|
|
using var transaction = _db.BeginTransaction();
|
|
try
|
|
{
|
|
// Create user
|
|
var user = new User
|
|
{
|
|
Email = email,
|
|
PasswordHash = PasswordHasher.HashPassword(password),
|
|
SecurityStamp = Guid.NewGuid().ToString(),
|
|
EmailConfirmed = false,
|
|
CreatedDate = DateTime.UtcNow
|
|
};
|
|
|
|
var userId = await _db.ExecuteScalarAsync<int>(@$"
|
|
INSERT INTO {schema}.users (email, password_hash, security_stamp, email_confirmed, created_date)
|
|
VALUES (@Email, @PasswordHash, @SecurityStamp, @EmailConfirmed, @CreatedDate)
|
|
RETURNING id", user);
|
|
|
|
// Create tenant
|
|
var tenant = new Tenant
|
|
{
|
|
ConnectionString = tenantConnectionString,
|
|
CreatedDate = DateTime.UtcNow,
|
|
CreatedBy = userId,
|
|
IsActive = true
|
|
};
|
|
|
|
var tenantId = await _db.ExecuteScalarAsync<int>(@$"
|
|
INSERT INTO {schema}.tenants (connection_string, created_date, created_by, is_active)
|
|
VALUES (@ConnectionString, @CreatedDate, @CreatedBy, @IsActive)
|
|
RETURNING id", tenant);
|
|
|
|
// Link user to tenant
|
|
var userTenant = new UserTenant
|
|
{
|
|
UserId = userId,
|
|
TenantId = tenantId,
|
|
CreatedDate = DateTime.UtcNow
|
|
};
|
|
|
|
await _db.ExecuteAsync(@$"
|
|
INSERT INTO {schema}.user_tenants (user_id, tenant_id, created_date)
|
|
VALUES (@UserId, @TenantId, @CreatedDate)", userTenant);
|
|
|
|
transaction.Commit();
|
|
}
|
|
catch
|
|
{
|
|
transaction.Rollback();
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|