コード例 #1
0
        public static bool ReloadUserInfo()
        {
            TDBTransaction  Transaction = new TDBTransaction();
            TDataBase       db          = DBAccess.Connect("ReloadUserInfo");
            TPetraPrincipal UserDetails = null;
            bool            SubmitOK    = false;

            try
            {
                db.WriteTransaction(ref Transaction, ref SubmitOK,
                                    delegate
                {
                    LoadUser(UserInfo.GetUserInfo().UserID, out UserDetails, Transaction);
                });

                UserInfo.SetUserInfo(UserDetails);

                SubmitOK = true;
            }
            catch (Exception Exp)
            {
                TLogging.Log("Exception occured in ReloadCachedUserInfo: " + Exp.ToString());
                throw;
            }

            return(true);
        }
コード例 #2
0
ファイル: UserManagement.cs プロジェクト: hoangduit/openpetra
        public static bool PasswordAuthentication(String AUserID, String APassword)
        {
            TPetraPrincipal PetraPrincipal = null;

            SUserRow UserDR = TUserManagerWebConnector.LoadUser(AUserID, out PetraPrincipal);
            string   UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

            if (UserAuthenticationMethod == "OpenPetraDBSUser")
            {
                if (TUserManagerWebConnector.CreateHashOfPassword(String.Concat(APassword,
                                                                                UserDR.PasswordSalt)) != UserDR.PasswordHash)
                {
                    return(false);
                }
            }
            else
            {
                IUserAuthentication auth = TUserManagerWebConnector.LoadAuthAssembly(UserAuthenticationMethod);

                string ErrorMessage;

                if (!auth.AuthenticateUser(AUserID, APassword, out ErrorMessage))
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #3
0
ファイル: Navigation.cs プロジェクト: mechandavid/openpetra
        /// <summary>
        /// checks if the user has access to the navigation node
        /// </summary>
        public bool HasAccessPermission(XmlNode ANode, TPetraPrincipal AUserInfo, bool ACheckLedgerPermissions)
        {
            // TODO: if this is an action node, eg. opens a screen, check the static function that tells RequiredPermissions of the screen

            string PermissionsRequired = TXMLParser.GetAttributeRecursive(ANode, "PermissionsRequired", true);

            while (PermissionsRequired.Length > 0)
            {
                string PermissionRequired = StringHelper.GetNextCSV(ref PermissionsRequired);

                if (!AUserInfo.IsInModule(PermissionRequired))
                {
                    return(false);
                }
            }

            if (ACheckLedgerPermissions)
            {
                if (TXMLParser.GetAttributeRecursive(ANode, "DependsOnLedger", true).ToLower() == "true")
                {
                    // check if the user has permissions for this ledger
                    Int32 LedgerNumber = TXMLParser.GetIntAttribute(ANode, "LedgerNumber");

                    if (LedgerNumber != -1)
                    {
                        if (!AUserInfo.IsInModule(FormatLedgerNumberForModuleAccess(LedgerNumber)))
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
コード例 #4
0
        /// <summary>
        /// Initialize the Petra server and connect to the database
        /// </summary>
        /// <param name="AConfigName">just provide the server config file, plus AutoLogin and AutoLoginPasswd</param>
        public static TServerManager Connect(string AConfigName)
        {
            if (File.Exists(AConfigName))
            {
                new TAppSettingsManager(AConfigName);
            }
            else
            {
                new TAppSettingsManager();
            }

            new TLogging(TAppSettingsManager.GetValue("Server.LogFile"));

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TServerManager ServerManager = new TServerManager();

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                        TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort,
                                                        TSrvSetting.PostgreSQLDatabaseName,
                                                        TSrvSetting.DBUsername, TSrvSetting.DBPassword, "");

            bool            SystemEnabled;
            int             ProcessID;
            TPetraPrincipal UserInfo = (TPetraPrincipal)TClientManager.PerformLoginChecks(TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                                                                                          TAppSettingsManager.GetValue("AutoLoginPasswd"),
                                                                                          "NUNITTEST", "127.0.0.1", out ProcessID, out SystemEnabled);

            if (FDomain != null)
            {
                FDomain.StopClientAppDomain();
            }

            TClientManager ClientManager = new TClientManager();

            DomainManager.UClientManagerCallForwarderRef = new TClientManagerCallForwarder(ClientManager);

            // do the same as in Ict.Petra.Server.App.Main.TRemoteLoader.LoadDomainManagerAssembly
            FDomain = new TClientDomainManager("0",
                                               TClientServerConnectionType.csctLocal,
                                               DomainManager.UClientManagerCallForwarderRef,
                                               new TSystemDefaultsCache(),
                                               new TCacheableTablesManager(null),
                                               UserInfo);
            FDomain.InitAppDomain(TSrvSetting.ServerSettings);

            new TCallForwarding();

            // we don't need to establish the database connection anymore
            // FDomain.EstablishDBConnection();

            return(ServerManager);
        }
コード例 #5
0
        /// <summary>
        /// Tests whether the current user has access to a particular Partner.
        /// </summary>
        /// <remarks>
        /// <para>Corresponds to Progress 4GL Method 'CanAccessPartner' in
        /// common/sp_partn.p</para>
        /// <para>A server-side implementation of this Method exists that has only the
        /// <paramref name="APartnerRow" />parameter as an Argument. It
        /// looks up the Foundation Row on its own if this is needed.</para>
        /// </remarks>
        /// <param name="APartnerRow">Partner for which access should be checked for.</param>
        /// <param name="AIsFoundation">Set to true if Partner is a Foundation.</param>
        /// <param name="AFoundationRow">Foundation Row needs to be passed in
        /// if Partner is a Foundation.</param>
        /// <returns><see cref="TPartnerAccessLevelEnum.palGranted" /> if access
        /// to the Partner is granted, otherwise a different
        /// <see cref="TPartnerAccessLevelEnum" /> value.</returns>
        public static TPartnerAccessLevelEnum CanAccessPartner(PPartnerRow APartnerRow, bool AIsFoundation,
                                                               PFoundationRow AFoundationRow)
        {
            TPetraPrincipal userinfo = UserInfo.GetUserInfo();

            if ((APartnerRow.Restricted == PARTNER_RESTRICTED_TO_USER) &&
                !((APartnerRow.UserId == userinfo.UserID) || userinfo.IsInModule("SYSMAN")))
            {
                TLogging.LogAtLevel(6,
                                    "CanAccessPartner: Access DENIED - Partner " + APartnerRow.PartnerKey.ToString() + " is restriced to User " +
                                    APartnerRow.UserId + "!");
                return(TPartnerAccessLevelEnum.palRestrictedToUser);
            }
            else if ((APartnerRow.Restricted == PARTNER_RESTRICTED_TO_GROUP) &&
                     !((userinfo.IsInGroup(APartnerRow.GroupId)) || userinfo.IsInModule("SYSMAN")))
            {
                TLogging.LogAtLevel(6,
                                    "CanAccessPartner: Access DENIED - Partner " + APartnerRow.PartnerKey.ToString() + " is restriced to Group " +
                                    APartnerRow.GroupId +
                                    "!");
                return(TPartnerAccessLevelEnum.palRestrictedToGroup);
            }

            if (APartnerRow.PartnerClass == SharedTypes.PartnerClassEnumToString(TPartnerClass.ORGANISATION))
            {
                if (AIsFoundation)
                {
                    if (AFoundationRow != null)
                    {
                        if (!CheckFoundationSecurity(AFoundationRow))
                        {
                            TLogging.LogAtLevel(6,
                                                "CanAccessPartner: Access DENIED - Partner " + APartnerRow.PartnerKey.ToString() +
                                                " is restriced by Foundation Ownership!");
                            return(TPartnerAccessLevelEnum.palRestrictedByFoundationOwnership);
                        }
                    }
                    else
                    {
                        throw new System.ArgumentException("AFoundationRow must not be null if AIsFoundation is true");
                    }
                }
            }

            TLogging.LogAtLevel(6, "CanAccessPartner: Access to Partner " + APartnerRow.PartnerKey.ToString() + " is GRANTED!");
            return(TPartnerAccessLevelEnum.palGranted);
        }
コード例 #6
0
        internal static SUserRow LoadUser(String AUserID, out TPetraPrincipal APetraPrincipal, TDBTransaction ATransaction)
        {
            SUserRow ReturnValue = LoadUser(AUserID, ATransaction);

            APetraPrincipal = new TPetraPrincipal(AUserID, TGroupManager.LoadUserGroups(
                                                      AUserID, ATransaction), TModuleAccessManager.LoadUserModules(AUserID, ATransaction));
            if (!ReturnValue.IsPartnerKeyNull())
            {
                APetraPrincipal.PartnerKey = ReturnValue.PartnerKey;
            }

/*
 *          TLogging.LogAtLevel (8, "APetraPrincipal.IsTableAccessOK(tapMODIFY, 'p_person'): " +
 *                  APetraPrincipal.IsTableAccessOK(TTableAccessPermission.tapMODIFY, "p_person").ToString());
 */
            return(ReturnValue);
        }
コード例 #7
0
        internal static SUserRow LoadUser(String AUserID, out TPetraPrincipal APetraPrincipal, TDBTransaction ATransaction)
        {
            SUserRow ReturnValue;

            TPetraIdentity PetraIdentity;

            ReturnValue = LoadUser(AUserID, out PetraIdentity, ATransaction);

            APetraPrincipal = new TPetraPrincipal(PetraIdentity, TGroupManager.LoadUserGroups(
                                                      AUserID, ATransaction), TTableAccessPermissionManager.LoadTableAccessPermissions(
                                                      AUserID, ATransaction), TModuleAccessManager.LoadUserModules(AUserID, ATransaction));

/*
 *          TLogging.LogAtLevel (8, "APetraPrincipal.IsTableAccessOK(tapMODIFY, 'p_person'): " +
 *                  APetraPrincipal.IsTableAccessOK(TTableAccessPermission.tapMODIFY, "p_person").ToString());
 */
            return(ReturnValue);
        }
コード例 #8
0
        /// <summary>
        /// checks if the user has access to the navigation node
        /// </summary>
        public bool HasAccessPermission(XmlNode ANode, TPetraPrincipal AUserInfo)
        {
            // TODO: if this is an action node, eg. opens a screen, check the static function that tells RequiredPermissions of the screen

            string PermissionsRequired = TXMLParser.GetAttributeRecursive(ANode, "PermissionsRequired", true);

            while (PermissionsRequired.Length > 0)
            {
                string PermissionRequired = StringHelper.GetNextCSV(ref PermissionsRequired);

                if (!AUserInfo.IsInModule(PermissionRequired))
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #9
0
ファイル: UserManager.cs プロジェクト: Kingefosa/openpetra
        public static SUserRow LoadUser(String AUserID, out TPetraPrincipal APetraPrincipal)
        {
            SUserRow ReturnValue;

            Ict.Petra.Shared.Security.TPetraIdentity PetraIdentity;

            ReturnValue = LoadUser(AUserID, out PetraIdentity);

            APetraPrincipal = new TPetraPrincipal(PetraIdentity, TGroupManager.LoadUserGroups(
                                                      AUserID), TTableAccessPermissionManager.LoadTableAccessPermissions(
                                                      AUserID), TModuleAccessManager.LoadUserModules(AUserID));

/*
 *          TLogging.LogAtLevel (8, "APetraPrincipal.IsTableAccessOK(tapMODIFY, 'p_person'): " +
 *                  APetraPrincipal.IsTableAccessOK(TTableAccessPermission.tapMODIFY, "p_person").ToString());
 */
            return(ReturnValue);
        }
コード例 #10
0
ファイル: Navigation.cs プロジェクト: mechandavid/openpetra
        private Dictionary <string, object> AddFolder(XmlNode AFolderNode, TPetraPrincipal AUserInfo)
        {
            // TODO icon?

            // enabled/disabled based on permissions
            bool enabled = true;

            if ((TYml2Xml.HasAttribute(AFolderNode, "Enabled")) &&
                (TYml2Xml.GetAttribute(AFolderNode, "Enabled").ToLower() == "false"))
            {
                enabled = false;
            }
            else
            {
                enabled = HasAccessPermission(AFolderNode, AUserInfo, false);
            }

            Dictionary <string, object> folder = new Dictionary <string, object>();

            folder.Add("caption", GetCaption(AFolderNode, true));
            folder.Add("icon", TYml2Xml.GetAttribute(AFolderNode, "fa-icon"));

            if (!enabled)
            {
                folder.Add("enabled", "false");
            }

            Dictionary <string, object> items = new Dictionary <string, object>();

            foreach (XmlNode child in AFolderNode.ChildNodes)
            {
                Dictionary <string, object> item = new Dictionary <string, object>();
                item.Add("caption", GetCaption(child, true));
                if (child.ChildNodes.Count == 1 && child.ChildNodes[0].ChildNodes.Count == 0)
                {
                    item.Add("form", child.ChildNodes[0].Name);
                }
                items.Add(child.Name, item);
            }

            folder.Add("items", items);

            return(folder);
        }
コード例 #11
0
        /// <summary>
        /// Tests whether the current user has access to a particular Foundation.
        /// </summary>
        /// <remarks>Corresponds to Progress 4GL Method 'CheckFoundationSecurity' in
        /// common/sp_partn.p</remarks>
        /// <param name="AFoundationOwner1Key">PartnerKey of the first owner of the Foundation.
        /// Pass in 0 if there is no first owner.</param>
        /// <param name="AFoundationOwner2Key">PartnerKey of the second owner of the Foundation
        /// Pass in 0 if there is no second owner.</param>
        /// <returns>True if the current user has access to the passed in Foundation,
        /// otherwise false.</returns>
        public static bool CheckFoundationSecurity(Int64 AFoundationOwner1Key, Int64 AFoundationOwner2Key)
        {
            Boolean         ReturnValue;
            TPetraPrincipal userinfo = UserInfo.GetUserInfo();

            ReturnValue = false;

            if ((AFoundationOwner1Key == 0) && (AFoundationOwner2Key == 0))
            {
                TLogging.Log("CheckFoundationSecurity: None of the Owners is set.");

                if (userinfo.IsInModule(SharedConstants.PETRAMODULE_DEVUSER) ||
                    (userinfo.IsInModule(SharedConstants.PETRAMODULE_DEVADMIN)))
                {
                    TLogging.Log("CheckFoundationSecurity: User is member of DEVUSER or DEVADMIN Module");
                    ReturnValue = true;
                }
            }
            else
            {
                TLogging.Log("CheckFoundationSecurity: One of the Owners is set!");

                if (userinfo.IsInModule(SharedConstants.PETRAMODULE_DEVADMIN))
                {
                    TLogging.Log("CheckFoundationSecurity: User is member of DEVADMIN Module");
                    ReturnValue = true;
                }
                else
                {
                    TLogging.Log("CheckFoundationSecurity: User is NOT member of DEVADMIN Module");

                    if ((userinfo.PartnerKey == AFoundationOwner1Key) ||
                        (userinfo.PartnerKey == AFoundationOwner2Key))
                    {
                        TLogging.Log("CheckFoundationSecurity: User is Owner1 or Owner2");
                        ReturnValue = true;
                    }
                }
            }

            return(ReturnValue);
        }
コード例 #12
0
ファイル: Navigation.cs プロジェクト: mechandavid/openpetra
        /// <summary>
        /// load the navigation ready to be converted to JSON
        /// </summary>
        public Dictionary <string, object> LoadNavigationUI(bool ADontUseDefaultLedger = false)
        {
            TPetraPrincipal userinfo = UserInfo.GetUserInfo();

            // Force re-calculation of available Ledgers and correct setting of FCurrentLedger
            FLedgersAvailableToUser = null;

            XmlNode MainMenuNode   = BuildNavigationXml(ADontUseDefaultLedger);
            XmlNode DepartmentNode = MainMenuNode.FirstChild;

            Dictionary <string, object> result = new Dictionary <string, object>();

            while (DepartmentNode != null)
            {
                result.Add(DepartmentNode.Name, AddFolder(DepartmentNode, userinfo));

                DepartmentNode = DepartmentNode.NextSibling;
            }

            return(result);
        }
コード例 #13
0
        public static TPetraPrincipal ReloadCachedUserInfo()
        {
            TDBTransaction  ReadTransaction = null;
            TPetraPrincipal UserDetails     = null;

            try
            {
                DBAccess.SimpleAutoReadTransactionWrapper(IsolationLevel.ReadCommitted, "ReloadCachedUserInfo", out ReadTransaction, delegate
                {
                    LoadUser(UserInfo.GUserInfo.UserID, out UserDetails, ReadTransaction);
                });

                UserInfo.GUserInfo = UserDetails;
            }
            catch (Exception Exp)
            {
                TLogging.Log("Exception occured in ReloadCachedUserInfo: " + Exp.ToString());
                throw;
            }

            return(UserInfo.GUserInfo);
        }
コード例 #14
0
ファイル: Navigation.cs プロジェクト: weiplanet/openpetra
        private Dictionary <string, object> AddFolder(XmlNode AFolderNode, TPetraPrincipal AUserInfo)
        {
            // enabled/disabled based on permissions
            bool enabled = true;

            if ((TYml2Xml.HasAttribute(AFolderNode, "Enabled")) &&
                (TYml2Xml.GetAttribute(AFolderNode, "Enabled").ToLower() == "false"))
            {
                enabled = false;
            }
            else
            {
                enabled = HasAccessPermission(AFolderNode, AUserInfo);
            }

            if (!enabled)
            {
                return(null);
            }

            Dictionary <string, object> folder = new Dictionary <string, object>();

            folder.Add("caption", GetCaption(AFolderNode, true));
            folder.Add("icon", TYml2Xml.GetAttribute(AFolderNode, "fa-icon"));

            if (!enabled)
            {
                folder.Add("enabled", "false");
            }

            folder.Add("items", GetChildItems(AFolderNode, AFolderNode.Name, AUserInfo));

            if (File.Exists(TAppSettingsManager.GetValue("Forms.Path") + "/" + AFolderNode.Name + ".html"))
            {
                folder["htmlexists"] = true;
            }

            return(folder);
        }
コード例 #15
0
ファイル: Navigation.cs プロジェクト: weiplanet/openpetra
        /// <summary>
        /// load the navigation ready to be converted to JSON
        /// </summary>
        public Dictionary <string, object> LoadNavigationUI()
        {
            TPetraPrincipal userinfo = UserInfo.GetUserInfo();

            XmlNode MainMenuNode   = BuildNavigationXml();
            XmlNode DepartmentNode = MainMenuNode.FirstChild;

            Dictionary <string, object> result = new Dictionary <string, object>();

            while (DepartmentNode != null)
            {
                Dictionary <string, object> Folder = AddFolder(DepartmentNode, userinfo);

                if (Folder != null)
                {
                    result.Add(DepartmentNode.Name, Folder);
                }

                DepartmentNode = DepartmentNode.NextSibling;
            }

            return(result);
        }
コード例 #16
0
ファイル: Navigation.cs プロジェクト: weiplanet/openpetra
        /// <summary>
        /// checks if the user has access to the navigation node
        /// </summary>
        public bool HasAccessPermission(XmlNode ANode, TPetraPrincipal AUserInfo)
        {
            // TODO: if this is an action node, eg. opens a screen, check the static function that tells RequiredPermissions of the screen

            string PermissionsRequired = TXMLParser.GetAttributeRecursive(ANode, "PermissionsRequired", true);

            try
            {
                if (PermissionsRequired.StartsWith("\"") && PermissionsRequired.EndsWith("\""))
                {
                    PermissionsRequired = PermissionsRequired.Substring(1, PermissionsRequired.Length - 2);
                }

                if (PermissionsRequired.Contains(",") && !PermissionsRequired.EndsWith(")"))
                {
                    PermissionsRequired = "AND(" + PermissionsRequired + ")";
                }

                if (PermissionsRequired == "")
                {
                    PermissionsRequired = "USER";
                }

                TSecurityChecks.CheckUserModulePermissions(PermissionsRequired, "UINavigation");
                return(true);
            }
            catch (ESecurityModuleAccessDeniedException)
            {
                return(false);
            }
            catch (ArgumentException e)
            {
                TLogging.Log("Issue for node " + ANode.Name + Environment.NewLine +
                             e.ToString());
                return(false);
            }
        }
コード例 #17
0
ファイル: ServerManager.cs プロジェクト: merbst/openpetra
        /// <summary>
        /// Initialises Logging and parses Server settings from different sources.
        /// </summary>
        public TServerManager() : base()
        {
            // Create SystemDefaults Cache
            TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache();
            DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate = @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault;

            TCacheableTablesManager.InitializeUnit();
            TCacheableTablesManager.GCacheableTablesManager = new TCacheableTablesManager(new TDelegateSendClientTask(TClientManager.QueueClientTask));

            Assembly SysManAssembly   = Assembly.Load("Ict.Petra.Server.lib.MSysMan");
            Type     ImportExportType = SysManAssembly.GetType("Ict.Petra.Server.MSysMan.ImportExport.TImportExportManager");

            FImportExportManager = (IImportExportManager)Activator.CreateInstance(ImportExportType,
                                                                                  (BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod),
                                                                                  null,
                                                                                  null,
                                                                                  null);

            Assembly DBUpgradesAssembly  = Assembly.Load("Ict.Petra.Server.lib.MSysMan.DBUpgrades");
            Type     DatabaseUpgradeType = DBUpgradesAssembly.GetType("Ict.Petra.Server.MSysMan.DBUpgrades.TDBUpgrades");

            FDBUpgrades = (IDBUpgrades)Activator.CreateInstance(DatabaseUpgradeType,
                                                                (BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod),
                                                                null,
                                                                null,
                                                                null);

            Type UserManagement = SysManAssembly.GetType("Ict.Petra.Server.MSysMan.Maintenance.UserManagement.TUserManager");

            FUserManager = (IUserManager)Activator.CreateInstance(UserManagement,
                                                                  (BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod),
                                                                  null,
                                                                  null,
                                                                  null);

            TClientManager.InitializeStaticVariables(TSystemDefaultsCache.GSystemDefaultsCache,
                                                     FUserManager,
                                                     new TErrorLog(),
                                                     new TLoginLog(),
                                                     new TMaintenanceLogonMessage(),
                                                     ExceptionHandling_DBConnectionBrokenCallback);

            // Set up the SYSADMIN user (#5650).
            // (This is required for all SubmitChanges method calls in the server's main AppDomain because
            // that Method references UserInfo.GUserInfo)
            // When using this with the Web Services, this does not apply to the threads for each session.
            TPetraIdentity PetraIdentity = new TPetraIdentity(
                "SYSADMIN", "", "", "", "",
                DateTime.MinValue, DateTime.MinValue, DateTime.MinValue,
                0, -1, -1, false, false, false);

            TPetraPrincipal Principal = new TPetraPrincipal(PetraIdentity, null);

            UserInfo.GUserInfo = Principal;

            //
            // Set up 'Timed Processing'
            //
            TTimedProcessing.DailyStartTime24Hrs = TAppSettingsManager.GetValue("Server.Processing.DailyStartTime24Hrs", "00:30");

            if (TAppSettingsManager.GetBoolean("Server.Processing.PartnerReminders.Enabled", true))
            {
                Assembly PartnerProcessingAssembly = Assembly.Load("Ict.Petra.Server.lib.MPartner.processing");
                Type     PartnerReminderClass      = PartnerProcessingAssembly.GetType("Ict.Petra.Server.MPartner.Processing.TProcessPartnerReminders");
                TTimedProcessing.AddProcessingJob(
                    "TProcessPartnerReminders",
                    (TTimedProcessing.TProcessDelegate)Delegate.CreateDelegate(
                        typeof(TTimedProcessing.TProcessDelegate),
                        PartnerReminderClass,
                        "Process"));
            }

            if (TAppSettingsManager.GetBoolean("Server.Processing.AutomatedIntranetExport.Enabled", false))
            {
                Assembly CommonProcessingAssembly = Assembly.Load("Ict.Petra.Server.lib.MCommon.processing");
                Type     IntranetExportClass      = CommonProcessingAssembly.GetType("Ict.Petra.Server.MCommon.Processing.TProcessAutomatedIntranetExport");
                TTimedProcessing.AddProcessingJob(
                    "TProcessAutomatedIntranetExport",
                    (TTimedProcessing.TProcessDelegate)Delegate.CreateDelegate(
                        typeof(TTimedProcessing.TProcessDelegate),
                        IntranetExportClass,
                        "Process"));
            }

            if (TAppSettingsManager.GetBoolean("Server.Processing.DataChecks.Enabled", false))
            {
                Assembly CommonProcessingAssembly = Assembly.Load("Ict.Petra.Server.lib.MCommon.processing");
                Type     ProcessDataChecksClass   = CommonProcessingAssembly.GetType("Ict.Petra.Server.MCommon.Processing.TProcessDataChecks");
                TTimedProcessing.AddProcessingJob(
                    "TProcessDataChecks",
                    (TTimedProcessing.TProcessDelegate)Delegate.CreateDelegate(
                        typeof(TTimedProcessing.TProcessDelegate),
                        ProcessDataChecksClass,
                        "Process"));
            }
        }
コード例 #18
0
ファイル: SessionManager.cs プロジェクト: weblate/openpetra
 static private void SetUserInfoForSession(TPetraPrincipal userinfo)
 {
     TSession.SetVariable("UserInfo", userinfo);
 }
コード例 #19
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);
        }
コード例 #20
0
ファイル: Navigation.cs プロジェクト: mechandavid/openpetra
        private void AddNavigationForEachLedger(XmlNode AMenuNode, ALedgerTable AAvailableLedgers, bool ADontUseDefaultLedger)
        {
            XmlNode         childNode = AMenuNode.FirstChild;
            int             PotentialCurrentLedger;
            ALedgerRow      ProcessedLedger;
            XmlAttribute    enabledAttribute;
            bool            LedgersAvailableToUserCreatedInThisIteration = false;
            TPetraPrincipal userinfo = UserInfo.GetUserInfo();

            //Iterate through all children nodes of the node
            while (childNode != null)
            {
                if (TXMLParser.GetAttribute(childNode, "DependsOnLedger").ToLower() == "true")
                {
                    // If there is more than one Ledger in the system, show a 'Select Ledger' Collapsible Panel with a Task (=LinkLabel)
                    // for each Ledger.
                    if (false && (AAvailableLedgers.Rows.Count > 1))
                    {
                        LedgersAvailableToUserCreatedInThisIteration = false;
                        AAvailableLedgers.DefaultView.Sort           = ALedgerTable.GetLedgerNumberDBName() + " ASC";

                        FMultiLedgerSite = true;

                        // Create 'Select Ledger' Node
                        XmlAttribute LabelAttributeLedger = childNode.OwnerDocument.CreateAttribute("Label");
                        XmlElement   SelLedgerElmnt       = childNode.OwnerDocument.CreateElement("SelectLedger");
                        XmlNode      SelectLedgerNode     = childNode.AppendChild(SelLedgerElmnt);
                        SelectLedgerNode.Attributes.Append(LabelAttributeLedger);
                        SelectLedgerNode.Attributes["Label"].Value = Catalog.GetString("Select Ledger");

                        // Create 1..n 'Ledger xyz' Nodes
                        foreach (DataRowView Drv in AAvailableLedgers.DefaultView)
                        {
                            ProcessedLedger = (ALedgerRow)Drv.Row;

                            XmlElement   SpecificLedgerElmnt          = childNode.OwnerDocument.CreateElement("Ledger" + ProcessedLedger.LedgerNumber);
                            XmlNode      SpecificLedgerNode           = SelectLedgerNode.AppendChild(SpecificLedgerElmnt);
                            XmlAttribute LabelAttributeSpecificLedger = childNode.OwnerDocument.CreateAttribute("Label");
                            SpecificLedgerNode.Attributes.Append(LabelAttributeSpecificLedger);
                            XmlAttribute ledgerNumberAttribute = childNode.OwnerDocument.CreateAttribute("LedgerNumber");
                            ledgerNumberAttribute.Value = ProcessedLedger.LedgerNumber.ToString();
                            SpecificLedgerNode.Attributes.Append(ledgerNumberAttribute);
                            XmlAttribute ledgerNameAttribute = childNode.OwnerDocument.CreateAttribute("LedgerName");
                            ledgerNameAttribute.Value = ProcessedLedger.LedgerName;
                            SpecificLedgerNode.Attributes.Append(ledgerNameAttribute);

                            if (ProcessedLedger.LedgerName != String.Empty)
                            {
                                SpecificLedgerNode.Attributes["Label"].Value = String.Format(Catalog.GetString(
                                                                                                 "Ledger {0} (#{1})"), ProcessedLedger.LedgerName, ProcessedLedger.LedgerNumber);
                            }
                            else
                            {
                                SpecificLedgerNode.Attributes["Label"].Value = String.Format(Catalog.GetString(
                                                                                                 "Ledger #{0}"), ProcessedLedger.LedgerNumber);
                            }

                            // Check access permission for Ledger
                            if (!HasAccessPermission(SpecificLedgerNode, userinfo, true))
                            {
                                enabledAttribute       = childNode.OwnerDocument.CreateAttribute("Enabled");
                                enabledAttribute.Value = "false";
                                SpecificLedgerNode.Attributes.Append(enabledAttribute);
                            }
                            else
                            {
                                if (FLedgersAvailableToUser == null)
                                {
                                    // (Re-)Calculate which Ledgers the user has access to
                                    FLedgersAvailableToUser = new List <string>();
                                    LedgersAvailableToUserCreatedInThisIteration = true;
                                }

                                if (LedgersAvailableToUserCreatedInThisIteration)
                                {
                                    // Add Ledger to the List of Ledgers that are available to the user
                                    if (!FLedgersAvailableToUser.Contains(FormatLedgerNumberForModuleAccess(ProcessedLedger.LedgerNumber)))
                                    {
                                        FLedgersAvailableToUser.Add(FormatLedgerNumberForModuleAccess(ProcessedLedger.LedgerNumber));
                                    }
                                }
                            }
                        }

                        if ((LedgersAvailableToUserCreatedInThisIteration) ||
                            (FLedgersAvailableToUser == null))
                        {
                            if (!ADontUseDefaultLedger)
                            {
                                // Set the 'Current Ledger' to the users' Default Ledger, or if he/she hasn't got one, to the first Ledger of the Site.
                                PotentialCurrentLedger = TUserDefaults.GetInt32Default(TUserDefaults.FINANCE_DEFAULT_LEDGERNUMBER,
                                                                                       ((ALedgerRow)AAvailableLedgers.DefaultView[0].Row).LedgerNumber);

                                if ((FLedgersAvailableToUser != null) &&
                                    (FLedgersAvailableToUser.Contains(FormatLedgerNumberForModuleAccess(PotentialCurrentLedger))))
                                {
                                    FCurrentLedger = PotentialCurrentLedger;
                                }
                                else
                                {
                                    if (FLedgersAvailableToUser != null)
                                    {
                                        FCurrentLedger = Convert.ToInt32(FLedgersAvailableToUser[0].Substring(6)); // Skip "LEDGER"
                                    }
                                    else                                                                           // = no Ledgers available to the user at all!
                                    {
                                        FCurrentLedger = LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                                    }
                                }
                            }
                        }
                    }
                    else if (AAvailableLedgers.Rows.Count == 1)
                    {
                        // Check access permission for Ledger
                        if (userinfo.IsInModule(FormatLedgerNumberForModuleAccess(AAvailableLedgers[0].LedgerNumber)))
                        {
                            // Set the 'Current Ledger' to the only Ledger of the Site.
                            FCurrentLedger = AAvailableLedgers[0].LedgerNumber;
                        }
                        else   // = no Ledgers available to the user at all!
                        {
                            FCurrentLedger = LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                        }
                    }
                    else   // = no Ledgers available to the user at all!
                    {
                        FCurrentLedger = LEDGERNUMBER_NO_ACCESS_TO_ANY_LEDGER;
                    }

                    childNode = childNode.NextSibling;
                }
                else
                {
                    // Recurse into deeper levels!
                    AddNavigationForEachLedger(childNode, AAvailableLedgers, ADontUseDefaultLedger);

                    childNode = childNode.NextSibling;
                }
            }
        }
コード例 #21
0
ファイル: Navigation.cs プロジェクト: weiplanet/openpetra
        private Dictionary <string, object> GetChildItems(XmlNode AFolderNode, string APath, TPetraPrincipal AUserInfo)
        {
            Dictionary <string, object> items = new Dictionary <string, object>();

            foreach (XmlNode child in AFolderNode.ChildNodes)
            {
                if (!HasAccessPermission(child, AUserInfo))
                {
                    continue;
                }

                Dictionary <string, object> item = new Dictionary <string, object>();
                item.Add("caption", GetCaption(child, true));
                if (child.ChildNodes.Count > 0)
                {
                    item.Add("items", GetChildItems(child, APath + "/" + child.Name, AUserInfo));
                }
                else
                {
                    item.Add("form", child.Name);
                }

                string Action = TXMLParser.GetAttribute(child, "Action");

                if (Action.Length > 0)
                {
                    item.Add("action", Action);
                }

                string Icon = TXMLParser.GetAttributeRecursive(child, "fa-icon", false);

                if (Icon.Length > 0)
                {
                    item.Add("icon", Icon);
                }

                string form = TXMLParser.GetAttribute(child, "Form");

                if (form.Length > 0)
                {
                    item["form"] = form;
                }

                string path = TXMLParser.GetAttributeRecursive(child, "Path", false);

                if (path.Length == 0)
                {
                    path = APath;
                }

                item.Add("path", path);

                if (File.Exists(TAppSettingsManager.GetValue("Forms.Path") + "/" + path.Replace('_', '/') + "/" + child.Name + ".html"))
                {
                    item["htmlexists"] = true;
                }

                items.Add(child.Name, item);
            }

            return(items);
        }
コード例 #22
0
ファイル: UserManager.cs プロジェクト: Kingefosa/openpetra
        public static TPetraPrincipal PerformUserAuthentication(String AUserID, String APassword, out Boolean ASystemEnabled)
        {
            DateTime        LoginDateTime;
            TPetraPrincipal PetraPrincipal = null;

            Int32 AProcessID = -1;

            ASystemEnabled = true;

            string EmailAddress = AUserID;

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

            try
            {
                SUserRow UserDR = LoadUser(AUserID, out PetraPrincipal);

                // Already assign the global variable here, because it is needed for SUserAccess.SubmitChanges later in this function
                UserInfo.GUserInfo = PetraPrincipal;

                // Check if user is retired
                if (PetraPrincipal.PetraIdentity.Retired)
                {
                    throw new EUserRetiredException(StrInvalidUserIDPassword);
                }

                int FailedLoginsUntilRetire = Convert.ToInt32(
                    TSystemDefaults.GetSystemDefault(SharedConstants.SYSDEFAULT_FAILEDLOGINS_UNTIL_RETIRE, "10"));

                // Console.WriteLine('PetraPrincipal.PetraIdentity.FailedLogins: ' + PetraPrincipal.PetraIdentity.FailedLogins.ToString +
                // '; PetraPrincipal.PetraIdentity.Retired: ' + PetraPrincipal.PetraIdentity.Retired.ToString);
                // Check if user should be autoretired
                if ((PetraPrincipal.PetraIdentity.FailedLogins >= FailedLoginsUntilRetire) && ((!PetraPrincipal.PetraIdentity.Retired)))
                {
                    UserDR.Retired      = true;
                    UserDR.FailedLogins = 0;

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

                    throw new EAccessDeniedException(StrInvalidUserIDPassword);
                }

                // Check SystemLoginStatus (Petra enabled/disabled) in the SystemStatus table (always holds only one record)
                Boolean            NewTransaction = false;
                SSystemStatusTable SystemStatusDT;

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

                try
                {
                    SystemStatusDT = SSystemStatusAccess.LoadAll(ReadTransaction);
                }
                finally
                {
                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(7, "TUserManager.PerformUserAuthentication: committed own transaction.");
                    }
                }

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

                    if (PetraPrincipal.IsInGroup("SYSADMIN"))
                    {
                        PetraPrincipal.LoginMessage =
                            String.Format(StrSystemDisabled1,
                                          SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine + StrSystemDisabled2Admin;
                    }
                    else
                    {
                        TLoginLog.AddLoginLogEntry(AUserID, "System disabled", true, out AProcessID);

                        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()));
                    }
                }

                if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken"))
                {
                    // Login via server admin console authenticated by file token
                }
                else
                {
                    string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false);

                    if (UserAuthenticationMethod == "OpenPetraDBSUser")
                    {
                        // TODO 1 oChristianK cSecurity : Perform user authentication by verifying password hash in the DB
                        // see also ICTPetraWiki: Todo_Petra.NET#Implement_Security_.7B2.7D_.5BChristian.5D
                        if (CreateHashOfPassword(String.Concat(APassword,
                                                               UserDR.PasswordSalt)) != UserDR.PasswordHash)
                        {
                            // increase failed logins
                            UserDR.FailedLogins++;
                            LoginDateTime          = DateTime.Now;
                            UserDR.FailedLoginDate = LoginDateTime;
                            UserDR.FailedLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
                            SaveUser(AUserID, (SUserTable)UserDR.Table);

                            throw new EPasswordWrongException(StrInvalidUserIDPassword);
                        }
                    }
                    else
                    {
                        IUserAuthentication auth = LoadAuthAssembly(UserAuthenticationMethod);

                        string ErrorMessage;

                        if (!auth.AuthenticateUser(EmailAddress, APassword, out ErrorMessage))
                        {
                            UserDR.FailedLogins++;
                            LoginDateTime          = DateTime.Now;
                            UserDR.FailedLoginDate = LoginDateTime;
                            UserDR.FailedLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
                            SaveUser(AUserID, (SUserTable)UserDR.Table);

                            throw new EPasswordWrongException(ErrorMessage);
                        }
                    }
                }

                // Save successful login
                LoginDateTime        = DateTime.Now;
                UserDR.LastLoginDate = LoginDateTime;
                UserDR.LastLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime);
                UserDR.FailedLogins  = 0;

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

                PetraPrincipal.PetraIdentity.CurrentLogin = LoginDateTime;

                // PetraPrincipal.PetraIdentity.FailedLogins := 0;

                if (PetraPrincipal.IsInGroup("SYSADMIN"))
                {
                    TLoginLog.AddLoginLogEntry(AUserID, "Successful  SYSADMIN", out AProcessID);
                }
                else
                {
                    TLoginLog.AddLoginLogEntry(AUserID, "Successful", out AProcessID);
                }

                PetraPrincipal.ProcessID = AProcessID;
                AProcessID = 0;

                if (UserDR.PasswordNeedsChange)
                {
                    // The user needs to change their password before they can use OpenPetra
                    PetraPrincipal.LoginMessage = Catalog.GetString("You need to change your password immediately.");
                }
            }
            finally
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
            }

            return(PetraPrincipal);
        }
コード例 #23
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);
        }
コード例 #24
0
ファイル: UserInfo.cs プロジェクト: weiplanet/openpetra
 /// <summary>set user information in the session</summary>
 public static void SetUserInfo(TPetraPrincipal value)
 {
     TSession.SetVariable("UserInfo", value);
 }
コード例 #25
0
        /// Load Petra Module DLLs into Clients AppDomain, initialise them and remote an Instantiator Object
        public override void LoadAssemblies(string AClientID, IPrincipal AUserInfo, ref Hashtable ARemotingURLs)
        {
            String RemotingURL_MCommon;
            String RemotingURL_MConference;
            String RemotingURL_MSysMan;
            String RemotingURL_MPartner;
            String RemotingURL_MPersonnel;
            String RemotingURL_MFinance;
            String RemotingURL_MReporting;

            TPetraPrincipal UserInfo = (TPetraPrincipal)AUserInfo;

            // Load SYSMAN Module assembly (always loaded)
            LoadPetraModuleAssembly(AClientID, MSYSMAN_DLLNAME, MSYSMAN_CLASSNAME, out RemotingURL_MSysMan);
            ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MSYSMAN, RemotingURL_MSysMan);

            if (TLogging.DL >= 5)
            {
                Console.WriteLine("  TMSysMan instantiated. Remoting URL: " + RemotingURL_MSysMan);
            }

            // Load COMMON Module assembly (always loaded)
            LoadPetraModuleAssembly(AClientID, MCOMMON_DLLNAME, MCOMMON_CLASSNAME, out RemotingURL_MCommon);
            ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MCOMMON, RemotingURL_MCommon);

            if (TLogging.DL >= 5)
            {
                Console.WriteLine("  TMCommon instantiated. Remoting URL: " + RemotingURL_MCommon);
            }

            // Load CONFERENCE Module assembly (always loaded)
            LoadPetraModuleAssembly(AClientID, MCONFERENCE_DLLNAME, MCONFERENCE_CLASSNAME, out RemotingURL_MConference);
            ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MCONFERENCE, RemotingURL_MConference);

            if (TLogging.DL >= 5)
            {
                Console.WriteLine("  TMConference instantiated. Remoting URL: " + RemotingURL_MConference);
            }

            // Load PARTNER Module assembly (always loaded)
            LoadPetraModuleAssembly(AClientID, MPARTNER_DLLNAME, MPARTNER_CLASSNAME, out RemotingURL_MPartner);
            ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MPARTNER, RemotingURL_MPartner);

            if (TLogging.DL >= 5)
            {
                Console.WriteLine("  TMPartner instantiated. Remoting URL: " + RemotingURL_MPartner);
            }

            // Load REPORTING Module assembly (always loaded)
            LoadPetraModuleAssembly(AClientID, MREPORTING_DLLNAME, MREPORTING_CLASSNAME, out RemotingURL_MReporting);
            ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MREPORTING, RemotingURL_MReporting);

            if (TLogging.DL >= 5)
            {
                Console.WriteLine("  TMReporting instantiated. Remoting URL: " + RemotingURL_MReporting);
            }

            // Load PERSONNEL Module assembly (loaded only for users that have personnel privileges)
            if (UserInfo.IsInModule(SharedConstants.PETRAMODULE_PERSONNEL))
            {
                LoadPetraModuleAssembly(AClientID, MPERSONNEL_DLLNAME, MPERSONNEL_CLASSNAME, out RemotingURL_MPersonnel);
                ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MPERSONNEL, RemotingURL_MPersonnel);

                if (TLogging.DL >= 5)
                {
                    Console.WriteLine("  TMPersonnel instantiated. Remoting URL: " + RemotingURL_MPersonnel);
                }
            }

            // Load FINANCE Module assembly (loaded only for users that have finance privileges)
            if ((UserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE1)) || (UserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE2)) ||
                (UserInfo.IsInModule(SharedConstants.PETRAMODULE_FINANCE3)))
            {
                LoadPetraModuleAssembly(AClientID, MFINANCE_DLLNAME, MFINANCE_CLASSNAME, out RemotingURL_MFinance);
                ARemotingURLs.Add(SharedConstants.REMOTINGURL_IDENTIFIER_MFINANCE, RemotingURL_MFinance);

                if (TLogging.DL >= 5)
                {
                    Console.WriteLine("  TMFinance instantiated. Remoting URL: " + RemotingURL_MFinance);
                }
            }
        }