BusinessMgr

This commit is contained in:
Andy Howard
2025-01-09 16:31:16 +00:00
parent 4005870236
commit 4f91faae8b
30 changed files with 475 additions and 265 deletions
+78 -1
View File
@@ -61,6 +61,83 @@ namespace Sarand.Net.Standard.Dbas.Base
public abstract int GetNextIdFromTable(string objectName, string idColumn = "Id");
public abstract bool SetMinNextId(String objectName, SysId id, DbUpdateInfo dbUpdateInfo, bool databaseTable = true, String idColumn = "Id", bool force = false);
//-------------------------------------------------------------------
// Password utilities.
//-------------------------------------------------------------------
/// <summary>
/// Generate password hash using the specified method.
/// <para>- Returns hex notation as a string.</para>
/// </summary>
/// <param name="password"></param>
/// <returns>String of hex digits corresponding to encrypted password.</returns>
public String EncodePassword_Hex(String password, ISacsDatabase.PasswordHashMethod method = ISacsDatabase.PasswordHashMethod.MsSql)
{
ClearErrorState();
if (method == ISacsDatabase.PasswordHashMethod.MsSql)
{
if (DbmsType == DbmsType.MsSql)
{
try
{
String colAlias = "DataValue";
String query = $"Select {colAlias}=Convert(VarChar(2000),PwdEncrypt('{DbQuery.FormatForCondition(password)}'),2);";
using (DbResultSet dbResultSet = DbResultSet_DataReader.ExecuteQuery(this, query))
{
if (dbResultSet.NextRecord())
return dbResultSet.GetRecordValues().GetValue(colAlias).ToString();
else if (dbResultSet.HasErrorState())
SetErrorState(dbResultSet.ErrorStateMessage);
}
}
catch (Exception exc)
{
SaLogger.Error($"{SysUtil.Fn} {ExceptionUtil.GetLogMessage(exc, "hashing password")}", true);
SetErrorState(exc.Message);
}
}
else SaLogger.Warn($"{SysUtil.Fn} Unable to encode password by method 'SQL'. Database is '{DbmsType}'.");
}
else SaLogger.Warn($"{SysUtil.Fn} Unable to encode password. Unrecognised method: '{method}'.");
return "";
}
/// <summary>
/// Compare the password to the encrypted hash using the specified method.
/// </summary>
/// <param name="password"></param>
/// <param name="passwordHashHex"></param>
/// <returns>True if the password matches the encrypted hash value.</returns>
public bool ComparePassword_Hex(String password, String passwordHashHex, ISacsDatabase.PasswordHashMethod method = ISacsDatabase.PasswordHashMethod.MsSql)
{
ClearErrorState();
if (method == ISacsDatabase.PasswordHashMethod.MsSql)
{
if (DbmsType == DbmsType.MsSql)
{
try
{
String colAlias = "PwdCompare";
String query = $"Select {colAlias}=PwdCompare('{DbQuery.FormatForCondition(password)}', Convert(VarBinary(1000),'{DbQuery.FormatForCondition(passwordHashHex)}',2));";
using (DbResultSet dbResultSet = DbResultSet_DataReader.ExecuteQuery(this, query))
{
if (dbResultSet.NextRecord())
return StringUtil.ToBool(dbResultSet.GetRecordValues().GetValue(colAlias).ToString());
else if (dbResultSet.HasErrorState())
SetErrorState(dbResultSet.ErrorStateMessage);
}
}
catch (Exception exc)
{
SaLogger.Error($"{SysUtil.Fn} {ExceptionUtil.GetLogMessage(exc, "comparing password")}", true);
SetErrorState(exc.Message);
}
}
else SaLogger.Warn($"{SysUtil.Fn} Unable to compare password by method 'SQL'. Database is '{DbmsType}'.");
}
else SaLogger.Warn($"{SysUtil.Fn} Unable to compare password. Unrecognised method: '{method}'.");
return false;
}
//-------------------------------------------------------------------
// O D B C D r i v e r s
//-------------------------------------------------------------------
@@ -184,7 +261,7 @@ namespace Sarand.Net.Standard.Dbas.Base
}
return "";
}
public abstract IDbDataTable ExecuteQuery(String query);
public abstract DbResultSet ExecuteQuery(String query);
public abstract int ExecuteNonQuery(String query);
public abstract int ExecuteInsert(String tableName, List<StringPair> columnNameValues);
public abstract int ExecuteUpdate(String tableName, List<StringPair> columnNameValues, String filter);
@@ -17,9 +17,9 @@ namespace Sarand.Net.Standard.Dbas.Base
// Database configuration
public class OdbcConfig
{
public DbmsType dbms = DbmsType.General;
public String connectionString; // Raw connection string.
public String location, user, pword; // Application properties.
public DbmsType Dbms = DbmsType.General;
public String ConnectionString; // Raw connection string.
public String Location, User, Password; // Connection properties.
/// <summary>Database name populated when connection string is generated if not done previously.</summary>
public String DatabaseName { get; set; }
}
@@ -42,9 +42,9 @@ namespace Sarand.Net.Standard.Dbas.Base
//-------------------------------------------------------------------
public static DbmsType GetDbmsType(OdbcConfig config)
{
if (config.dbms == DbmsType.MsSql || config.location.Left(6).EqualsCI("MsSql:"))
if (config.Dbms == DbmsType.MsSql || config.Location.Left(6).EqualsCI("MsSql:"))
return DbmsType.MsSql;
return config.dbms;
return config.Dbms;
}
public static String GenerateConnectionString(OdbcConfig config, bool dbmsSpecificConnectionString = false)
{
@@ -58,7 +58,7 @@ namespace Sarand.Net.Standard.Dbas.Base
// MsSql:Server:Port\Instance.Database
dbms = DbmsType.MsSql;
String sqlDriver = OdbcUtil.GetOdbcSqlDriverName();
String sqlLocation = config.location.Left(6).EqualsCI("MsSql:") ? config.location.Substring(6) : config.location;
String sqlLocation = config.Location.Left(6).EqualsCI("MsSql:") ? config.Location.Substring(6) : config.Location;
String sqlServer = "."; /* Assume local host */
String sqlInstance = "";
String sqlPort = "";
@@ -99,17 +99,17 @@ namespace Sarand.Net.Standard.Dbas.Base
// WsId=<WorkstationId>;
// Server=[protocol:]Server[,port][\instancename];
// Database=<Default database>;
// Trusted_Connection=<Yes|No>;
// Trusted_Connection=<Yes|No>; [or Integrated Security=SSPI;]
// UseProcForPrepare=2
connectionString = "Driver={" + sqlDriver + "};";
connectionString += "Server=" + sqlServer + ";";
connectionString += "Database=" + sqlDatabase + ";";
if (!config.user.IsEmpty())
if (!config.User.IsEmpty())
{
connectionString += "UID=" + config.user + ";";
connectionString += "PWD=" + config.pword + ";";
connectionString += "UID=" + config.User + ";";
connectionString += "PWD=" + config.Password + ";";
}
connectionString += "Trusted_Connection=" + (config.user.IsEmpty() ? "Yes" : "No") + ";";
connectionString += "Trusted_Connection=" + (config.User.IsEmpty() ? "Yes" : "No") + ";";
// Mar24 Added to avoid 'The certificate chain was issued by an authority that is not trusted'.
connectionString += "TrustServerCertificate=Yes;";
// Multiple Active Result Sets.
@@ -125,23 +125,23 @@ namespace Sarand.Net.Standard.Dbas.Base
connectionString = "";
connectionString += "Server=" + sqlServer + ";";
connectionString += "Database=" + sqlDatabase + ";";
if (!config.user.IsEmpty())
if (!config.User.IsEmpty())
{
connectionString += "User Id=" + config.user + ";";
connectionString += "Password=" + config.pword + ";";
connectionString += "User Id=" + config.User + ";";
connectionString += "Password=" + config.Password + ";";
}
connectionString += "Trusted_Connection=" + (config.user.IsEmpty() ? "Yes" : "No") + ";";
connectionString += "Trusted_Connection=" + (config.User.IsEmpty() ? "Yes" : "No") + ";";
// Mar24 Added to avoid 'The certificate chain was issued by an authority that is not trusted'.
connectionString += "TrustServerCertificate=Yes;";
}
// Populate configuration values if blank.
if (config.dbms <= 0)
config.dbms = dbms;
if (config.Dbms <= 0)
config.Dbms = dbms;
if (StringUtil.IsEmpty(config.DatabaseName))
config.DatabaseName = sqlDatabase;
SaLogger.Info($"{SysUtil.Fn} Driver: " + sqlDriver + ". Server: " + sqlServer + ". Database: " + sqlDatabase + ". Connection: " + connectionString);
//SaLogger.Debug($"{SysUtil.Fn} Driver: " + sqlDriver + ". Server: " + sqlServer + ". Database: " + sqlDatabase + ". Connection: " + connectionString);
}
return connectionString;
}
@@ -152,17 +152,17 @@ namespace Sarand.Net.Standard.Dbas.Base
public static SacsDatabase OpenOdbcDatabase(OdbcConfig config)
{
// Populate configuration.
config.dbms = GetDbmsType(config);
config.Dbms = GetDbmsType(config);
// Connection strings.
String connectionString = config.connectionString;
String connectionString = config.ConnectionString;
if (StringUtil.IsEmpty(connectionString))
connectionString = GenerateConnectionString(config);
String sqlConnectionString = GenerateConnectionString(config, true);
// Open database.
DbGlobalDbms.Type = config.dbms;
SacsDatabaseOdbc database = new SacsDatabaseOdbc(config.dbms, config.DatabaseName, connectionString);
DbGlobalDbms.Type = config.Dbms;
SacsDatabaseOdbc database = new SacsDatabaseOdbc(config.Dbms, config.DatabaseName, connectionString);
database.SelectLockMode = SelectLockMode.ReadUncommitted;
database.SqlConnectionString = sqlConnectionString;
return database;
@@ -29,7 +29,7 @@ namespace Sarand.Net.Standard.Dbas.CodeType
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
-28
View File
@@ -1,28 +0,0 @@
using System.Data;
using Sarand.Net.Standard.Base.Dbas;
namespace Sarand.Net.Standard.Dbas.Data
{
//=======================================================================
/// <summary>
/// Wrapper for System.Data.DataTable
/// </summary>
public class DbDataTable : IDbDataTable
{
//-------------------------------------------------------------------
// Data members.
private DataTable dataTable;
//-------------------------------------------------------------------
// Construction.
public DbDataTable (DataTable dataTable)
{
this.dataTable = dataTable;
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
}
//=======================================================================
}
+3 -12
View File
@@ -171,29 +171,20 @@ namespace Sarand.Net.Standard.Dbas.Data
// Q u e r y D a t a b a s e
//-------------------------------------------------------------------
// Query records.
public override IDbDataTable ExecuteQuery(String query)
public override DbResultSet ExecuteQuery(String query)
{
ClearErrorState();
DataTable dataTable = null;
Log(SysUtil.Fn, "Query: " + query, SaMessageLevel.Debug);
try
{
using (DbConnection dbConnection = CreateConnection())
using (var dbCommand = dbConnection.CreateCommand())
{
dbConnection.Open();
dbCommand.CommandType = System.Data.CommandType.Text;
dbCommand.CommandText = query;
dataTable = new DataTable();
dataTable.Load(dbCommand.ExecuteReader());
}
return DbResultSet_DataReader.ExecuteQuery(this, query);
}
catch (Exception exc)
{
SaLogger.Error($"{SysUtil.Fn} {ExceptionUtil.GetLogMessage(exc)}\nQuery:\n\t{String.Join("\n\t", query.ReplaceAll("\n\r", "\n").Split("\n"))}", true);
SetErrorState(exc.Message);
}
return new DbDataTable(dataTable);
return null;
}
//-------------------------------------------------------------------
/// <summary>Execute a non-query statement and return the row count.</summary>
@@ -32,7 +32,7 @@ namespace Sarand.Net.Standard.Dbas.Interface
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
@@ -31,7 +31,7 @@ namespace Sarand.Net.Standard.Dbas.ItemData
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
@@ -35,7 +35,7 @@ namespace Sarand.Net.Standard.Dbas.ItemDocs
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
@@ -31,7 +31,7 @@ namespace Sarand.Net.Standard.Dbas.ItemOptions
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
@@ -31,7 +31,7 @@ namespace Sarand.Net.Standard.Dbas.ReferenceData
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
@@ -73,6 +73,28 @@ namespace Sarand.Net.Standard.Dbas.Security
}
//-------------------------------------------------------------------
// Password utilities.
//-------------------------------------------------------------------
/// <summary>Store the password against against the user.</summary>
public override bool SetPassword(SaSecurityItem securityItemUser, String password)
{
return securityMgr.SetPassword(securityItemUser, password);
}
/// <summary>Does the password match that currently defined against the user.</summary>
public override bool PasswordMatches(SaSecurityItem securityItemUser, String password)
{
return securityMgr.PasswordMatches(securityItemUser, password);
}
/// <summary>Is the password currently defined against the user blank.</summary>
public override bool PasswordIsBlank(SaSecurityItem securityItemUser)
{
return securityMgr.PasswordIsBlank(securityItemUser);
}
/// <summary>Change Password form - desktop only.</summary>
public override bool ShowChangePasswordForm(DbUpdateInfo dbUpdateInfo)
{
ClearErrorState();
@@ -112,16 +134,16 @@ namespace Sarand.Net.Standard.Dbas.Security
if (!HasErrorState()) PopulateSuperGroup(dbUpdateInfo);
// Create the 'admin' user.
if (!HasErrorState()) PopulateAdminUser(dbUpdateInfo);
return !HasErrorState();
return OK;
}
private bool PopulateSuperGroup(DbUpdateInfo dbUpdateInfo)
{
ClearErrorState();
SaSecurityItem superGroup = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.Group, GroupSuperCode);
SaSecurityItem superGroup = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.Group, GroupCode_Super);
if (superGroup == null)
{
superGroup = securityMgr.CreateSecurityItem(SaSecurity.ItemType.Group);
superGroup.Code = GroupSuperCode;
superGroup.Code = GroupCode_Super;
superGroup.Description = "Superuser";
if (!securityMgr.InsertSecurityItem(superGroup, dbUpdateInfo))
return SetErrorState(securityMgr.ErrorStateMessage);
@@ -143,29 +165,29 @@ namespace Sarand.Net.Standard.Dbas.Security
}
}
}
return !HasErrorState();
return OK;
}
private bool PopulateAdminUser(DbUpdateInfo dbUpdateInfo)
{
ClearErrorState();
SaSecurityItem user = null;
if (!securityMgr.SecurityItemExistsByTypeCode(SaSecurity.ItemType.User, AdminUserCode))
if (!securityMgr.SecurityItemExistsByTypeCode(SaSecurity.ItemType.User, UserCode_Admin))
{
// Create the admin user.
user = securityMgr.CreateSecurityItem(SaSecurity.ItemType.User);
user.Code = AdminUserCode;
user.Code = UserCode_Admin;
user.Description = "<Admin>";
user.Location = "<System>";
user.PasswordEncrypted = SaSecurityItem.EncryptPassword(AdminUserCode);
securityMgr.SetPassword(user, UserCode_Admin);
if (!securityMgr.InsertSecurityItem(user, dbUpdateInfo))
return SetErrorState(securityMgr.ErrorStateMessage);
}
// Retrieve the user (even if just created).
user = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.User, AdminUserCode);
user = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.User, UserCode_Admin);
if (user != null)
{
// Give this user superuser rights.
SaSecurityItem superGroup = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.Group, GroupSuperCode);
SaSecurityItem superGroup = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.Group, GroupCode_Super);
if (superGroup != null)
{
if (!securityMgr.SecurityItemHasLinksWith(user.Id, superGroup.Id))
@@ -176,7 +198,7 @@ namespace Sarand.Net.Standard.Dbas.Security
}
}
}
return !HasErrorState();
return OK;
}
//-------------------------------------------------------------------
@@ -234,7 +256,7 @@ namespace Sarand.Net.Standard.Dbas.Security
}
OnLogin(secItem != null ? secItem.Id : null);
return !HasErrorState();
return OK;
}
//-------------------------------------------------------------------
@@ -534,19 +556,35 @@ namespace Sarand.Net.Standard.Dbas.Security
if (!securityMgr.InsertSecurityItem(secItem, dbUpdateInfo))
return SetErrorState(securityMgr.ErrorStateMessage);
return !HasErrorState();
return OK;
}
public override bool AssignUserToGroup(string userCode, string groupCode, DbUpdateInfo dbUpdateInfo)
{
ClearErrorState();
throw new NotImplementedException();
// Validate environment.
if (securityMgr == null) return SetErrorState("security manager is not available");
if (!securityMgr.DatabaseIsValid) return SetErrorState("database has an invalid security profile");
// User security item.
SaSecurityItem securityItemUser = securityMgr.GetSecurityItemByTypeCode(SaSecurity.ItemType.User, userCode);
if (securityItemUser == null) return SetErrorState(("user does not exist"));
// Group security item.
SysId securityGroupId = GetIdForItemCode(SaSecurity.ItemType.Group, groupCode);
if (!SysId.IsValid(securityGroupId)) return SetErrorState(("invalid group code"));
if (!ItemsAreLinked(securityItemUser.Id, securityGroupId))
{
SaSecurityLink securityLinkUserGroup = securityMgr.CreateSecurityLink(securityItemUser.Id, securityGroupId, new SysId());
if (securityLinkUserGroup == null) return SetErrorState($"failed to create user-group ({securityMgr.ErrorStateMessage})");
if (!securityMgr.InsertSecurityLink(securityLinkUserGroup, dbUpdateInfo))
return SetErrorState($"failed to add user to group ({securityMgr.ErrorStateMessage})");
}
return OK;
}
public override bool UpdateSecurityItem(SaSecurityItem securityItem, DbUpdateInfo dbUpdateInfo)
{
ClearErrorState();
if (!securityMgr.UpdateSecurityItem(securityItem, dbUpdateInfo))
return SetErrorState(securityMgr.ErrorStateMessage);
return !HasErrorState();
return OK;
}
//-------------------------------------------------------------------
@@ -31,7 +31,7 @@ namespace Sarand.Net.Standard.Dbas.Security
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.
@@ -278,7 +278,9 @@ namespace Sarand.Net.Standard.Dbas.Security
dbSecurityItem._Code = securityItem.Code;
dbSecurityItem._Description = securityItem.Description;
dbSecurityItem._Location = securityItem.Location;
#pragma warning disable CS0618 // Deprecated property
dbSecurityItem._EncPword = securityItem.PasswordEncrypted;
#pragma warning restore CS0618 // Deprecated property
dbSecurityItem._PwordSalt = securityItem.PasswordSalt;
dbSecurityItem._PwordHash = securityItem.PasswordHash;
dbSecurityItem._LastLogin = securityItem.LastLogin;
@@ -304,7 +306,9 @@ namespace Sarand.Net.Standard.Dbas.Security
securityItem.EmailAddress = dbSecurityItem._EmailAddress;
securityItem.Description = dbSecurityItem._Description;
securityItem.Location = dbSecurityItem._Location;
#pragma warning disable CS0618 // Deprecated property
securityItem.PasswordEncrypted = dbSecurityItem._EncPword;
#pragma warning restore CS0618 // Deprecated property
securityItem.PasswordSalt = dbSecurityItem._PwordSalt;
securityItem.PasswordHash = dbSecurityItem._PwordHash;
securityItem.LastLogin = dbSecurityItem._LastLogin;
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Dbas;
using Sarand.Net.Standard.Base.Security;
using Sarand.Net.Standard.Dbas.Data;
@@ -15,7 +17,7 @@ namespace Sarand.Net.Standard.Dbas.Security
//-------------------------------------------------------------------
// Construction.
internal SaSecurityMgr_Dbas (SaSecurityConsole_Dbas securityConsole) : base()
internal SaSecurityMgr_Dbas(SaSecurityConsole_Dbas securityConsole) : base()
{
SecurityConsole = securityConsole;
DbInfo = new DbDataItem.DatabaseInfo(securityConsole.Database);
@@ -31,15 +33,109 @@ namespace Sarand.Net.Standard.Dbas.Security
public override bool DatabaseIsValid { get { return (Database != null && Database.GetTableNames().Contains(TableName_SecItem) && Database.GetTableNames().Contains(TableName_SecLink)); } }
public override bool CanUpdateDatabase { get { return DatabaseIsValid; } }
//-------------------------------------------------------------------
// Utilities.
public override bool ColumnExists (SaSecurityDbDfn.ColumnIdx columnIdx)
// Database utilities.
public override bool ColumnExists(SaSecurityDbDfn.ColumnIdx columnIdx)
{
String tableName = SaSecurityDbDfn.GetTableName(SaSecurityDbDfn.GetTableForColumn(columnIdx), false);
String columnName = SaSecurityDbDfn.GetColumnName(columnIdx, false);
return Database.ColumnExists(tableName, columnName);
}
//-------------------------------------------------------------------
// Password utilities.
public override bool PasswordIsBlank(SaSecurityItem securityItemUser)
{
if (securityItemUser == null) return false;
SaSecurity.PasswordMethod method = securityItemUser.GetPasswordMethod();
// MsSql method.
if (method == SaSecurity.PasswordMethod.MsSql)
{
//...
}
// Legacy.
#pragma warning disable CS0618 // Deprecated property
return EncryptPassword_Legacy("").Equals(securityItemUser.PasswordEncrypted);
#pragma warning restore CS0618 // Deprecated property
}
public override bool PasswordMatches(SaSecurityItem securityItemUser, String password)
{
if (securityItemUser == null) return false;
SaSecurity.PasswordMethod method = securityItemUser.GetPasswordMethod();
// MsSql method.
if (method == SaSecurity.PasswordMethod.MsSql)
{
//...
}
// Legacy.
#pragma warning disable CS0618 // Deprecated property
return (EncryptPassword_Legacy(password).Equals(securityItemUser.PasswordEncrypted));
#pragma warning restore CS0618 // Deprecated property
}
/// <summary>Store the password against against the user.</summary>
public override bool SetPassword(SaSecurityItem securityItemUser, String password)
{
return false;
}
internal static String EncryptPassword_Legacy(String password)
{
// We know this is not very water-tight, but it at least
// hides the contents of the password from prying eyes.
String toBeEncrypted = password;
// Password length goes in as first character:
toBeEncrypted = ByteToString((byte)(128 - password.Length)) + toBeEncrypted;
toBeEncrypted = string.Concat(toBeEncrypted.Reverse());
// Pad out to fixed length (minimum 16, multiples of 8):
int fixedLength = 16;
if (password.Length / 8 > 2) fixedLength = 8 * (int)(password.Length / 8);
while (toBeEncrypted.Length < fixedLength)
{
char charToAdd = (char)(password.Length > 0 ? password[(toBeEncrypted.Length % password.Length)] : 'A' + (toBeEncrypted.Length * 13) % 23);
if (toBeEncrypted.Length % 2 != 0)
toBeEncrypted += charToAdd;
else toBeEncrypted = charToAdd + toBeEncrypted;
}
// Now perform a simple algorythm on each character to hide its true value:
byte[] encryptedChars = new byte[toBeEncrypted.Length];
for (int i = 0; i < toBeEncrypted.Length; i++)
{
int iData = toBeEncrypted[i];
iData += 17 + i;
if (iData > 255) iData -= (255 + 32);
encryptedChars[i] = (byte)iData;
}
String result = Encoding_Ansi1252.GetString(encryptedChars);
#if DEBUG
// Password: mgbgt
// To encrypt: tbmggtgbgm{btggm
// Encrypted: 133, 116, 128, 123, 124, 138, 126, 122, 128, 135, 150, 126, 145, 133, 134, 141
//Logger.Info(fn + "\n\tPassword: " + password + "\n\tTo encrypt: " + toBeEncrypted + "\n\tEncrypted: " + encryptedChars.Select(i => i.ToString()).ToList().Concat(", "));
//Logger.Debug(password + ": " + result);
#endif
return result;
}
private static byte[] PasswordStringToBytes(String value)
{
byte[] values = new byte[value.Length];
for (int idx = 0; idx < value.Length; idx++)
{
char c = value[idx];
UInt32 ui = Convert.ToUInt32(c);
SaLogger.Info(idx + ". " + ui.ToString("x8"));
values[idx] = (byte)(c);
}
return values;
}
private static readonly Encoding Encoding_Ansi1252 = Encoding.GetEncoding(1252);
private static String ByteToString(byte value)
{
return Encoding_Ansi1252.GetString(new[] { value });
}
//-------------------------------------------------------------------
}
//=======================================================================
@@ -31,7 +31,7 @@ namespace Sarand.Net.Standard.Dbas.UpdateLog
// Open database.
// NB Must be ODBC connection - especially to retrieve index columns.
SacsDatabaseConsole.OdbcConfig config = new SacsDatabaseConsole.OdbcConfig();
config.connectionString = connectionString;
config.ConnectionString = connectionString;
SacsDatabase database = SacsDatabaseConsole.OpenOdbcDatabase(config);
// Generate database definition.