예제 #1
0
        private static SUserRow LoadUser(String AUserID, out TPetraIdentity APetraIdentity, TDBTransaction ATransaction)
        {
            SUserRow   ReturnValue;
            SUserTable UserDT = null;
            SUserRow   UserDR;
            DateTime   LastLoginDateTime;
            DateTime   FailedLoginDateTime;

            // Check if user exists in s_user DB Table
            if (!SUserAccess.Exists(AUserID, ATransaction))
            {
                throw new EUserNotExistantException(StrInvalidUserIDPassword);
            }

            // User exists, so load User record
            UserDT = SUserAccess.LoadByPrimaryKey(AUserID, ATransaction);

            UserDR = UserDT[0];

            if (!UserDR.IsFailedLoginDateNull())
            {
                FailedLoginDateTime = UserDR.FailedLoginDate.Value;
                FailedLoginDateTime = FailedLoginDateTime.AddSeconds(Convert.ToDouble(UserDR.FailedLoginTime));
            }
            else
            {
                FailedLoginDateTime = DateTime.MinValue;
            }

            if (!UserDR.IsLastLoginDateNull())
            {
                LastLoginDateTime = UserDR.LastLoginDate.Value;
                LastLoginDateTime = LastLoginDateTime.AddSeconds(Convert.ToDouble(UserDR.LastLoginTime));
            }
            else
            {
                LastLoginDateTime = DateTime.MinValue;
            }

            Int64 PartnerKey;

            if (!UserDR.IsPartnerKeyNull())
            {
                PartnerKey = UserDR.PartnerKey;
            }
            else
            {
                // to make it not match PartnerKey 0, which might be stored in the DB or in a variable
                PartnerKey = -1;
            }

            // Create PetraIdentity
            APetraIdentity = new Ict.Petra.Shared.Security.TPetraIdentity(
                AUserID.ToUpper(), UserDR.LastName, UserDR.FirstName, UserDR.LanguageCode, UserDR.AcquisitionCode, DateTime.MinValue,
                LastLoginDateTime, FailedLoginDateTime, UserDR.FailedLogins, PartnerKey, UserDR.DefaultLedgerNumber, UserDR.AccountLocked,
                UserDR.Retired, UserDR.CanModify);
            ReturnValue = UserDR;

            return(ReturnValue);
        }
예제 #2
0
        private static Boolean SaveUser(String AUserID, SUserTable AUserDataTable)
        {
            TDBTransaction TheTransaction;

            if ((AUserDataTable != null) && (AUserDataTable.Rows.Count > 0))
            {
                TheTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

                try
                {
                    SUserAccess.SubmitChanges(AUserDataTable, TheTransaction);

                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured during the saving of a User:" + Environment.NewLine + Exc.ToString());

                    DBAccess.GDBAccessObj.RollbackTransaction();

                    throw;
                }
            }
            else
            {
                // nothing to save!
                return(false);
            }

            return(true);
        }
예제 #3
0
        public static bool SetUserPassword(string AUsername, string APassword, bool APasswordNeedsChanged)
        {
            string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                TPetraPrincipal tempPrincipal;
                SUserRow        UserDR    = TUserManagerWebConnector.LoadUser(AUsername.ToUpper(), out tempPrincipal);
                SUserTable      UserTable = (SUserTable)UserDR.Table;

                Random r = new Random();
                UserDR.PasswordSalt = r.Next(1000000000).ToString();
                UserDR.PasswordHash = TUserManagerWebConnector.CreateHashOfPassword(String.Concat(APassword,
                                                                                                  UserDR.PasswordSalt), "SHA1");
                UserDR.PasswordNeedsChange = APasswordNeedsChanged;

                TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);
                SUserAccess.SubmitChanges(UserTable, Transaction);

                DBAccess.GDBAccessObj.CommitTransaction();

                return(true);
            }
            else
            {
                IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                return(auth.SetPassword(AUsername, APassword));
            }
        }
예제 #4
0
        public static MaintainUsersTDS LoadUsersAndModulePermissions()
        {
            MaintainUsersTDS ReturnValue = null;

            Boolean        NewTransaction;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                                           TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            try
            {
                ReturnValue = new MaintainUsersTDS();
                SUserAccess.LoadAll(ReturnValue, Transaction);
                SUserModuleAccessPermissionAccess.LoadAll(ReturnValue, Transaction);
                SModuleAccess.LoadAll(ReturnValue, Transaction);
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);
                TLogging.Log(e.StackTrace);
                ReturnValue = null;
            }

            if (NewTransaction)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }

            return(ReturnValue);
        }
예제 #5
0
        public static MaintainUsersTDS LoadUsersAndModulePermissions()
        {
            TDBTransaction   ReadTransaction = null;
            MaintainUsersTDS ReturnValue     = new MaintainUsersTDS();

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref ReadTransaction,
                                                                      delegate
            {
                SUserAccess.LoadAll(ReturnValue, ReadTransaction);
                SUserModuleAccessPermissionAccess.LoadAll(ReturnValue, ReadTransaction);
                SModuleAccess.LoadAll(ReturnValue, ReadTransaction);
            });

            // Remove Password Hash and Password 'Salt' before passing it out to the caller - these aren't needed
            // and it is better to not hand them out needlessly to prevent possible 'eavesdropping' by an attacker
            // (who could otherwise gather the Password Hashes and Password 'Salts' of all users in one go if the
            // attacker manages to listen to network traffic). (#5502)!
            foreach (var UserRow in ReturnValue.SUser.Rows)
            {
                ((SUserRow)UserRow).PasswordHash = "****************";
                ((SUserRow)UserRow).PasswordSalt = "****************";
            }

            ReturnValue.AcceptChanges();

            return(ReturnValue);
        }
예제 #6
0
        /// <summary>
        /// get the datatable from the database
        /// </summary>
        /// <param name="ATableName">name of table to retrieve</param>
        /// <returns></returns>
        public DataTable GetData(string ATableName)
        {
            DataTable      table           = new DataTable();
            TDBTransaction ReadTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.RepeatableRead, 5);

            if (ATableName == SUserTable.GetTableDBName())
            {
                table = SUserAccess.LoadAll(ReadTransaction);
            }

            return(table);
        }
예제 #7
0
        /// <summary>
        /// Retrieves the e-mail address of the given user
        /// </summary>
        private static bool GetEmailOfUser(string AUserID, TDBTransaction ATransaction,
                                           out string AEmailAddress, out string ALanguageCode,
                                           out string AFirstName, out string ALastName)
        {
            SUserTable Users = SUserAccess.LoadByPrimaryKey(AUserID, ATransaction);

            AEmailAddress = Users[0].EmailAddress;
            ALanguageCode = Users[0].LanguageCode;
            AFirstName    = Users[0].FirstName;
            ALastName     = Users[0].LastName;

            return(true);
        }
예제 #8
0
        private static SUserRow LoadUser(String AUserID, TDBTransaction ATransaction)
        {
            // Check if user exists in s_user DB Table
            if (!SUserAccess.Exists(AUserID, ATransaction))
            {
                throw new EUserNotExistantException(StrInvalidUserIDPassword);
            }

            // User exists, so load User record
            SUserTable UserDT = SUserAccess.LoadByPrimaryKey(AUserID, ATransaction);

            return(UserDT[0]);
        }
예제 #9
0
        private DataTable GetUserListTable(TDBTransaction AReadTransaction, string ATableName)
        {
            DataColumn LastAndFirstNameColumn;
            DataTable  TmpTable = SUserAccess.LoadAll(AReadTransaction);

            // add column to display a combination of last and first name
            LastAndFirstNameColumn            = new DataColumn();
            LastAndFirstNameColumn.DataType   = System.Type.GetType("System.String");
            LastAndFirstNameColumn.ColumnName = MSysManConstants.USER_LAST_AND_FIRST_NAME_COLUMNNAME;
            LastAndFirstNameColumn.Expression = string.Format("{0} + ' ' + {1}", SUserTable.GetFirstNameDBName(), SUserTable.GetLastNameDBName());
            TmpTable.Columns.Add(LastAndFirstNameColumn);

            return(TmpTable);
        }
예제 #10
0
        public static MaintainUsersTDS LoadUsersAndModulePermissions()
        {
            TDBTransaction   ReadTransaction = null;
            MaintainUsersTDS ReturnValue     = new MaintainUsersTDS();

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                                      TEnforceIsolationLevel.eilMinimum,
                                                                      ref ReadTransaction,
                                                                      delegate
            {
                SUserAccess.LoadAll(ReturnValue, ReadTransaction);
                SUserModuleAccessPermissionAccess.LoadAll(ReturnValue, ReadTransaction);
                SModuleAccess.LoadAll(ReturnValue, ReadTransaction);
            });

            return(ReturnValue);
        }
예제 #11
0
        public static bool SetUserPassword(string AUsername, string APassword, bool APasswordNeedsChanged, bool AUnretireIfRetired)
        {
            string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                TDBTransaction  SubmitChangesTransaction = null;
                bool            SubmissionResult         = false;
                TPetraPrincipal tempPrincipal;

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                           ref SubmissionResult,
                                                           delegate
                {
                    SUserRow UserDR      = TUserManagerWebConnector.LoadUser(AUsername.ToUpper(), out tempPrincipal);
                    SUserTable UserTable = (SUserTable)UserDR.Table;

                    Random r            = new Random();
                    UserDR.PasswordSalt = r.Next(1000000000).ToString();
                    UserDR.PasswordHash = TUserManagerWebConnector.CreateHashOfPassword(String.Concat(APassword,
                                                                                                      UserDR.PasswordSalt), "SHA1");
                    UserDR.PasswordNeedsChange = APasswordNeedsChanged;

                    // unretire the user if it has been previously retired
                    if (AUnretireIfRetired)
                    {
                        UserDR.Retired = false;
                    }

                    SUserAccess.SubmitChanges(UserTable, SubmitChangesTransaction);

                    SubmissionResult = true;
                });

                return(true);
            }
            else
            {
                IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                return(auth.SetPassword(AUsername, APassword));
            }
        }
예제 #12
0
        private static Boolean SaveUser(String AUserID, SUserTable AUserDataTable, TDBTransaction ATransaction)
        {
            if ((AUserDataTable != null) && (AUserDataTable.Rows.Count > 0))
            {
                try
                {
                    SUserAccess.SubmitChanges(AUserDataTable, ATransaction);
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured during the saving of a User:" + Environment.NewLine + Exc.ToString());

                    throw;
                }
            }
            else
            {
                // nothing to save!
                return(false);
            }

            return(true);
        }
예제 #13
0
        public static SUserRow LoadUser(String AUserID, out TPetraIdentity APetraIdentity)
        {
            SUserRow       ReturnValue;
            TDBTransaction ReadWriteTransaction;
            Boolean        NewTransaction;
            SUserTable     UserDT;
            SUserRow       UserDR;
            Boolean        UserExists;
            DateTime       LastLoginDateTime;
            DateTime       FailedLoginDateTime;

            ReadWriteTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.Serializable,
                                                                                     TEnforceIsolationLevel.eilMinimum,
                                                                                     out NewTransaction);

            // Check if user exists in s_user DB Table
            try
            {
                UserExists = SUserAccess.Exists(AUserID, ReadWriteTransaction);
            }
            catch
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TUserManager.LoadUser: committed own transaction.");
                }

                throw;
            }

            if (!UserExists)
            {
                throw new EUserNotExistantException(StrInvalidUserIDPassword);
            }
            else
            {
                try
                {
                    // Load User record
                    UserDT = SUserAccess.LoadByPrimaryKey(AUserID, ReadWriteTransaction);
                }
                catch (Exception Exp)
                {
                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(7, "TUserManager.LoadUser: committed own transaction.");
                    }

                    TLogging.LogAtLevel(8, "Exception occured while loading a s_user record: " + Exp.ToString());

                    throw;
                }

                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TUserManager.LoadUser: committed own transaction.");
                }

                UserDR = UserDT[0];

                if (!UserDR.IsFailedLoginDateNull())
                {
                    FailedLoginDateTime = UserDR.FailedLoginDate.Value;
                    FailedLoginDateTime = FailedLoginDateTime.AddSeconds(Convert.ToDouble(UserDR.FailedLoginTime));
                }
                else
                {
                    FailedLoginDateTime = DateTime.MinValue;
                }

                if (!UserDR.IsLastLoginDateNull())
                {
                    LastLoginDateTime = UserDR.LastLoginDate.Value;
                    LastLoginDateTime = LastLoginDateTime.AddSeconds(Convert.ToDouble(UserDR.LastLoginTime));
                }
                else
                {
                    LastLoginDateTime = DateTime.MinValue;
                }

                Int64 PartnerKey;

                if (!UserDR.IsPartnerKeyNull())
                {
                    PartnerKey = UserDR.PartnerKey;
                }
                else
                {
                    // to make it not match PartnerKey 0, which might be stored in the DB or in a variable
                    PartnerKey = -1;
                }

                // Create PetraIdentity
                APetraIdentity = new Ict.Petra.Shared.Security.TPetraIdentity(
                    AUserID.ToUpper(), UserDR.LastName, UserDR.FirstName, UserDR.LanguageCode, UserDR.AcquisitionCode, DateTime.MinValue,
                    LastLoginDateTime, FailedLoginDateTime, UserDR.FailedLogins, PartnerKey, UserDR.DefaultLedgerNumber, UserDR.Retired,
                    UserDR.CanModify);
                ReturnValue = UserDR;
            }

            return(ReturnValue);
        }
예제 #14
0
        public static bool SetUserPassword(string AUserID,
                                           string ANewPassword,
                                           string ACurrentPassword,
                                           bool APasswordNeedsChanged,
                                           string AClientComputerName, string AClientIPAddress,
                                           out TVerificationResultCollection AVerification)
        {
            string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);
            TVerificationResult           VerificationResult;
            TVerificationResultCollection VerificationResultColl = null;
            SUserRow   UserDR    = null;
            SUserTable UserTable = null;
            bool       BogusPasswordChangeAttempt = false;

            AVerification = new TVerificationResultCollection();

            // Security check: Is the user that is performing the password change request the current user?
            if (AUserID != UserInfo.GUserInfo.UserID)
            {
                throw new EOPAppException(
                          "The setting of a User's Password must only be done by the user itself, but this isn't the case here and therefore the request gets denied");
            }

            // Password quality check
            if (!TSharedSysManValidation.CheckPasswordQuality(ANewPassword, out VerificationResult))
            {
                AVerification.Add(VerificationResult);

                return(false);
            }

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                TPetraPrincipal tempPrincipal;
                TDBTransaction  SubmitChangesTransaction = null;
                bool            SubmissionResult         = false;

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                           ref SubmissionResult,
                                                           delegate
                {
                    try
                    {
                        UserDR = TUserManagerWebConnector.LoadUser(AUserID.ToUpper(), out tempPrincipal,
                                                                   SubmitChangesTransaction);
                    }
                    catch (EUserNotExistantException)
                    {
                        // Because this cannot happen when a password change gets effected through normal OpenPetra
                        // operation this is treated as a bogus operation that an attacker launches!

                        BogusPasswordChangeAttempt = true;

                        // Logging
                        TUserAccountActivityLog.AddUserAccountActivityLogEntry(AUserID,
                                                                               TUserAccountActivityLog.USER_ACTIVITY_PWD_CHANGE_ATTEMPT_BY_USER_FOR_NONEXISTING_USER,
                                                                               String.Format(Catalog.GetString(
                                                                                                 "User {0} tried to make an attempt to change a User's password for UserID {1} " +
                                                                                                 "but that user doesn't exist! "), UserInfo.GUserInfo.UserID, AUserID) +
                                                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                               SubmitChangesTransaction);

                        SubmissionResult = true;     // Need to set this so that the DB Transaction gets committed!

                        // Simulate that time is spent on 'authenticating' a user (although the user doesn't exist)...! Reason for that: see Method
                        // SimulatePasswordAuthenticationForNonExistingUser!
                        TUserManagerWebConnector.SimulatePasswordAuthenticationForNonExistingUser();

                        return;
                    }

                    UserTable = (SUserTable)UserDR.Table;

                    // Security check: Is the supplied current password correct?
                    if (TUserManagerWebConnector.CreateHashOfPassword(ACurrentPassword,
                                                                      UserDR.PasswordSalt, UserDR.PwdSchemeVersion) != UserDR.PasswordHash)
                    {
                        VerificationResultColl = new TVerificationResultCollection();
                        VerificationResultColl.Add(new TVerificationResult("Password Verification",
                                                                           Catalog.GetString(
                                                                               "The current password was entered incorrectly! The password did not get changed."),
                                                                           TResultSeverity.Resv_Critical));

                        try
                        {
                            SUserAccess.SubmitChanges(UserTable, SubmitChangesTransaction);

                            TUserAccountActivityLog.AddUserAccountActivityLogEntry(UserDR.UserId,
                                                                                   TUserAccountActivityLog.USER_ACTIVITY_PWD_WRONG_WHILE_PWD_CHANGE,
                                                                                   String.Format(Catalog.GetString(
                                                                                                     "User {0} supplied the wrong current password while attempting to change " +
                                                                                                     "his/her password! ") +
                                                                                                 String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                                                 UserInfo.GUserInfo.UserID),
                                                                                   SubmitChangesTransaction);

                            SubmissionResult = true;
                        }
                        catch (Exception Exc)
                        {
                            TLogging.Log(String.Format(
                                             "An Exception occured during the changing of the User Password by user '{0}' (Situation 1):", AUserID) +
                                         Environment.NewLine + Exc.ToString());

                            throw;
                        }
                    }
                });

                if (BogusPasswordChangeAttempt)
                {
                    // Note: VerificationResultColl will be null in this case because we don't want to disclose to an attackeer
                    // why the password change attempt was denied!!!
                    return(false);
                }

                if (VerificationResultColl != null)
                {
                    AVerification = VerificationResultColl;
                    return(false);
                }

                // Security check: Is the supplied new password the same than the current password?
                if (IsNewPasswordSameAsExistingPassword(ANewPassword, UserDR, out VerificationResult))
                {
                    AVerification.Add(VerificationResult);

                    return(false);
                }

                //
                // All checks passed: We go aheand and change the user's password!
                //

                SetNewPasswordHashAndSaltForUser(UserDR, ANewPassword, AClientComputerName, AClientIPAddress, SubmitChangesTransaction);

                UserDR.PasswordNeedsChange = false;

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                           ref SubmissionResult,
                                                           delegate
                {
                    try
                    {
                        SUserAccess.SubmitChanges(UserTable, SubmitChangesTransaction);

                        TUserAccountActivityLog.AddUserAccountActivityLogEntry(UserDR.UserId,
                                                                               (APasswordNeedsChanged ? TUserAccountActivityLog.USER_ACTIVITY_PWD_CHANGE_BY_USER_ENFORCED :
                                                                                TUserAccountActivityLog.USER_ACTIVITY_PWD_CHANGE_BY_USER),
                                                                               String.Format(Catalog.GetString("User {0} changed his/her password{1}"),
                                                                                             UserInfo.GUserInfo.UserID,
                                                                                             (APasswordNeedsChanged ? Catalog.GetString(" (enforced password change.) ") : ". ")) +
                                                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                               SubmitChangesTransaction);

                        SubmissionResult = true;
                    }
                    catch (Exception Exc)
                    {
                        TLogging.Log(String.Format("An Exception occured during the changing of the User Password by user '{0}' (Situation 2):",
                                                   AUserID) +
                                     Environment.NewLine + Exc.ToString());

                        throw;
                    }
                });

                return(true);
            }
            else
            {
                IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                return(auth.SetPassword(AUserID, ANewPassword, ACurrentPassword));
            }
        }
예제 #15
0
        public static bool CreateUser(string AUsername, string APassword, string AFirstName, string AFamilyName, string AModulePermissions)
        {
            TDBTransaction ReadTransaction          = null;
            TDBTransaction SubmitChangesTransaction = null;
            bool           UserExists   = false;
            bool           SubmissionOK = false;

            // TODO: check permissions. is the current user allowed to create other users?
            SUserTable userTable = new SUserTable();
            SUserRow   newUser   = userTable.NewRowTyped();

            newUser.UserId    = AUsername;
            newUser.FirstName = AFirstName;
            newUser.LastName  = AFamilyName;

            if (AUsername.Contains("@"))
            {
                newUser.EmailAddress = AUsername;
                newUser.UserId       = AUsername.Substring(0, AUsername.IndexOf("@")).
                                       Replace(".", string.Empty).
                                       Replace("_", string.Empty).ToUpper();
            }

            // Check whether the user that we are asked to create already exists
            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted, ref ReadTransaction,
                                                           delegate
            {
                if (SUserAccess.Exists(newUser.UserId, ReadTransaction))
                {
                    TLogging.Log("Cannot create new user as a user with User Name '" + newUser.UserId + "' already exists!");
                    UserExists = true;
                }
            });

            if (UserExists)
            {
                return(false);
            }

            userTable.Rows.Add(newUser);

            string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                if (APassword.Length > 0)
                {
                    newUser.PasswordSalt        = PasswordHelper.GetNewPasswordSalt();
                    newUser.PasswordHash        = PasswordHelper.GetPasswordHash(APassword, newUser.PasswordSalt);
                    newUser.PasswordNeedsChange = true;
                }
            }
            else
            {
                try
                {
                    IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                    if (!auth.CreateUser(AUsername, APassword, AFirstName, AFamilyName))
                    {
                        newUser = null;
                    }
                }
                catch (Exception e)
                {
                    TLogging.Log("Problem loading user authentication method " + UserAuthenticationMethod + ": " + e.ToString());
                    return(false);
                }
            }

            if (newUser != null)
            {
                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction, ref SubmissionOK,
                                                           delegate
                {
                    SUserAccess.SubmitChanges(userTable, SubmitChangesTransaction);

                    List <string> modules = new List <string>();

                    if (AModulePermissions == DEMOMODULEPERMISSIONS)
                    {
                        modules.Add("PTNRUSER");
                        modules.Add("FINANCE-1");

                        ALedgerTable theLedgers = ALedgerAccess.LoadAll(SubmitChangesTransaction);

                        foreach (ALedgerRow ledger in theLedgers.Rows)
                        {
                            modules.Add("LEDGER" + ledger.LedgerNumber.ToString("0000"));
                        }
                    }
                    else
                    {
                        string[] modulePermissions = AModulePermissions.Split(new char[] { ',' });

                        foreach (string s in modulePermissions)
                        {
                            if (s.Trim().Length > 0)
                            {
                                modules.Add(s.Trim());
                            }
                        }
                    }

                    SUserModuleAccessPermissionTable moduleAccessPermissionTable = new SUserModuleAccessPermissionTable();

                    foreach (string module in modules)
                    {
                        SUserModuleAccessPermissionRow moduleAccessPermissionRow = moduleAccessPermissionTable.NewRowTyped();
                        moduleAccessPermissionRow.UserId    = newUser.UserId;
                        moduleAccessPermissionRow.ModuleId  = module;
                        moduleAccessPermissionRow.CanAccess = true;
                        moduleAccessPermissionTable.Rows.Add(moduleAccessPermissionRow);
                    }

                    SUserModuleAccessPermissionAccess.SubmitChanges(moduleAccessPermissionTable, SubmitChangesTransaction);

                    // TODO: table permissions should be set by the module list
                    // TODO: add p_data_label... tables here so user can generally have access
                    string[] tables = new string[] {
                        "p_bank", "p_church", "p_family", "p_location",
                        "p_organisation", "p_partner", "p_partner_location",
                        "p_partner_type", "p_person", "p_unit", "p_venue",
                        "p_data_label", "p_data_label_lookup", "p_data_label_lookup_category", "p_data_label_use", "p_data_label_value_partner",
                    };

                    SUserTableAccessPermissionTable tableAccessPermissionTable = new SUserTableAccessPermissionTable();

                    foreach (string table in tables)
                    {
                        SUserTableAccessPermissionRow tableAccessPermissionRow = tableAccessPermissionTable.NewRowTyped();
                        tableAccessPermissionRow.UserId    = newUser.UserId;
                        tableAccessPermissionRow.TableName = table;
                        tableAccessPermissionTable.Rows.Add(tableAccessPermissionRow);
                    }

                    SUserTableAccessPermissionAccess.SubmitChanges(tableAccessPermissionTable, SubmitChangesTransaction);

                    SubmissionOK = true;
                });

                return(true);
            }

            return(false);
        }
예제 #16
0
        public static bool SetUserPassword(string AUsername,
                                           string APassword,
                                           string AOldPassword,
                                           bool APasswordNeedsChanged,
                                           out TVerificationResultCollection AVerification)
        {
            TDBTransaction      Transaction;
            string              UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);
            TVerificationResult VerificationResult;

            AVerification = new TVerificationResultCollection();

            if (!TSharedSysManValidation.CheckPasswordQuality(APassword, out VerificationResult))
            {
                return(false);
            }

            if (APasswordNeedsChanged && APassword == AOldPassword)
            {
                AVerification = new TVerificationResultCollection();
                AVerification.Add(new TVerificationResult("\nPassword check.",
                                                          Catalog.GetString(
                                                              "Password not changed as the old password was reused. Please use a new password."),
                                                          TResultSeverity.Resv_Critical));
                return(false);
            }

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                TPetraPrincipal tempPrincipal;
                SUserRow        UserDR = TUserManagerWebConnector.LoadUser(AUsername.ToUpper(), out tempPrincipal);

                if (TUserManagerWebConnector.CreateHashOfPassword(String.Concat(AOldPassword,
                                                                                UserDR.PasswordSalt)) != UserDR.PasswordHash)
                {
                    AVerification = new TVerificationResultCollection();
                    AVerification.Add(new TVerificationResult("\nPassword quality check.",
                                                              String.Format(
                                                                  Catalog.GetString(
                                                                      "Old password entered incorrectly. Password not changed.")),
                                                              TResultSeverity.Resv_Critical));
                    return(false);
                }

                SUserTable UserTable = (SUserTable)UserDR.Table;

                UserDR.PasswordHash = TUserManagerWebConnector.CreateHashOfPassword(String.Concat(APassword,
                                                                                                  UserDR.PasswordSalt));
                UserDR.PasswordNeedsChange = false;

                Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

                try
                {
                    SUserAccess.SubmitChanges(UserTable, Transaction);

                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                catch (Exception Exc)
                {
                    TLogging.Log("An Exception occured during the setting of the User Password:" + Environment.NewLine + Exc.ToString());

                    DBAccess.GDBAccessObj.RollbackTransaction();

                    throw;
                }

                return(true);
            }
            else
            {
                IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                return(auth.SetPassword(AUsername, APassword, AOldPassword));
            }
        }
예제 #17
0
        private static void SendEmailForUser(TDataBase ADataBaseObj, string AUserId, DataTable AErrors)
        {
            TDBTransaction ReadTransaction = new TDBTransaction();
            SUserRow       userrow         = null;

            // get the email address of the user
            ADataBaseObj.ReadTransaction(ref ReadTransaction,
                                         delegate
            {
                userrow = SUserAccess.LoadByPrimaryKey(AUserId, ReadTransaction)[0];
            });

            string   excelfile        = TAppSettingsManager.GetValue("DataChecks.TempPath") + "/errors" + AUserId + ".xlsx";
            DateTime Errors_SinceDate = DateTime.Today.AddDays(-1 * SENDREPORTFORDAYS_TOUSERS);

            DataView v = new DataView(AErrors,
                                      "(CreatedBy='" + AUserId + "' AND ModifiedBy IS NULL AND DateCreated > #" + Errors_SinceDate.ToString("MM/dd/yyyy") + "#) " +
                                      "OR (ModifiedBy='" + AUserId + "' AND DateModified > #" + Errors_SinceDate.ToString("MM/dd/yyyy") + "#)",
                                      string.Empty, DataViewRowState.CurrentRows);

            try
            {
                using (StreamWriter sw = new StreamWriter(excelfile))
                {
                    using (MemoryStream m = new MemoryStream())
                    {
                        if (!TCsv2Xml.DataTable2ExcelStream(v.ToTable(), m))
                        {
                            return;
                        }

                        m.WriteTo(sw.BaseStream);
                        m.Close();
                        sw.Close();
                    }
                }
            }
            catch (Exception e)
            {
                TLogging.Log("Problems writing to file " + excelfile);
                TLogging.Log(e.ToString());
                return;
            }

            string recipientEmail = string.Empty;

            if (!userrow.IsEmailAddressNull())
            {
                recipientEmail = userrow.EmailAddress;
            }
            else if (TAppSettingsManager.HasValue("DataChecks.Email.Recipient.UserDomain"))
            {
                recipientEmail = userrow.FirstName + "." + userrow.LastName + "@" + TAppSettingsManager.GetValue(
                    "DataChecks.Email.Recipient.UserDomain");
            }
            else if (TAppSettingsManager.HasValue("DataChecks.Email.Recipient"))
            {
                recipientEmail = TAppSettingsManager.GetValue("DataChecks.Email.Recipient");
            }

            if (recipientEmail.Length > 0)
            {
                new TSmtpSender().SendEmail("<" + TAppSettingsManager.GetValue("DataChecks.Email.Sender") + ">",
                                            "OpenPetra DataCheck Robot",
                                            recipientEmail,
                                            "Data Check for " + AUserId,
                                            "there are " + v.Count.ToString() + " errors. Please see attachment!",
                                            new string[] { excelfile });
            }
            else
            {
                TLogging.Log("no email can be sent to " + AUserId);
            }
        }
예제 #18
0
        public static bool CreateUser(string AUsername, string APassword, string AFirstName, string AFamilyName,
                                      string AModulePermissions, string AClientComputerName, string AClientIPAddress, TDBTransaction ATransaction = null)
        {
            TDataBase      DBConnectionObj                 = DBAccess.GetDBAccessObj(ATransaction);
            TDBTransaction ReadWriteTransaction            = null;
            bool           SeparateDBConnectionEstablished = false;
            bool           NewTransaction;
            bool           SubmissionOK = false;

            // TODO: check permissions. is the current user allowed to create other users?
            SUserTable userTable = new SUserTable();
            SUserRow   newUser   = userTable.NewRowTyped();

            newUser.UserId    = AUsername;
            newUser.FirstName = AFirstName;
            newUser.LastName  = AFamilyName;

            if (AUsername.Contains("@"))
            {
                newUser.EmailAddress = AUsername;
                newUser.UserId       = AUsername.Substring(0, AUsername.IndexOf("@")).
                                       Replace(".", string.Empty).
                                       Replace("_", string.Empty).ToUpper();
            }

            if (DBConnectionObj == null)
            {
                // ATransaction was null and GDBAccess is also null: we need to establish a DB Connection manually here!
                DBConnectionObj = DBAccess.SimpleEstablishDBConnection("CreateUser");

                SeparateDBConnectionEstablished = true;
            }

            ReadWriteTransaction = DBConnectionObj.GetNewOrExistingTransaction(
                IsolationLevel.Serializable, out NewTransaction, "CreateUser");

            try
            {
                // Check whether the user that we are asked to create already exists
                if (SUserAccess.Exists(newUser.UserId, ReadWriteTransaction))
                {
                    TLogging.Log("Cannot create new user because a user with User Name '" + newUser.UserId + "' already exists!");

                    return(false);
                }

                newUser.PwdSchemeVersion = TPasswordHelper.CurrentPasswordSchemeNumber;

                userTable.Rows.Add(newUser);

                string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

                if (UserAuthenticationMethod == "OpenPetraDBSUser")
                {
                    if (APassword.Length > 0)
                    {
                        SetNewPasswordHashAndSaltForUser(newUser, APassword, AClientComputerName, AClientIPAddress, ReadWriteTransaction);

                        if (AModulePermissions != TMaintenanceWebConnector.DEMOMODULEPERMISSIONS)
                        {
                            newUser.PasswordNeedsChange = true;
                        }
                    }
                }
                else
                {
                    try
                    {
                        IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                        if (!auth.CreateUser(AUsername, APassword, AFirstName, AFamilyName))
                        {
                            newUser = null;
                        }
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("Problem loading user authentication method " + UserAuthenticationMethod + ": " + e.ToString());
                        return(false);
                    }
                }

                if (newUser != null)
                {
                    SUserAccess.SubmitChanges(userTable, ReadWriteTransaction);

                    List <string> modules = new List <string>();

                    if (AModulePermissions == DEMOMODULEPERMISSIONS)
                    {
                        modules.Add("PTNRUSER");
                        modules.Add("FINANCE-1");

                        ALedgerTable theLedgers = ALedgerAccess.LoadAll(ReadWriteTransaction);

                        foreach (ALedgerRow ledger in theLedgers.Rows)
                        {
                            modules.Add("LEDGER" + ledger.LedgerNumber.ToString("0000"));
                        }
                    }
                    else
                    {
                        string[] modulePermissions = AModulePermissions.Split(new char[] { ',' });

                        foreach (string s in modulePermissions)
                        {
                            if (s.Trim().Length > 0)
                            {
                                modules.Add(s.Trim());
                            }
                        }
                    }

                    SUserModuleAccessPermissionTable moduleAccessPermissionTable = new SUserModuleAccessPermissionTable();

                    foreach (string module in modules)
                    {
                        SUserModuleAccessPermissionRow moduleAccessPermissionRow = moduleAccessPermissionTable.NewRowTyped();
                        moduleAccessPermissionRow.UserId    = newUser.UserId;
                        moduleAccessPermissionRow.ModuleId  = module;
                        moduleAccessPermissionRow.CanAccess = true;
                        moduleAccessPermissionTable.Rows.Add(moduleAccessPermissionRow);
                    }

                    SUserModuleAccessPermissionAccess.SubmitChanges(moduleAccessPermissionTable, ReadWriteTransaction);

                    // TODO: table permissions should be set by the module list
                    // TODO: add p_data_label... tables here so user can generally have access
                    string[] tables = new string[] {
                        "p_bank", "p_church", "p_family", "p_location",
                        "p_organisation", "p_partner", "p_partner_location",
                        "p_partner_type", "p_person", "p_unit", "p_venue",
                        "p_data_label", "p_data_label_lookup", "p_data_label_lookup_category", "p_data_label_use", "p_data_label_value_partner",
                    };

                    SUserTableAccessPermissionTable tableAccessPermissionTable = new SUserTableAccessPermissionTable();

                    foreach (string table in tables)
                    {
                        SUserTableAccessPermissionRow tableAccessPermissionRow = tableAccessPermissionTable.NewRowTyped();
                        tableAccessPermissionRow.UserId    = newUser.UserId;
                        tableAccessPermissionRow.TableName = table;
                        tableAccessPermissionTable.Rows.Add(tableAccessPermissionRow);
                    }

                    SUserTableAccessPermissionAccess.SubmitChanges(tableAccessPermissionTable, ReadWriteTransaction);

                    TUserAccountActivityLog.AddUserAccountActivityLogEntry(newUser.UserId,
                                                                           TUserAccountActivityLog.USER_ACTIVITY_USER_RECORD_CREATED,
                                                                           String.Format(Catalog.GetString("The user record for the new user {0} got created by user {1}. "),
                                                                                         newUser.UserId, UserInfo.GUserInfo.UserID) +
                                                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                           ReadWriteTransaction);

                    SubmissionOK = true;

                    return(true);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    if (SubmissionOK)
                    {
                        ReadWriteTransaction.DataBaseObj.CommitTransaction();
                    }
                    else
                    {
                        ReadWriteTransaction.DataBaseObj.RollbackTransaction();
                    }

                    if (SeparateDBConnectionEstablished)
                    {
                        DBConnectionObj.CloseDBConnection();
                    }
                }
            }

            return(false);
        }
예제 #19
0
        /// <summary>
        /// overload. language code is part of TPetraPrincipal
        /// </summary>
        /// <param name="AUserID"></param>
        /// <param name="AReturnEnglishIfNotFound"></param>
        /// <param name="ATransaction">Instantiated DB Transaction.</param>
        /// <returns></returns>
        public String GetLogonMessage(string AUserID, Boolean AReturnEnglishIfNotFound, TDBTransaction ATransaction)
        {
            SUserTable user = SUserAccess.LoadByPrimaryKey(AUserID, ATransaction);

            return(GetLogonMessageLanguage(user[0].LanguageCode, false, ATransaction));
        }
예제 #20
0
        public static bool SetUserPassword(string AUsername,
                                           string ANewPassword,
                                           bool APasswordNeedsChanged,
                                           bool AUnretireIfRetired,
                                           string AClientComputerName, string AClientIPAddress,
                                           out TVerificationResultCollection AVerification)
        {
            TVerificationResult VerificationResult;
            SUserTable          UserTable;
            SUserRow            UserDR;
            string UserAuthenticationMethod   = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);
            bool   BogusPasswordChangeAttempt = false;

            AVerification = new TVerificationResultCollection();

            // Password quality check
            if (!TSharedSysManValidation.CheckPasswordQuality(ANewPassword, out VerificationResult))
            {
                AVerification.Add(VerificationResult);

                return(false);
            }

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                TDBTransaction  SubmitChangesTransaction = null;
                bool            SubmissionResult         = false;
                TPetraPrincipal tempPrincipal;

                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                           ref SubmissionResult,
                                                           delegate
                {
                    try
                    {
                        UserDR = TUserManagerWebConnector.LoadUser(AUsername.ToUpper(), out tempPrincipal,
                                                                   SubmitChangesTransaction);
                    }
                    catch (EUserNotExistantException)
                    {
                        // Because this cannot happen when a password change gets effected through normal OpenPetra
                        // operation this is treated as a bogus operation that an attacker launches!

                        BogusPasswordChangeAttempt = true;

                        // Logging
                        TUserAccountActivityLog.AddUserAccountActivityLogEntry(AUsername,
                                                                               TUserAccountActivityLog.USER_ACTIVITY_PWD_CHANGE_ATTEMPT_BY_SYSADMIN_FOR_NONEXISTING_USER,
                                                                               String.Format(Catalog.GetString(
                                                                                                 "A system administrator, {0}, made an attempt to change a User's password for UserID {1} " +
                                                                                                 "but that user doesn't exist! "), UserInfo.GUserInfo.UserID, AUsername) +
                                                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                               SubmitChangesTransaction);

                        SubmissionResult = true;     // Need to set this so that the DB Transaction gets committed!

                        // Simulate that time is spent on 'authenticating' a user (although the user doesn't exist)...! Reason for that: see Method
                        // SimulatePasswordAuthenticationForNonExistingUser!
                        TUserManagerWebConnector.SimulatePasswordAuthenticationForNonExistingUser();

                        return;
                    }

                    UserTable = (SUserTable)UserDR.Table;

                    // Note: We are on purpose NOT checking here whether the new password is the same as the existing
                    // password (which would be done by calling the IsNewPasswordSameAsExistingPassword Method) because
                    // if we would do that then the SYSADMIN could try to find out what the password of a user is by
                    // seeing if (s)he would get a message that the new password must be different from the old password...!

                    SetNewPasswordHashAndSaltForUser(UserDR, ANewPassword, AClientComputerName, AClientIPAddress, SubmitChangesTransaction);

                    UserDR.PasswordNeedsChange = APasswordNeedsChanged;

                    // 'Unretire' the user if the user has been previously 'retired' and also 'unlock' the User Account if
                    // it has previously been locked
                    if (AUnretireIfRetired)
                    {
                        UserDR.Retired       = false;
                        UserDR.AccountLocked = false;
                    }

                    try
                    {
                        SUserAccess.SubmitChanges(UserTable, SubmitChangesTransaction);

                        TUserAccountActivityLog.AddUserAccountActivityLogEntry(UserDR.UserId,
                                                                               TUserAccountActivityLog.USER_ACTIVITY_PWD_CHANGE_BY_SYSADMIN,
                                                                               String.Format(Catalog.GetString(
                                                                                                 "The password of user {0} got changed by user {1} (the latter user has got SYSADMIN " +
                                                                                                 "privileges). "), UserDR.UserId, UserInfo.GUserInfo.UserID) +
                                                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                               SubmitChangesTransaction);
                    }
                    catch (Exception Exc)
                    {
                        TLogging.Log("An Exception occured during the saving of the new User Password by the SYSADMIN:" + Environment.NewLine +
                                     Exc.ToString());

                        throw;
                    }

                    SubmissionResult = true;
                });


                return(!BogusPasswordChangeAttempt);
            }
            else
            {
                IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                return(auth.SetPassword(AUsername, ANewPassword));
            }
        }