Пример #1
0
 public static string CreateHashOfPassword(string APassword, string ASalt, int APasswordSchemeVersion)
 {
     if (APasswordSchemeVersion == 0)
     {
         // SHA1 - DO NOT USE ANYMORE as this password hash is not considered safe nowadays!
         return(BitConverter.ToString(
                    SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(String.Concat(APassword,
                                                                                   ASalt)))).Replace("-", ""));
     }
     else
     {
         return(TPasswordHelper.GetPasswordSchemeHelperForVersion(APasswordSchemeVersion).GetPasswordHash(
                    APassword, Convert.FromBase64String(ASalt)));
     }
 }
Пример #2
0
        /// <summary>
        /// Compares the new password with existing password - are they the same?
        /// </summary>
        /// <param name="ANewPassword">New password.</param>
        /// <param name="AUserDR">DataRow of the user record in s_user DB Table whose password should be changed.</param>
        /// <param name="AVerificationResult">Will be null if the new password is not the same than the old password,
        /// otherwise it will be populated.</param>
        /// <returns>False if the new password is not the same than the old password, otherwise true.</returns>
        private static bool IsNewPasswordSameAsExistingPassword(string ANewPassword, SUserRow AUserDR,
                                                                out TVerificationResult AVerificationResult)
        {
            string NewPasswordHashWithOldSalt = TUserManagerWebConnector.CreateHashOfPassword(ANewPassword,
                                                                                              AUserDR.PasswordSalt, AUserDR.PwdSchemeVersion);

            if (TPasswordHelper.EqualsAntiTimingAttack(Convert.FromBase64String(AUserDR.PasswordHash),
                                                       Convert.FromBase64String(NewPasswordHashWithOldSalt)))
            {
                AVerificationResult = new TVerificationResult("Password change",
                                                              ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_NEW_PASSWORD_MUST_BE_DIFFERENT));

                return(true);
            }

            AVerificationResult = null;

            return(false);
        }
Пример #3
0
        private void NewRowManual(ref SUserRow ARow)
        {
            string newName        = Catalog.GetString("NEWUSER");
            Int32  countNewDetail = 0;

            if (FMainDS.SUser.Rows.Find(new object[] { newName }) != null)
            {
                while (FMainDS.SUser.Rows.Find(new object[] { newName + countNewDetail.ToString() }) != null)
                {
                    countNewDetail++;
                }

                newName += countNewDetail.ToString();
            }

            ARow.UserId       = newName;
            ARow.PasswordHash = TPasswordHelper.GetRandomSecurePassword();

            FNewRecordBeingAdded = true;
        }
Пример #4
0
        public static TPetraPrincipal PerformUserAuthentication(String AUserID, String APassword,
                                                                string AClientComputerName, string AClientIPAddress, out Boolean ASystemEnabled,
                                                                TDBTransaction ATransaction)
        {
            SUserRow            UserDR;
            DateTime            LoginDateTime;
            TPetraPrincipal     PetraPrincipal           = null;
            string              UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);
            IUserAuthentication AuthenticationAssembly;
            string              AuthAssemblyErrorMessage;

            Int32 AProcessID = -1;

            ASystemEnabled = true;

            string EmailAddress = AUserID;

            if (EmailAddress.Contains("@"))
            {
                // try to find unique User for this e-mail address
                string sql = "SELECT s_user_id_c FROM PUB_s_user WHERE UPPER(s_email_address_c) = ?";

                OdbcParameter[] parameters = new OdbcParameter[1];
                parameters[0]       = new OdbcParameter("EmailAddress", OdbcType.VarChar);
                parameters[0].Value = EmailAddress.ToUpper();

                DataTable result = ATransaction.DataBaseObj.SelectDT(sql, "user", ATransaction, parameters);

                if (result.Rows.Count == 1)
                {
                    AUserID = result.Rows[0][0].ToString();
                }
                else
                {
                    TLogging.Log("Login with E-Mail address failed for " + EmailAddress + ". " +
                                 "We found " + result.Rows.Count.ToString() + " matching rows for this address.");
                }
            }

            try
            {
                UserDR = LoadUser(AUserID, out PetraPrincipal, ATransaction);
            }
            catch (EUserNotExistantException)
            {
                TPetraIdentity PetraIdentity = new TPetraIdentity(
                    "SYSADMIN", "", "", "", "",
                    DateTime.MinValue, DateTime.MinValue, DateTime.MinValue,
                    0, -1, -1, false, false, false);

                UserInfo.GUserInfo = new TPetraPrincipal(PetraIdentity, null);

                // Logging
                TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_NONEXISTING_USER,
                                           String.Format(Catalog.GetString(
                                                             "User with User ID '{0}' attempted to log in, but there is no user account for this user! "),
                                                         AUserID) + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                           out AProcessID, ATransaction);

                // Only now throw the Exception!
                throw;
            }

            UserInfo.GUserInfo = PetraPrincipal;

            if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken"))
            {
                // Login via server admin console authenticated by file token
                APassword = String.Empty;
            }
            //
            // (1) Check user-supplied password
            //
            else if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                if (!TPasswordHelper.EqualsAntiTimingAttack(
                        Convert.FromBase64String(
                            CreateHashOfPassword(APassword, UserDR.PasswordSalt, UserDR.PwdSchemeVersion)),
                        Convert.FromBase64String(UserDR.PasswordHash)))
                {
                    // The password that the user supplied is wrong!!! --> Save failed user login attempt!
                    // If the number of permitted failed logins in a row gets exceeded then also lock the user account!
                    SaveFailedLogin(AUserID, UserDR, AClientComputerName, AClientIPAddress, ATransaction);

                    if (UserDR.AccountLocked &&
                        (Convert.ToBoolean(UserDR[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != UserDR.AccountLocked))
                    {
                        // User Account just got locked!
                        throw new EUserAccountGotLockedException(StrInvalidUserIDPassword);
                    }
                    else
                    {
                        throw new EPasswordWrongException(StrInvalidUserIDPassword);
                    }
                }
            }
            else
            {
                AuthenticationAssembly = LoadAuthAssembly(UserAuthenticationMethod);

                if (!AuthenticationAssembly.AuthenticateUser(EmailAddress, APassword, out AuthAssemblyErrorMessage))
                {
                    // The password that the user supplied is wrong!!! --> Save failed user login attempt!
                    // If the number of permitted failed logins in a row gets exceeded then also lock the user account!
                    SaveFailedLogin(AUserID, UserDR, AClientComputerName, AClientIPAddress, ATransaction);

                    if (UserDR.AccountLocked &&
                        (Convert.ToBoolean(UserDR[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != UserDR.AccountLocked))
                    {
                        // User Account just got locked!
                        throw new EUserAccountGotLockedException(StrInvalidUserIDPassword);
                    }
                    else
                    {
                        throw new EPasswordWrongException(AuthAssemblyErrorMessage);
                    }
                }
            }

            //
            // (2) Check if the User Account is Locked or if the user is 'Retired'. If either is true then deny the login!!!
            //
            // IMPORTANT: We perform these checks only AFTER the check for the correctness of the password so that every
            // log-in attempt that gets rejected on grounds of a wrong password takes the same amount of time (to help prevent
            // an attack vector called 'timing attack')
            if (PetraPrincipal.PetraIdentity.AccountLocked || PetraPrincipal.PetraIdentity.Retired)
            {
                if (PetraPrincipal.PetraIdentity.AccountLocked)
                {
                    // Logging
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_LOCKED_USER,
                                               Catalog.GetString("User attempted to log in, but the user account was locked! ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    // Only now throw the Exception!
                    throw new EUserAccountLockedException(StrInvalidUserIDPassword);
                }
                else
                {
                    // Logging
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_RETIRED_USER,
                                               Catalog.GetString("User attempted to log in, but the user is retired! ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    // Only now throw the Exception!
                    throw new EUserRetiredException(StrInvalidUserIDPassword);
                }
            }

            //
            // (3) Check SystemLoginStatus (whether the general use of the OpenPetra application is enabled/disabled) in the
            // SystemStatus table (this table always holds only a single record)
            //
            SSystemStatusTable SystemStatusDT;

            SystemStatusDT = SSystemStatusAccess.LoadAll(ATransaction);

            if (SystemStatusDT[0].SystemLoginStatus)
            {
                ASystemEnabled = true;
            }
            else
            {
                ASystemEnabled = false;

                // TODO: Check for Security Group membership might need reviewal when security model of OpenPetra might get reviewed...
                if (PetraPrincipal.IsInGroup("SYSADMIN"))
                {
                    PetraPrincipal.LoginMessage =
                        String.Format(StrSystemDisabled1,
                                      SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine +
                        StrSystemDisabled2Admin;
                }
                else
                {
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_WHEN_SYSTEM_WAS_DISABLED,
                                               Catalog.GetString("User wanted to log in, but the System was disabled. ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    TLoginLog.RecordUserLogout(AUserID, AProcessID, ATransaction);

                    throw new ESystemDisabledException(String.Format(StrSystemDisabled1,
                                                                     SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine +
                                                       String.Format(StrSystemDisabled2, StringHelper.DateToLocalizedString(SystemStatusDT[0].SystemAvailableDate.Value),
                                                                     SystemStatusDT[0].SystemAvailableDate.Value.AddSeconds(SystemStatusDT[0].SystemAvailableTime).ToShortTimeString()));
                }
            }

            //
            // (4) Save successful login!
            //
            LoginDateTime        = DateTime.Now;
            UserDR.LastLoginDate = LoginDateTime;
            UserDR.LastLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
            UserDR.FailedLogins  = 0; // this needs resetting!

            // Upgrade the user's password hashing scheme if it is older than the current password hashing scheme
            if (APassword != String.Empty && UserDR.PwdSchemeVersion < TPasswordHelper.CurrentPasswordSchemeNumber)
            {
                TMaintenanceWebConnector.SetNewPasswordHashAndSaltForUser(UserDR, APassword,
                                                                          AClientComputerName, AClientIPAddress, ATransaction);
            }

            SaveUser(AUserID, (SUserTable)UserDR.Table, ATransaction);

            PetraPrincipal.PetraIdentity.CurrentLogin = LoginDateTime;

            //PetraPrincipal.PetraIdentity.FailedLogins = 0;

            // TODO: Check for Security Group membership might need reviewal when security model of OpenPetra might get reviewed...

            if (PetraPrincipal.IsInGroup("SYSADMIN"))
            {
                TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_SUCCESSFUL_SYSADMIN,
                                           Catalog.GetString("User login - SYSADMIN privileges. ") +
                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                           out AProcessID, ATransaction);
            }
            else
            {
                TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_SUCCESSFUL,
                                           Catalog.GetString("User login. ") +
                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                           out AProcessID, ATransaction);
            }

            PetraPrincipal.ProcessID = AProcessID;
            AProcessID = 0;

            //
            // (5) Check if a password change is requested for this user
            //
            if (UserDR.PasswordNeedsChange)
            {
                // The user needs to change their password before they can use OpenPetra
                PetraPrincipal.LoginMessage = SharedConstants.LOGINMUSTCHANGEPASSWORD;
            }

            return(PetraPrincipal);
        }
Пример #5
0
        public static bool PerformUserAuthentication(String AUserID, String APassword,
                                                     string AClientComputerName, string AClientIPAddress, out Boolean ASystemEnabled,
                                                     TDBTransaction ATransaction)
        {
            SUserRow            UserDR;
            DateTime            LoginDateTime;
            TPetraPrincipal     PetraPrincipal           = null;
            string              UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);
            IUserAuthentication AuthenticationAssembly;
            string              AuthAssemblyErrorMessage;

            Int32 AProcessID = -1;

            ASystemEnabled = true;

            CheckDatabaseVersion(ATransaction.DataBaseObj);

            string EmailAddress = AUserID;

            try
            {
                UserDR = LoadUser(AUserID, out PetraPrincipal, ATransaction);
            }
            catch (EUserNotExistantException)
            {
                // pass ATransaction
                UserInfo.SetUserInfo(new TPetraPrincipal("SYSADMIN"));

                // Logging
                TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_NONEXISTING_USER,
                                           String.Format(Catalog.GetString(
                                                             "User with User ID '{0}' attempted to log in, but there is no user account for this user! "),
                                                         AUserID) + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                           out AProcessID, ATransaction);

                // Only now throw the Exception!
                throw;
            }

            // pass ATransaction
            UserInfo.SetUserInfo(PetraPrincipal);

            if (AUserID == "SELFSERVICE")
            {
                APassword = String.Empty;
            }
            else if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken"))
            {
                // Login via server admin console authenticated by file token
                APassword = String.Empty;
            }
            //
            // (1) Check user-supplied password
            //
            else if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                if (!TPasswordHelper.EqualsAntiTimingAttack(
                        Convert.FromBase64String(
                            CreateHashOfPassword(APassword, UserDR.PasswordSalt, UserDR.PwdSchemeVersion)),
                        Convert.FromBase64String(UserDR.PasswordHash)))
                {
                    // The password that the user supplied is wrong!!! --> Save failed user login attempt!
                    // If the number of permitted failed logins in a row gets exceeded then also lock the user account!
                    SaveFailedLogin(AUserID, UserDR, AClientComputerName, AClientIPAddress, ATransaction);

                    if (UserDR.AccountLocked &&
                        (Convert.ToBoolean(UserDR[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != UserDR.AccountLocked))
                    {
                        // User Account just got locked!
                        throw new EUserAccountGotLockedException(StrInvalidUserIDPassword);
                    }
                    else
                    {
                        throw new EPasswordWrongException(StrInvalidUserIDPassword);
                    }
                }
            }
            else
            {
                AuthenticationAssembly = LoadAuthAssembly(UserAuthenticationMethod);

                if (!AuthenticationAssembly.AuthenticateUser(EmailAddress, APassword, out AuthAssemblyErrorMessage))
                {
                    // The password that the user supplied is wrong!!! --> Save failed user login attempt!
                    // If the number of permitted failed logins in a row gets exceeded then also lock the user account!
                    SaveFailedLogin(AUserID, UserDR, AClientComputerName, AClientIPAddress, ATransaction);

                    if (UserDR.AccountLocked &&
                        (Convert.ToBoolean(UserDR[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != UserDR.AccountLocked))
                    {
                        // User Account just got locked!
                        throw new EUserAccountGotLockedException(StrInvalidUserIDPassword);
                    }
                    else
                    {
                        throw new EPasswordWrongException(AuthAssemblyErrorMessage);
                    }
                }
            }

            //
            // (2) Check if the User Account is Locked or if the user is 'Retired'. If either is true then deny the login!!!
            //
            // IMPORTANT: We perform these checks only AFTER the check for the correctness of the password so that every
            // log-in attempt that gets rejected on grounds of a wrong password takes the same amount of time (to help prevent
            // an attack vector called 'timing attack')
            if (UserDR.AccountLocked || UserDR.Retired)
            {
                if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken"))
                {
                    // this is ok. we need to be able to activate the sysadmin account on SetInitialSysadminEmail
                }
                else if (UserDR.AccountLocked)
                {
                    // Logging
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_LOCKED_USER,
                                               Catalog.GetString("User attempted to log in, but the user account was locked! ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    // Only now throw the Exception!
                    throw new EUserAccountLockedException(StrInvalidUserIDPassword);
                }
                else
                {
                    // Logging
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_RETIRED_USER,
                                               Catalog.GetString("User attempted to log in, but the user is retired! ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    // Only now throw the Exception!
                    throw new EUserRetiredException(StrInvalidUserIDPassword);
                }
            }

            //
            // (3) Check SystemLoginStatus (whether the general use of the OpenPetra application is enabled/disabled) in the
            // SystemStatus table (this table always holds only a single record)
            //
            SSystemStatusTable SystemStatusDT;

            SystemStatusDT = SSystemStatusAccess.LoadAll(ATransaction);

            if (SystemStatusDT[0].SystemLoginStatus)
            {
                ASystemEnabled = true;
            }
            else
            {
                ASystemEnabled = false;

                // TODO: Check for Security Group membership might need reviewal when security model of OpenPetra might get reviewed...
                if (PetraPrincipal.IsInGroup("SYSADMIN"))
                {
                    PetraPrincipal.LoginMessage =
                        String.Format(StrSystemDisabled1,
                                      SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine +
                        StrSystemDisabled2Admin;
                }
                else
                {
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_WHEN_SYSTEM_WAS_DISABLED,
                                               Catalog.GetString("User wanted to log in, but the System was disabled. ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    TLoginLog.RecordUserLogout(AUserID, AProcessID, ATransaction);

                    throw new ESystemDisabledException(String.Format(StrSystemDisabled1,
                                                                     SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine +
                                                       String.Format(StrSystemDisabled2, StringHelper.DateToLocalizedString(SystemStatusDT[0].SystemAvailableDate.Value),
                                                                     SystemStatusDT[0].SystemAvailableDate.Value.AddSeconds(SystemStatusDT[0].SystemAvailableTime).ToShortTimeString()));
                }
            }

            //
            // (3b) Check if the license is valid
            //
            string LicenseCheckUrl = TAppSettingsManager.GetValue("LicenseCheck.Url", String.Empty, false);
            string LicenseUser     = TAppSettingsManager.GetValue("Server.DBName");

            if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken"))
            {
                // don't check for the license, since this is called when upgrading the server as well.
                LicenseCheckUrl = String.Empty;
            }

            if ((LicenseCheckUrl != String.Empty) && (LicenseUser != "openpetra"))
            {
                string url = LicenseCheckUrl + LicenseUser;

                string result = THTTPUtils.ReadWebsite(url);

                bool valid  = result.Contains("\"valid\":true");
                bool gratis = result.Contains("\"gratis\":true");

                if (!valid && !gratis)
                {
                    TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_WHEN_SYSTEM_WAS_DISABLED,
                                               Catalog.GetString("User wanted to log in, but the license is expired. ") +
                                               String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                               out AProcessID, ATransaction);

                    TLoginLog.RecordUserLogout(AUserID, AProcessID, ATransaction);

                    throw new ELicenseExpiredException("LICENSE_EXPIRED");
                }
            }

            //
            // (4) Save successful login!
            //
            LoginDateTime        = DateTime.Now;
            UserDR.LastLoginDate = LoginDateTime;
            UserDR.LastLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
            UserDR.FailedLogins  = 0; // this needs resetting!

            // Upgrade the user's password hashing scheme if it is older than the current password hashing scheme
            if (APassword != String.Empty && UserDR.PwdSchemeVersion < TPasswordHelper.CurrentPasswordSchemeNumber)
            {
                TMaintenanceWebConnector.SetNewPasswordHashAndSaltForUser(UserDR, APassword,
                                                                          AClientComputerName, AClientIPAddress, ATransaction);
            }

            SaveUser(AUserID, (SUserTable)UserDR.Table, ATransaction);

            // TODO: Check for Security Group membership might need reviewal when security model of OpenPetra might get reviewed...

            if (PetraPrincipal.IsInGroup("SYSADMIN"))
            {
                TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_SUCCESSFUL_SYSADMIN,
                                           Catalog.GetString("User login - SYSADMIN privileges. ") +
                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                           out AProcessID, ATransaction);
            }
            else
            {
                TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_SUCCESSFUL,
                                           Catalog.GetString("User login. ") +
                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                           out AProcessID, ATransaction);
            }

            PetraPrincipal.ProcessID = AProcessID;
            AProcessID = 0;

            //
            // (5) Check if a password change is requested for this user
            //
            if (UserDR.PasswordNeedsChange)
            {
                // The user needs to change their password before they can use OpenPetra
                PetraPrincipal.LoginMessage = SharedConstants.LOGINMUSTCHANGEPASSWORD;
            }

            return(true);
        }
Пример #6
0
        public static bool GetDefaultsForFirstSetup(
            string AClientLanguage,
            out string AUserID,
            out string AFirstName,
            out string ALastName,
            out string ALanguageCode,
            out string AEmailAddress,
            out string AInitialModulePermissions,
            out string AInitialPassword,
            out Int64 ASiteKey
            )
        {
            AUserID  = AFirstName = ALastName = ALanguageCode = AEmailAddress = AInitialModulePermissions = AInitialPassword = String.Empty;
            ASiteKey = -1;

            TDBTransaction t  = new TDBTransaction();
            TDataBase      db = DBAccess.Connect("GetDefaultsForFirstSetup");

            string sql = "SELECT * FROM PUB_s_user " +
                         "WHERE s_user_id_c = 'SYSADMIN'";

            SUserTable usertable = new SUserTable();

            db.ReadTransaction(ref t,
                               delegate
            {
                db.SelectDT(usertable, sql, t);
            });

            db.CloseDBConnection();

            if (usertable.Rows.Count == 1)
            {
                AUserID       = usertable[0].FirstName.Replace(" ", "").Replace("-", "").ToUpper();
                AFirstName    = usertable[0].FirstName;
                ALastName     = usertable[0].LastName;
                ALanguageCode = usertable[0].LanguageCode;
                AEmailAddress = usertable[0].EmailAddress;
                if (AEmailAddress.Contains("+sysadmin@"))
                {
                    AEmailAddress = AEmailAddress.Replace("+sysadmin@", "@");
                }
                else
                {
                    AEmailAddress = AEmailAddress.Replace("@", "+openpetra@");
                }
                AInitialModulePermissions = "PTNRUSER,PTNRADMIN,CONFERENCE,DEVUSER,PERSONNEL,PERSADMIN,SPONSORADMIN,FINANCE-1,FINANCE-2,FINANCE-3,FINANCE-RPT,FIN-EX-RATE";
                AInitialPassword          = TPasswordHelper.GetRandomSecurePassword();
                ASiteKey = 10 * 1000000;

                if (AEmailAddress == String.Empty)
                {
                    AEmailAddress = "*****@*****.**";
                }

                if (AFirstName == String.Empty)
                {
                    AFirstName = "Demo";
                }

                if (ALastName == String.Empty)
                {
                    ALastName = "User";
                }

                if (AUserID == String.Empty)
                {
                    AUserID = "DEMO";
                }

                if (ALanguageCode == "99")
                {
                    ALanguageCode = AClientLanguage.ToUpper();
                    if (ALanguageCode.Contains("-"))
                    {
                        ALanguageCode = ALanguageCode.Substring(ALanguageCode.IndexOf("-") + 1);
                    }
                }

                return(true);
            }

            return(false);
        }
Пример #7
0
        private void ResetPassword(Object Sender, EventArgs e)
        {
            TVerificationResultCollection VerificationResultCollection = null;
            string OneTimePassword = String.Empty;
            bool   RandomSecurePasswordUtilised = false;

            if (FPreviouslySelectedDetailRow == null)
            {
                return;
            }

            if (FPetraUtilsObject.HasChanges)
            {
                MessageBox.Show(
                    Catalog.GetString("It is necessary to save any changes before a user's password can be changed." +
                                      Environment.NewLine + "Please save changes now and then repeat the operation."),
                    CommonDialogsResourcestrings.StrResetUserPasswordTitle,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Stop);
                return;
            }

            string username = GetSelectedDetailRow().UserId;

            var UserChoice = MessageBox.Show(Catalog.GetString(
                                                 "The resetting of a User Password requires the creation of a one-time password that the user will need to enter.\r\n" +
                                                 "OpenPetra can generate a 'random secure' password for this purpose (recommended!). Alternatively, you can come up with such a password manually.\r\n\r\nCreate 'random secure' User Password?"),
                                             Catalog.GetString("User Password Reset"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                                             MessageBoxDefaultButton.Button1);

            switch (UserChoice)
            {
            case DialogResult.Yes:
                OneTimePassword = TPasswordHelper.GetRandomSecurePassword();
                RandomSecurePasswordUtilised = true;

                break;

            case DialogResult.No:
                // only request the password once, since this is the sysadmin changing it.
                // see http://bazaar.launchpad.net/~openpetracore/openpetraorg/trunkhosted/view/head:/csharp/ICT/Petra/Client/MSysMan/Gui/SysManMain.cs
                // for the change password dialog for the normal user
                PetraInputBox input = new PetraInputBox(
                    CommonDialogsResourcestrings.StrResetUserPasswordTitle,
                    String.Format(Catalog.GetString("Please enter a one-time password for user {0}:"), username),
                    "", true);

                if (input.ShowDialog() == DialogResult.OK)
                {
                    OneTimePassword = input.GetAnswer();

                    break;
                }
                else
                {
                    ShowResettingOfUserPwdCancelledMessage();

                    return;
                }

            case DialogResult.Cancel:
                ShowResettingOfUserPwdCancelledMessage();

                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();  // give Windows a chance to update the Cursor

                // Save the new password (server-side checks get performed)
                if (TRemote.MSysMan.Maintenance.WebConnectors.SetUserPassword(username, OneTimePassword, true, true,
                                                                              TClientInfo.ClientComputerName, TClientInfo.ClientIPAddress,
                                                                              out VerificationResultCollection))
                {
                    MessageBox.Show(String.Format(Catalog.GetString(CommonDialogsResourcestrings.StrChangePasswordSuccess +
                                                                    Environment.NewLine +
                                                                    (RandomSecurePasswordUtilised ? Catalog.GetString(
                                                                         "The 'random secure' password will get copied to the clipboard after you have closed this message. Follow the steps lined out in the next message!")
                                                                     +
                                                                     Environment.NewLine : String.Empty) +
                                                                    Environment.NewLine +
                                                                    "(The user must change the new password for a password of his/her choice the next time (s)he logs on.)"),
                                                  username), CommonDialogsResourcestrings.StrResetUserPasswordTitle,
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);

                    if (RandomSecurePasswordUtilised)
                    {
                        CopyPasswordIntoClipboard(OneTimePassword);
                    }

                    // This has been saved on the server so my data is out-of-date - re-loading needed to get new
                    // ModificationId etc:
                    FPreviouslySelectedDetailRow = null;
                    Int32 rowIdx = GetSelectedRowIndex();

                    LoadUsers();

                    grdDetails.SelectRowInGrid(rowIdx);
                }
                else
                {
                    MessageBox.Show(String.Format(CommonDialogsResourcestrings.StrChangePasswordError, username) +
                                    Environment.NewLine + Environment.NewLine +
                                    VerificationResultCollection.BuildVerificationResultString(),
                                    CommonDialogsResourcestrings.StrResetUserPasswordTitle,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }