using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using FrameworkDAL.DTO.User;
using FrameworkDAL.Query.SessionStore;
using FrameworkDAL.Query.UserLogin;
using GB5Shared.Connection;
using GB5Shared.DTO.Framework.CommonConfig;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using Npgsql;
using static GB5Shared.GB5Constant.Constant;
namespace FrameworkDAL.CustomCode.UserLogin
{
///
/// Queries MSESSIONSTORE in the GB5 system database to return active sessions.
/// Does NOT use IQueryExecutor (which routes to tenant DBs).
///
public class LoggedInUsersDAL : ILoggedInUsersDAL
{
private readonly IApplicationConnection _appConnection;
private readonly IOptionsMonitor _systemDto;
public LoggedInUsersDAL(
IApplicationConnection appConnection,
IOptionsMonitor systemDto)
{
_appConnection = appConnection;
_systemDto = systemDto;
}
public async Task> GetLoggedInUsersAsync(CancellationToken ct = default)
{
string connStr = await _appConnection.Gb5SystemConnectionString().ConfigureAwait(false);
int dbType = _systemDto.CurrentValue.DataBaseType;
string sql = dbType == DBTYPE.POSTGRESQL
? LoggedInUsersDashboardQB.GET_LOGGED_IN_USERS_POSTGRESQL
: LoggedInUsersDashboardQB.GET_LOGGED_IN_USERS_SQL;
using IDbConnection conn = dbType == DBTYPE.POSTGRESQL
? new NpgsqlConnection(connStr)
: (IDbConnection)new SqlConnection(connStr);
return await conn.QueryAsync(
new CommandDefinition(sql, cancellationToken: ct)).ConfigureAwait(false);
}
public async Task ForceLogoutAsync(int loginEventLogId, int serverConfigId, CancellationToken ct = default)
{
string connStr = await _appConnection.Gb5SystemConnectionString().ConfigureAwait(false);
int dbType = _systemDto.CurrentValue.DataBaseType;
using IDbConnection conn = dbType == DBTYPE.POSTGRESQL
? new NpgsqlConnection(connStr)
: (IDbConnection)new SqlConnection(connStr);
return await conn.ExecuteAsync(
new CommandDefinition(
SessionStoreQB.DELETE_SESSION,
new { ServerconfigId = serverConfigId, LoginEventLogId = loginEventLogId },
cancellationToken: ct)).ConfigureAwait(false);
}
}
}