public MainWindow()
        {
            InitializeComponent();

            try
            {
                this.logger = Gnosis.Utilities.Log4NetLogger.GetDefaultLogger(typeof(MainWindow));
            }
            catch (Exception loggerEx)
            {
                throw new ApplicationException("Could not initialize logger", loggerEx);
            }

            try
            {
                logger.Info("Initializing Alexandria");

                mediaFactory = new MediaFactory(logger);
                securityContext = new SecurityContext(mediaFactory);
                tagTypeFactory = new TagTypeFactory();

                mediaRepository = new SQLiteMediaRepository(logger, mediaFactory);
                mediaRepository.Initialize();

                linkRepository = new SQLiteLinkRepository(logger);
                linkRepository.Initialize();

                tagRepository = new SQLiteTagRepository(logger, tagTypeFactory);
                tagRepository.Initialize();

                metadataRepository = new SQLiteMetadataRepository(logger, securityContext, mediaFactory);
                metadataRepository.Initialize();

                marqueeRepository = new SQLiteMarqueeRepository(logger);

                audioStreamFactory = new AudioStreamFactory();

                videoPlayer = new Gnosis.Video.Vlc.VideoPlayerControl();
                videoPlayer.Initialize(logger, () => GetVideoHost());

                catalogController = new CatalogController(logger, securityContext, mediaFactory, mediaRepository, linkRepository, tagRepository, metadataRepository, audioStreamFactory);
                spiderFactory = new SpiderFactory(logger, securityContext, mediaFactory, linkRepository, tagRepository, mediaRepository, metadataRepository, audioStreamFactory);

                metadataController = new MediaItemController(logger, securityContext, mediaFactory, linkRepository, tagRepository, metadataRepository);
                taskController = new TaskController(logger, mediaFactory, videoPlayer, spiderFactory, metadataController, marqueeRepository, metadataRepository);
                tagController = new TagController(logger, tagRepository);
                commandController = new CommandController(logger);

                taskResultView.Initialize(logger, securityContext, mediaFactory, metadataController, taskController, tagController, videoPlayer);
                //taskManagerView.Initialize(logger, taskController, taskResultView);
                searchView.Initialize(logger, taskController, taskResultView);
                commandView.Initialize(logger, commandController, taskController, taskResultView);

                ScreenSaver.Disable();
            }
            catch (Exception ex)
            {
                logger.Error("MainWindow.ctor", ex);
            }
        }
        public void Test(string packageName, SspiContextFlags contextFlags)
        {
            var clientCredential = new SecurityCredential(packageName, SecurityCredentialUse.Outbound);
            clientCredential.Acquire();

            var serverCredential = new SecurityCredential(packageName, SecurityCredentialUse.Inbound);
            serverCredential.Acquire();

            var clientContext = new SecurityContext(clientCredential, contextFlags);
            var serverContext = new SecurityContext(serverCredential, contextFlags);

            byte[] clientToken;
            clientContext.Initialize(serverCredential.PrincipalName, null, out clientToken);

            while (true)
            {
                byte[] serverToken;
                serverContext.AcceptToken(clientToken, out serverToken);
                if (serverContext.IsInitialized && clientContext.IsInitialized)
                    break;

                clientContext.Initialize(serverCredential.PrincipalName, serverToken, out clientToken);
                if (clientContext.IsInitialized && serverContext.IsInitialized)
                    break;
            }

            clientContext.Dispose();
            serverContext.Dispose();

            clientCredential.Dispose();
            serverCredential.Dispose();
        }
        public static SecurityContext Initialize(SecurityCredential credential, string servicePrincipalName, byte[] input, out byte[] output)
        {
            var context = new SecurityContext();
            context._credential = credential;

            context.Initialize(servicePrincipalName, input, out output);
            return context;
        }
        private AuthenticationTokenData AuthenticateMeWithCode(AuthModel auth)
        {
            var tenant = TenantManager.GetCurrentTenant().TenantId;
            var user   = GetUser(auth, out _);

            var sms = false;

            try
            {
                if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
                {
                    sms = true;

                    SmsManager.ValidateSmsCode(user, auth.Code);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load <TfaAppAuthSettings>().EnableSetting)
                {
                    if (TfaManager.ValidateAuthCode(user, auth.Code))
                    {
                        MessageService.Send(MessageAction.UserConnectedTfaApp, MessageTarget.Create(user.ID));
                    }
                }
                else
                {
                    throw new System.Security.SecurityException("Auth code is not available");
                }

                var token = SecurityContext.AuthenticateMe(user.ID);

                MessageService.Send(sms ? MessageAction.LoginSuccessViaApiSms : MessageAction.LoginSuccessViaApiTfa);
                ;
                var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant);

                var result = new AuthenticationTokenData
                {
                    Token   = token,
                    Expires = new ApiDateTime(TenantManager, TimeZoneConverter, expires)
                };

                if (sms)
                {
                    result.Sms        = true;
                    result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
                }
                else
                {
                    result.Tfa = true;
                }

                return(result);
            }
            catch
            {
                MessageService.Send(user.DisplayUserName(false, DisplayUserSettingsHelper), sms
                                                                              ? MessageAction.LoginFailViaApiSms
                                                                              : MessageAction.LoginFailViaApiTfa,
                                    MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }
        /// <summary>
        /// Initializes the <see cref="SecurityHelper"/> class.
        /// </summary>
        internal SecurityHelper(string connectionString)
        {
#pragma warning disable 612,618
            _securityContext = new SecurityContext(connectionString);
#pragma warning restore 612,618
        }
Exemple #6
0
 protected void ChangeProjectPrivate(bool @private)
 {
     SecurityContext.AuthenticateMe(Owner);
     Project.Private = @private;
     SaveOrUpdate(Project);
 }
 public AuthenticationController(
     UserManager userManager,
     TenantManager tenantManager,
     SecurityContext securityContext,
     TenantCookieSettingsHelper tenantCookieSettingsHelper,
     CookiesManager cookiesManager,
     PasswordHasher passwordHasher,
     EmailValidationKeyModelHelper emailValidationKeyModelHelper,
     ICache cache,
     SetupInfo setupInfo,
     MessageService messageService,
     ProviderManager providerManager,
     IOptionsSnapshot <AccountLinker> accountLinker,
     CoreBaseSettings coreBaseSettings,
     PersonalSettingsHelper personalSettingsHelper,
     StudioNotifyService studioNotifyService,
     UserManagerWrapper userManagerWrapper,
     UserHelpTourHelper userHelpTourHelper,
     Signature signature,
     InstanceCrypto instanceCrypto,
     DisplayUserSettingsHelper displayUserSettingsHelper,
     MessageTarget messageTarget,
     StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
     SettingsManager settingsManager,
     SmsManager smsManager,
     TfaManager tfaManager,
     TimeZoneConverter timeZoneConverter,
     SmsKeyStorage smsKeyStorage,
     CommonLinkUtility commonLinkUtility,
     ApiContext apiContext,
     AuthContext authContext)
 {
     UserManager                   = userManager;
     TenantManager                 = tenantManager;
     SecurityContext               = securityContext;
     TenantCookieSettingsHelper    = tenantCookieSettingsHelper;
     CookiesManager                = cookiesManager;
     PasswordHasher                = passwordHasher;
     EmailValidationKeyModelHelper = emailValidationKeyModelHelper;
     Cache                               = cache;
     SetupInfo                           = setupInfo;
     MessageService                      = messageService;
     ProviderManager                     = providerManager;
     AccountLinker                       = accountLinker;
     CoreBaseSettings                    = coreBaseSettings;
     PersonalSettingsHelper              = personalSettingsHelper;
     StudioNotifyService                 = studioNotifyService;
     UserHelpTourHelper                  = userHelpTourHelper;
     Signature                           = signature;
     InstanceCrypto                      = instanceCrypto;
     DisplayUserSettingsHelper           = displayUserSettingsHelper;
     MessageTarget                       = messageTarget;
     StudioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
     SettingsManager                     = settingsManager;
     SmsManager                          = smsManager;
     TfaManager                          = tfaManager;
     TimeZoneConverter                   = timeZoneConverter;
     SmsKeyStorage                       = smsKeyStorage;
     CommonLinkUtility                   = commonLinkUtility;
     ApiContext                          = apiContext;
     AuthContext                         = authContext;
     UserManagerWrapper                  = userManagerWrapper;
 }
            SecurityContextInstance_WithProvidedConstructorWithNetworkCredentialsAndOverwittenHomeRealm_ReturnsTokenForThoseCredentials
            ()
        {
            var securityContext = new SecurityContext(new NetworkCredential("boyerc", "****"), "MyApplicationName",
                "MyPartnerName");
            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT +
                                                     "?homeRealm=dmzfs.fcsamerica.com&realm=devinternal.fcsamerica.net:AGRIPOINT";

            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));
        }
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            var            file_name  = string.Empty;
            MailAttachment attachment = null;

            try
            {
                if (!SecurityContext.AuthenticateMe(CookiesManager.GetCookies(CookiesType.AuthKey)))
                {
                    throw new UnauthorizedAccessException(MailResource.AttachemntsUnauthorizedError);
                }

                if (ProgressFileUploader.HasFilesToUpload(context))
                {
                    try
                    {
                        var stream_id = context.Request["stream"];
                        var mail_id   = Convert.ToInt32(context.Request["messageId"]);

                        if (mail_id < 1)
                        {
                            throw new AttachmentsException(AttachmentsException.Types.MESSAGE_NOT_FOUND,
                                                           "Message not yet saved!");
                        }

                        if (String.IsNullOrEmpty(stream_id))
                        {
                            throw new AttachmentsException(AttachmentsException.Types.BAD_PARAMS, "Have no stream");
                        }

                        var posted_file = new ProgressFileUploader.FileToUpload(context);

                        file_name = context.Request["name"];

                        attachment = new MailAttachment
                        {
                            fileId   = -1,
                            size     = posted_file.ContentLength,
                            fileName = file_name,
                            streamId = stream_id,
                            tenant   = TenantId,
                            user     = Username
                        };

                        attachment = _mailBoxManager.AttachFile(TenantId, Username, mail_id,
                                                                file_name, posted_file.InputStream, stream_id);

                        return(new FileUploadResult
                        {
                            Success = true,
                            FileName = attachment.fileName,
                            FileURL = attachment.storedFileUrl,
                            Data = attachment
                        });
                    }
                    catch (AttachmentsException e)
                    {
                        string error_message;

                        switch (e.ErrorType)
                        {
                        case AttachmentsException.Types.BAD_PARAMS:
                            error_message = MailScriptResource.AttachmentsBadInputParamsError;
                            break;

                        case AttachmentsException.Types.EMPTY_FILE:
                            error_message = MailScriptResource.AttachmentsEmptyFileNotSupportedError;
                            break;

                        case AttachmentsException.Types.MESSAGE_NOT_FOUND:
                            error_message = MailScriptResource.AttachmentsMessageNotFoundError;
                            break;

                        case AttachmentsException.Types.TOTAL_SIZE_EXCEEDED:
                            error_message = MailScriptResource.AttachmentsTotalLimitError;
                            break;

                        case AttachmentsException.Types.DOCUMENT_NOT_FOUND:
                            error_message = MailScriptResource.AttachmentsDocumentNotFoundError;
                            break;

                        case AttachmentsException.Types.DOCUMENT_ACCESS_DENIED:
                            error_message = MailScriptResource.AttachmentsDocumentAccessDeniedError;
                            break;

                        default:
                            error_message = MailScriptResource.AttachmentsUnknownError;
                            break;
                        }
                        throw new Exception(error_message);
                    }
                    catch (ASC.Core.Tenants.TenantQuotaException)
                    {
                        throw;
                    }
                    catch (Exception)
                    {
                        throw new Exception(MailScriptResource.AttachmentsUnknownError);
                    }
                }
                throw new Exception(MailScriptResource.AttachmentsBadInputParamsError);
            }
            catch (Exception ex)
            {
                return(new FileUploadResult
                {
                    Success = false,
                    FileName = file_name,
                    Data = attachment,
                    Message = ex.Message,
                });
            }
        }
        /// <summary>
        /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/>
        /// method.
        /// </summary>
        /// <param name="loggingEvent">the event to log</param>
        /// <remarks>
        /// <para>Writes the event to the system event log using the
        /// <see cref="ApplicationName"/>.</para>
        ///
        /// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>)
        /// set then this integer will be used as the event log event id.</para>
        ///
        /// <para>
        /// There is a limit of 32K characters for an event log message
        /// </para>
        /// </remarks>
        override protected void Append(LoggingEvent loggingEvent)
        {
            //
            // Write the resulting string to the event log system
            //
            int eventID = m_eventId;

            // Look for the EventID property
            object eventIDPropertyObj = loggingEvent.LookupProperty("EventID");

            if (eventIDPropertyObj != null)
            {
                if (eventIDPropertyObj is int)
                {
                    eventID = (int)eventIDPropertyObj;
                }
                else
                {
                    string eventIDPropertyString = eventIDPropertyObj as string;
                    if (eventIDPropertyString == null)
                    {
                        eventIDPropertyString = eventIDPropertyObj.ToString();
                    }
                    if (eventIDPropertyString != null && eventIDPropertyString.Length > 0)
                    {
                        // Read the string property into a number
                        int intVal;
                        if (SystemInfo.TryParse(eventIDPropertyString, out intVal))
                        {
                            eventID = intVal;
                        }
                        else
                        {
                            ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "].");
                        }
                    }
                }
            }

            short category = m_category;
            // Look for the Category property
            object categoryPropertyObj = loggingEvent.LookupProperty("Category");

            if (categoryPropertyObj != null)
            {
                if (categoryPropertyObj is short)
                {
                    category = (short)categoryPropertyObj;
                }
                else
                {
                    string categoryPropertyString = categoryPropertyObj as string;
                    if (categoryPropertyString == null)
                    {
                        categoryPropertyString = categoryPropertyObj.ToString();
                    }
                    if (categoryPropertyString != null && categoryPropertyString.Length > 0)
                    {
                        // Read the string property into a number
                        short shortVal;
                        if (SystemInfo.TryParse(categoryPropertyString, out shortVal))
                        {
                            category = shortVal;
                        }
                        else
                        {
                            ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "].");
                        }
                    }
                }
            }

            // Write to the event log
            try
            {
                string eventTxt = RenderLoggingEvent(loggingEvent);

                // There is a limit of about 32K characters for an event log message
                if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE)
                {
                    eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE);
                }

                EventLogEntryType entryType = GetEntryType(loggingEvent.Level);

                using (SecurityContext.Impersonate(this))
                {
                    EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category);
                }
            }
            catch (Exception ex)
            {
                ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex);
            }
        }
        public void SecurityContextWithCredendialsSupplied_ReturnsValidServiceTokenAndAuditInfo()
        {
            var securityContext =
                new SecurityContext(new NetworkCredential("agrilytic_o", Passwords["agrilytic_o"], "fcsamerica"), "MyAppName",
                    "MyPartnerName");
            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT;

            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));
        }
Exemple #12
0
        public static UserInfo AddUser(UserInfo userInfo, string passwordHash, bool afterInvite = false, bool notify = true, bool isVisitor = false, bool fromInviteLink = false, bool makeUniqueName = true, bool isCardDav = false)
        {
            if (userInfo == null)
            {
                throw new ArgumentNullException("userInfo");
            }

            if (!UserFormatter.IsValidUserName(userInfo.FirstName, userInfo.LastName))
            {
                throw new Exception(Resource.ErrorIncorrectUserName);
            }

            if (!CheckUniqueEmail(userInfo.ID, userInfo.Email))
            {
                throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
            }
            if (makeUniqueName)
            {
                userInfo.UserName = MakeUniqueName(userInfo);
            }
            if (!userInfo.WorkFromDate.HasValue)
            {
                userInfo.WorkFromDate = TenantUtil.DateTimeNow();
            }

            if (!CoreContext.Configuration.Personal && !fromInviteLink)
            {
                userInfo.ActivationStatus = !afterInvite ? EmployeeActivationStatus.Pending : EmployeeActivationStatus.Activated;
            }


            var newUserInfo = CoreContext.UserManager.SaveUserInfo(userInfo, isVisitor, isCardDav);

            SecurityContext.SetUserPasswordHash(newUserInfo.ID, passwordHash);



            if (CoreContext.Configuration.Personal)
            {
                StudioNotifyService.Instance.SendUserWelcomePersonal(newUserInfo);
                return(newUserInfo);
            }

            if ((newUserInfo.Status & EmployeeStatus.Active) == EmployeeStatus.Active && notify)
            {
                //NOTE: Notify user only if it's active
                if (afterInvite)
                {
                    if (isVisitor)
                    {
                        StudioNotifyService.Instance.GuestInfoAddedAfterInvite(newUserInfo);
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoAddedAfterInvite(newUserInfo);
                    }

                    if (fromInviteLink)
                    {
                        StudioNotifyService.Instance.SendEmailActivationInstructions(newUserInfo, newUserInfo.Email);
                    }
                }
                else
                {
                    //Send user invite
                    if (isVisitor)
                    {
                        StudioNotifyService.Instance.GuestInfoActivation(newUserInfo);
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoActivation(newUserInfo);
                    }
                }
            }

            if (isVisitor)
            {
                CoreContext.UserManager.AddUserIntoGroup(newUserInfo.ID, Constants.GroupVisitor.ID);
            }


            return(newUserInfo);
        }
        /// <summary>
        /// Initialize the appender based on the options set
        /// </summary>
        /// <remarks>
        /// <para>
        /// This is part of the <see cref="IOptionHandler"/> delayed object
        /// activation scheme. The <see cref="ActivateOptions"/> method must
        /// be called on this object after the configuration properties have
        /// been set. Until <see cref="ActivateOptions"/> is called this
        /// object is in an undefined state and must not be used.
        /// </para>
        /// <para>
        /// If any of the configuration properties are modified then
        /// <see cref="ActivateOptions"/> must be called again.
        /// </para>
        /// </remarks>
        override public void ActivateOptions()
        {
            try
            {
                base.ActivateOptions();

                if (m_securityContext == null)
                {
                    m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
                }

                bool   sourceAlreadyExists = false;
                string currentLogName      = null;

                using (SecurityContext.Impersonate(this))
                {
                    sourceAlreadyExists = EventLog.SourceExists(m_applicationName);
                    if (sourceAlreadyExists)
                    {
                        currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
                    }
                }

                if (sourceAlreadyExists && currentLogName != m_logName)
                {
                    LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]");
                }
                else if (!sourceAlreadyExists)
                {
                    LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]");
                }

                string registeredLogName = null;

                using (SecurityContext.Impersonate(this))
                {
                    if (sourceAlreadyExists && currentLogName != m_logName)
                    {
                        //
                        // Re-register this to the current application if the user has changed
                        // the application / logfile association
                        //
                        EventLog.DeleteEventSource(m_applicationName, m_machineName);
                        CreateEventSource(m_applicationName, m_logName, m_machineName);

                        registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
                    }
                    else if (!sourceAlreadyExists)
                    {
                        CreateEventSource(m_applicationName, m_logName, m_machineName);

                        registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName);
                    }
                }

                m_levelMapping.ActivateOptions();

                LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]");
            }
            catch (System.Security.SecurityException ex)
            {
                ErrorHandler.Error("Caught a SecurityException trying to access the EventLog.  Most likely the event source "
                                   + m_applicationName
                                   + " doesn't exist and must be created by a local administrator.  Will disable EventLogAppender."
                                   + "  See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog",
                                   ex);
                Threshold = Level.Off;
            }
        }
Exemple #14
0
        public void ProcessPatches()
        {
            using (SecurityContext.OpenSystemScope())
            {
                var entMan = new EntityManager();
                var relMan = new EntityRelationManager();
                var recMan = new RecordManager();
                var storeSystemSettings = DbContext.Current.SettingsRepository.Read();
                var systemSettings      = new SystemSettings(storeSystemSettings);

                //Create transaction
                using (var connection = DbContext.Current.CreateConnection())
                {
                    try
                    {
                        connection.BeginTransaction();

                        //Here we need to initialize or update the environment based on the plugin requirements.
                        //The default place for the plugin data is the "plugin_data" entity -> the "data" text field, which is used to store stringified JSON
                        //containing the plugin settings or version

                        //TODO: Develop a way to check for installed plugins
                        #region << 1.Get the current ERP database version and checks for other plugin dependencies >>

                        if (systemSettings.Version > 0)
                        {
                            //Do something if database version is not what you expect
                        }

                        //This plugin needs the webvella-sdk plugin to be installed, so we will check this here
                        //var installedPlugins = new PluginService().Plugins;
                        //var corePluginFound = false;
                        //foreach (var plugin in installedPlugins)
                        //{
                        //	if (plugin.Name == "webvella-core")
                        //	{
                        //		corePluginFound = true;
                        //		break;
                        //	}
                        //}

                        //if (!corePluginFound)
                        //	throw new Exception("'webvella-sdk' plugin is required for the 'webvella-sdk' to operate");

                        #endregion

                        #region << 2.Get the current plugin settings from the database >>

                        var currentPluginSettings = new PluginSettings()
                        {
                            Version = WEBVELLA_NEXT_INIT_VERSION
                        };
                        string jsonData = GetPluginData();
                        if (!string.IsNullOrWhiteSpace(jsonData))
                        {
                            currentPluginSettings = JsonConvert.DeserializeObject <PluginSettings>(jsonData);
                        }

                        #endregion

                        #region << 3. Run methods based on the current installed version of the plugin >>


                        //PATCH 20190203
                        {
                            var patchVersion = 20190203;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190203(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //PATCH 20190204
                        {
                            var patchVersion = 20190204;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190204(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //PATCH 20190205
                        {
                            var patchVersion = 20190205;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190205(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //PATCH 20190206
                        {
                            var patchVersion = 20190206;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190206(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //PATCH 20190222
                        {
                            var patchVersion = 20190222;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190222(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        #endregion


                        SavePluginData(JsonConvert.SerializeObject(currentPluginSettings));

                        connection.CommitTransaction();
                        //connection.RollbackTransaction();
                    }
                    catch (ValidationException ex)
                    {
                        connection.RollbackTransaction();
                        throw ex;
                    }
                    catch (Exception ex)
                    {
                        connection.RollbackTransaction();
                        throw ex;
                    }
                }
            }
        }
Exemple #15
0
 public NhanVienNhaThuocRespository(SecurityContext contenxt)
     : base(contenxt)
 {
 }
Exemple #16
0
 protected override void LoadNewItem()
 {
     linkAddEduProgramProfile.Visible = false;
     panelAddDefaultProfile.Visible   = SecurityContext.CanAdd(typeof(EduProgramProfileInfo));
 }
Exemple #17
0
		/// <summary>
		/// 将当前用户对象绑定到当前安全上下文中,之后,便可通过 SecurityContext.Current.User 访问该用户对象。
		/// </summary>
		/// <param name="securityContext"></param>
		public void Bind(SecurityContext securityContext)
		{
			if (securityContext == null)
			{
				throw new ArgumentNullException();
			}

			securityContext.BindUser(this);
		}
        private void ClientOnGetMessage(object sender, MailClientMessageEventArgs mailClientMessageEventArgs)
        {
            var log = _log;

            Stopwatch watch = null;

            if (_tasksConfig.CollectStatistics)
            {
                watch = new Stopwatch();
                watch.Start();
            }

            var failed = false;

            var mailbox = mailClientMessageEventArgs.Mailbox;

            try
            {
                var mimeMessage = mailClientMessageEventArgs.Message;
                var uid         = mailClientMessageEventArgs.MessageUid;
                var folder      = mailClientMessageEventArgs.Folder;
                var unread      = mailClientMessageEventArgs.Unread;
                var fromEmail   = mimeMessage.From.Mailboxes.FirstOrDefault();
                log = mailClientMessageEventArgs.Logger;

                log.Debug("ClientOnGetMessage MailboxId = {0}, Address = '{1}'",
                          mailbox.MailBoxId, mailbox.EMail);

                CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId);
                SecurityContext.AuthenticateMe(new Guid(mailbox.UserId));

                var manager = new MailBoxManager(log);

                var md5 =
                    string.Format("{0}|{1}|{2}|{3}",
                                  mimeMessage.From.Mailboxes.Any() ? mimeMessage.From.Mailboxes.First().Address : "",
                                  mimeMessage.Subject, mimeMessage.Date.UtcDateTime, mimeMessage.MessageId).GetMd5();

                var uidl = mailbox.Imap ? string.Format("{0}-{1}", uid, folder.FolderId) : uid;

                var fromThisMailBox = fromEmail != null &&
                                      fromEmail.Address.ToLowerInvariant()
                                      .Equals(mailbox.EMail.Address.ToLowerInvariant());

                var toThisMailBox =
                    mimeMessage.To.Mailboxes.Select(addr => addr.Address.ToLowerInvariant())
                    .Contains(mailbox.EMail.Address.ToLowerInvariant());

                log.Info(
                    @"Message: Subject: '{1}' Date: {2} Unread: {5} FolderId: {3} ('{4}') MimeId: '{0}' Uidl: '{6}' Md5: '{7}' To->From: {8} From->To: {9}",
                    mimeMessage.MessageId, mimeMessage.Subject, mimeMessage.Date, folder.FolderId, folder.Name, unread,
                    uidl, md5, fromThisMailBox, toThisMailBox);

                List <int> tagsIds = null;

                if (folder.Tags.Any())
                {
                    log.Debug("GetOrCreateTags()");

                    tagsIds = manager.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags);
                }

                log.Debug("SearchExistingMessagesAndUpdateIfNeeded()");

                var found = manager.SearchExistingMessagesAndUpdateIfNeeded(mailbox, folder.FolderId, uidl, md5,
                                                                            mimeMessage.MessageId, fromThisMailBox, toThisMailBox, tagsIds);

                var needSave = !found;
                if (!needSave)
                {
                    return;
                }

                log.Debug("DetectChainId()");

                var chainId = manager.DetectChainId(mailbox, mimeMessage.MessageId, mimeMessage.InReplyTo,
                                                    mimeMessage.Subject);

                var streamId = MailUtil.CreateStreamId();

                log.Debug("Convert MimeMessage->MailMessage");

                var message = ConvertToMailMessage(mimeMessage, folder, unread, chainId, streamId, log);

                log.Debug("TryStoreMailData()");

                if (!TryStoreMailData(message, mailbox, log))
                {
                    failed = true;
                    return;
                }

                log.Debug("MailSave()");

                if (TrySaveMail(manager, mailbox, message, folder, uidl, md5, log))
                {
                    log.Debug("DoOptionalOperations->START");

                    DoOptionalOperations(message, mimeMessage, mailbox, tagsIds, log);
                }
                else
                {
                    failed = true;

                    if (manager.TryRemoveMailDirectory(mailbox, message.StreamId))
                    {
                        log.Info("Problem with mail proccessing(Account:{0}). Body and attachment have been deleted", mailbox.EMail);
                    }
                    else
                    {
                        throw new Exception("Can't delete mail folder with data");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("[ClientOnGetMessage] Exception:\r\n{0}\r\n", ex.ToString());

                failed = true;
            }
            finally
            {
                if (_tasksConfig.CollectStatistics && watch != null)
                {
                    watch.Stop();

                    LogStat(PROCESS_MESSAGE, mailbox, watch.Elapsed, failed);
                }
            }
        }
Exemple #19
0
		/// <summary>
		/// 将 RunContext 的当前实例重设为 null,该方法一般与 InitCurrent 成对使用。
		/// </summary>
		public static void ResetCurrent()
		{
			current = null;
		}
Exemple #20
0
        public void ProcessPatches()
        {
            using (SecurityContext.OpenSystemScope())
            {
                var entMan = new EntityManager();
                var relMan = new EntityRelationManager();
                var recMan = new RecordManager();
                var storeSystemSettings = DbContext.Current.SettingsRepository.Read();
                var systemSettings      = new SystemSettings(storeSystemSettings);

                //Create transaction
                using (var connection = DbContext.Current.CreateConnection())
                {
                    try
                    {
                        connection.BeginTransaction();

                        //Here we need to initialize or update the environment based on the plugin requirements.
                        //The default place for the plugin data is the "plugin_data" entity -> the "data" text field, which is used to store stringified JSON
                        //containing the plugin settings or version

                        //TODO: Develop a way to check for installed plugins
                        #region << 1.Get the current ERP database version and checks for other plugin dependencies >>

                        if (systemSettings.Version > 0)
                        {
                            //Do something if database version is not what you expect
                        }

                        #endregion

                        #region << 2.Get the current plugin settings from the database >>

                        var currentPluginSettings = new PluginSettings()
                        {
                            Version = WEBVELLA_PROJECT_INIT_VERSION
                        };
                        string jsonData = GetPluginData();
                        if (!string.IsNullOrWhiteSpace(jsonData))
                        {
                            currentPluginSettings = JsonConvert.DeserializeObject <PluginSettings>(jsonData);
                        }

                        #endregion

                        #region << 3. Run methods based on the current installed version of the plugin >>

                        //Patch 20190203
                        {
                            var patchVersion = 20190203;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190203(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //Patch 20190205
                        {
                            var patchVersion = 20190205;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190205(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //Patch 20190206
                        {
                            var patchVersion = 20190206;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190206(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //Patch 20190207
                        {
                            var patchVersion = 20190207;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190207(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //Patch 20190208
                        {
                            var patchVersion = 20190208;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190208(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }

                        //Patch 20190222
                        {
                            var patchVersion = 20190222;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20190222(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }
                        //Patch 20211012
                        {
                            var patchVersion = 20211012;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20211012(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }
                        //Patch 20211013
                        {
                            var patchVersion = 20211013;
                            if (currentPluginSettings.Version < patchVersion)
                            {
                                try
                                {
                                    currentPluginSettings.Version = patchVersion;
                                    Patch20211013(entMan, relMan, recMan);
                                }
                                catch (ValidationException ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                                catch (Exception ex)
                                {
                                    var exception = ex;
                                    throw ex;
                                }
                            }
                        }
                        #endregion


                        SavePluginData(JsonConvert.SerializeObject(currentPluginSettings));

                        connection.CommitTransaction();
                        //connection.RollbackTransaction();
                    }
                    catch (ValidationException ex)
                    {
                        connection.RollbackTransaction();
                        throw ex;
                    }
                    catch (Exception ex)
                    {
                        connection.RollbackTransaction();
                        throw ex;
                    }
                }
            }
        }
        public void RequestingAToken_ForFCMATester_ReturnsValidTokenWithTheCorrectPartnerName()
        {
            var securityContext = new SecurityContext(new NetworkCredential("*****@*****.**", Passwords["*****@*****.**"]),
                "MyAppName", null);
            securityContext.AuditInfoServiceEndpoint = "https://internal.fcsamerica.net/mcgruff/v2/rest/api/auditInfo";
            ;
            securityContext.AuthenticationEndpoint = "https://fcma.fcsamerica.net/mcgruff/web/";

            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo)); // validate partner name is correct.
        }
 public PermissionAttribute(SecurityContext security, IUserService userService, IFeatureService featureService)
 {
     Security       = security;
     UserService    = userService;
     FeatureService = featureService;
 }
        public void SecurityContextWithDefaultCredendialsAndNoECS_CreatedTwice_ReturnsValidServiceTokenAndAuditInfo()
        {
            var securityContext = SecurityContext.GetInstance("MyApplicationName", "MyPartnerName", true);
            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT;

            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));

            securityContext = new SecurityContext(new NetworkCredential("testerl", Passwords["testerl"],"fcsameria.com"), "MyApplicationName", "MyPartnerName");


            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT;

            serviceToken = securityContext.ServiceToken;
            auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));
        }
Exemple #24
0
 //
 public CookieAuthHandler(IOptionsMonitor <AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, SecurityContext securityContext)
     : this(options, logger, encoder, clock)
 {
     SecurityContext = securityContext;
 }
 public CustomRequestProcessorProxy(SecurityContext securityContext)
     : base(EndpointConfigurationName, securityContext.ServiceUrl)
 {
 }
 public ListViewEstabelecimento(ApplicationContext _db, SecurityContext _seguranca_db)
 {
     this.Create(_db, _seguranca_db);
 }
Exemple #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterStyleControl(VirtualPathUtility.ToAbsolute("~/usercontrols/common/authorize/css/authorize.less"));
            Page.RegisterBodyScripts(ResolveUrl("~/usercontrols/common/authorize/js/authorize.js"));

            Login    = "";
            Password = "";
            HashId   = "";

            //Account link control
            AccountLinkControl accountLink = null;

            if (SetupInfo.ThirdPartyAuthEnabled && AccountLinkControl.IsNotEmpty)
            {
                accountLink                = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                accountLink.Visible        = true;
                accountLink.ClientCallback = "authCallback";
                accountLink.SettingsView   = false;
                signInPlaceholder.Controls.Add(accountLink);
            }

            //top panel
            var master = Page.Master as BaseTemplate;

            if (master != null)
            {
                master.TopStudioPanel.DisableProductNavigation = true;
                master.TopStudioPanel.DisableSearch            = true;
            }

            Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization);

            pwdReminderHolder.Controls.Add(LoadControl(PwdTool.Location));

            var msg      = Request["m"];
            var urlError = Request.QueryString["error"];

            if (!string.IsNullOrEmpty(msg))
            {
                ErrorMessage = msg;
            }
            else if (urlError == "ipsecurity")
            {
                ErrorMessage = Resource.LoginFailIPSecurityMsg;
            }

            var thirdPartyProfile = Request.Url.GetProfile();

            if ((IsPostBack || thirdPartyProfile != null) && !SecurityContext.IsAuthenticated)
            {
                var tryByHash   = false;
                var smsLoginUrl = string.Empty;
                try
                {
                    if (thirdPartyProfile != null)
                    {
                        if (string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                        {
                            HashId = thirdPartyProfile.HashId;
                        }
                        else
                        {
                            // ignore cancellation
                            if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                            {
                                ErrorMessage = thirdPartyProfile.AuthorizationError;
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && accountLink != null)
                        {
                            HashId = ASC.Common.Utils.Signature.Read <string>(Request["__EVENTARGUMENT"]);
                        }
                    }

                    if (!string.IsNullOrEmpty(Request["login"]))
                    {
                        Login = Request["login"].Trim();
                    }
                    else if (string.IsNullOrEmpty(HashId))
                    {
                        throw new InvalidCredentialException("login");
                    }

                    if (!string.IsNullOrEmpty(Request["pwd"]))
                    {
                        Password = Request["pwd"];
                    }
                    else if (string.IsNullOrEmpty(HashId))
                    {
                        throw new InvalidCredentialException("password");
                    }

                    if (string.IsNullOrEmpty(HashId))
                    {
                        // защита от перебора: на 5-ый неправильный ввод делать Sleep
                        var counter = (int)(cache.Get("loginsec/" + Login) ?? 0);
                        if (++counter % 5 == 0)
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(10));
                        }
                        cache.Insert("loginsec/" + Login, counter, DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                    }

                    if (!ActiveDirectoryUserImporter.TryLdapAuth(Login, Password))
                    {
                        smsLoginUrl = SmsLoginUrl();
                        if (string.IsNullOrEmpty(smsLoginUrl))
                        {
                            var session = string.IsNullOrEmpty(Request["remember"]);

                            if (string.IsNullOrEmpty(HashId))
                            {
                                var cookiesKey = SecurityContext.AuthenticateMe(Login, Password);
                                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccess);
                            }
                            else
                            {
                                Guid userId;
                                tryByHash = LoginWithThirdParty.TryGetUserByHash(HashId, out userId);
                                var cookiesKey = SecurityContext.AuthenticateMe(userId);
                                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                                MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialAccount);
                            }
                        }
                    }
                }
                catch (InvalidCredentialException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = tryByHash ? Resource.LoginWithAccountNotFound : Resource.InvalidUsernameOrPassword;

                    var loginName = tryByHash && !string.IsNullOrWhiteSpace(HashId)
                                        ? HashId
                                        : string.IsNullOrWhiteSpace(Login) ? AuditResource.EmailNotSpecified : Login;
                    var messageAction = tryByHash ? MessageAction.LoginFailSocialAccountNotFound : MessageAction.LoginFailInvalidCombination;

                    MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                    return;
                }
                catch (System.Security.SecurityException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = Resource.ErrorDisabledProfile;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                    return;
                }
                catch (IPSecurityException)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = Resource.ErrorIpSecurity;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                    return;
                }
                catch (Exception ex)
                {
                    Auth.ProcessLogout();
                    ErrorMessage = ex.Message;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                    return;
                }

                if (!string.IsNullOrEmpty(smsLoginUrl))
                {
                    Response.Redirect(smsLoginUrl);
                }

                var refererURL = (string)Session["refererURL"];
                if (string.IsNullOrEmpty(refererURL))
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                }
                else
                {
                    Session["refererURL"] = null;
                    Response.Redirect(refererURL);
                }
            }
            ProcessConfirmedEmailCondition();
        }
 public EstabelecimentoModel(ApplicationContext _db, SecurityContext _seguranca_db)
 {
     this.Create(_db, _seguranca_db);
 }
        private AuthenticationTokenData AuthenticateMe(AuthModel auth)
        {
            bool viaEmail;
            var  user = GetUser(auth, out viaEmail);

            if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
            {
                if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
                {
                    return new AuthenticationTokenData
                           {
                               Sms        = true,
                               ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneActivation)
                           }
                }
                ;

                SmsManager.PutAuthCode(user, false);

                return(new AuthenticationTokenData
                {
                    Sms = true,
                    PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
                    Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval)),
                    ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneAuth)
                });
            }

            if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load <TfaAppAuthSettings>().EnableSetting)
            {
                if (!TfaAppUserSettings.EnableForUser(SettingsManager, user.ID))
                {
                    return new AuthenticationTokenData
                           {
                               Tfa        = true,
                               TfaKey     = TfaManager.GenerateSetupCode(user).ManualEntryKey,
                               ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation)
                           }
                }
                ;

                return(new AuthenticationTokenData
                {
                    Tfa = true,
                    ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaAuth)
                });
            }

            try
            {
                var token = SecurityContext.AuthenticateMe(user.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, token, auth.Session);

                MessageService.Send(viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount);

                var tenant  = TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(TenantManager, TimeZoneConverter, expires)
                });
            }
            catch
            {
                MessageService.Send(user.DisplayUserName(false, DisplayUserSettingsHelper), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }
Exemple #30
0
        public void SendMsgWhatsNew(DateTime scheduleDate, INotifyClient client)
        {
            var log = LogManager.GetLogger("ASC.Notify.WhatsNew");

            if (WebItemManager.Instance.GetItemsAll <IProduct>().Count == 0)
            {
                log.Info("No products. Return from function");
                return;
            }

            log.Info("Start send whats new.");

            var products = WebItemManager.Instance.GetItemsAll().ToDictionary(p => p.GetSysName());

            foreach (var tenantid in GetChangedTenants(scheduleDate))
            {
                try
                {
                    var tenant = CoreContext.TenantManager.GetTenant(tenantid);
                    if (tenant == null ||
                        tenant.Status != TenantStatus.Active ||
                        !TimeToSendWhatsNew(TenantUtil.DateTimeFromUtc(tenant.TimeZone, scheduleDate)) ||
                        TariffState.NotPaid <= CoreContext.PaymentManager.GetTariff(tenantid).State)
                    {
                        continue;
                    }

                    CoreContext.TenantManager.SetCurrentTenant(tenant);

                    log.InfoFormat("Start send whats new in {0} ({1}).", tenant.TenantDomain, tenantid);
                    foreach (var user in CoreContext.UserManager.GetUsers())
                    {
                        if (!IsSubscribeToWhatsNew(user))
                        {
                            continue;
                        }

                        SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(user.ID));

                        var culture = string.IsNullOrEmpty(user.CultureName) ? tenant.GetCulture() : user.GetCulture();

                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
                        {
                            From = scheduleDate.Date.AddDays(-1),
                            To   = scheduleDate.Date.AddSeconds(-1),
                            Max  = 100,
                        });

                        var feedMinWrappers = feeds.ConvertAll(f => f.ToFeedMin());

                        var feedMinGroupedWrappers = feedMinWrappers
                                                     .Where(f =>
                                                            (f.CreatedDate == DateTime.MaxValue || f.CreatedDate >= scheduleDate.Date.AddDays(-1)) && //'cause here may be old posts with new comments
                                                            products.ContainsKey(f.Product) &&
                                                            !f.Id.StartsWith("participant")
                                                            )
                                                     .GroupBy(f => products[f.Product]);

                        var ProjectsProductName = products["projects"].Name; //from ASC.Feed.Aggregator.Modules.ModulesHelper.ProjectsProductName

                        var activities = feedMinGroupedWrappers
                                         .Where(f => f.Key.Name != ProjectsProductName) //not for project product
                                         .ToDictionary(
                            g => g.Key.Name,
                            g => g.Select(f => new WhatsNewUserActivity
                        {
                            Date            = f.CreatedDate,
                            UserName        = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName() : string.Empty,
                            UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                            Title           = HtmlUtil.GetText(f.Title, 512),
                            URL             = CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl),
                            BreadCrumbs     = new string[0],
                            Action          = getWhatsNewActionText(f)
                        }).ToList());


                        var projectActivities = feedMinGroupedWrappers
                                                .Where(f => f.Key.Name == ProjectsProductName) // for project product
                                                .SelectMany(f => f);

                        var projectActivitiesWithoutBreadCrumbs = projectActivities.Where(p => String.IsNullOrEmpty(p.ExtraLocation));

                        var whatsNewUserActivityGroupByPrjs = new List <WhatsNewUserActivity>();

                        foreach (var prawbc in projectActivitiesWithoutBreadCrumbs)
                        {
                            whatsNewUserActivityGroupByPrjs.Add(
                                new WhatsNewUserActivity
                            {
                                Date            = prawbc.CreatedDate,
                                UserName        = prawbc.Author != null && prawbc.Author.UserInfo != null ? prawbc.Author.UserInfo.DisplayUserName() : string.Empty,
                                UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                                Title           = HtmlUtil.GetText(prawbc.Title, 512),
                                URL             = CommonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl),
                                BreadCrumbs     = new string[0],
                                Action          = getWhatsNewActionText(prawbc)
                            });
                        }

                        var groupByPrjs = projectActivities.Where(p => !String.IsNullOrEmpty(p.ExtraLocation)).GroupBy(f => f.ExtraLocation);
                        foreach (var gr in groupByPrjs)
                        {
                            var grlist = gr.ToList();
                            for (var i = 0; i < grlist.Count(); i++)
                            {
                                var ls = grlist[i];
                                whatsNewUserActivityGroupByPrjs.Add(
                                    new WhatsNewUserActivity
                                {
                                    Date            = ls.CreatedDate,
                                    UserName        = ls.Author != null && ls.Author.UserInfo != null ? ls.Author.UserInfo.DisplayUserName() : string.Empty,
                                    UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? CommonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL()) : string.Empty,
                                    Title           = HtmlUtil.GetText(ls.Title, 512),
                                    URL             = CommonLinkUtility.GetFullAbsolutePath(ls.ItemUrl),
                                    BreadCrumbs     = i == 0 ? new string[1] {
                                        gr.Key
                                    } : new string[0],
                                    Action = getWhatsNewActionText(ls)
                                });
                            }
                        }

                        if (whatsNewUserActivityGroupByPrjs.Count > 0)
                        {
                            activities.Add(ProjectsProductName, whatsNewUserActivityGroupByPrjs);
                        }

                        if (0 < activities.Count)
                        {
                            log.InfoFormat("Send whats new to {0}", user.Email);
                            client.SendNoticeAsync(
                                Constants.ActionSendWhatsNew, null, user, null,
                                new TagValue(Constants.TagActivities, activities),
                                new TagValue(Constants.TagDate, DateToString(scheduleDate.AddDays(-1), culture)),
                                new TagValue(CommonTags.Priority, 1)
                                );
                        }
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
Exemple #31
0
 protected void ChangeProjectStatus(ProjectStatus status)
 {
     SecurityContext.AuthenticateMe(Owner);
     Project.Status = status;
     SaveOrUpdate(Project);
 }
Exemple #32
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (Containers == null)
     {
         throw new ValidationException(ValidationRules.CannotBeNull, "Containers");
     }
     if (Affinity != null)
     {
         Affinity.Validate();
     }
     if (Containers != null)
     {
         foreach (var element in Containers)
         {
             if (element != null)
             {
                 element.Validate();
             }
         }
     }
     if (EphemeralContainers != null)
     {
         foreach (var element1 in EphemeralContainers)
         {
             if (element1 != null)
             {
                 element1.Validate();
             }
         }
     }
     if (InitContainers != null)
     {
         foreach (var element2 in InitContainers)
         {
             if (element2 != null)
             {
                 element2.Validate();
             }
         }
     }
     if (ReadinessGates != null)
     {
         foreach (var element3 in ReadinessGates)
         {
             if (element3 != null)
             {
                 element3.Validate();
             }
         }
     }
     if (SecurityContext != null)
     {
         SecurityContext.Validate();
     }
     if (TopologySpreadConstraints != null)
     {
         foreach (var element4 in TopologySpreadConstraints)
         {
             if (element4 != null)
             {
                 element4.Validate();
             }
         }
     }
     if (Volumes != null)
     {
         foreach (var element5 in Volumes)
         {
             if (element5 != null)
             {
                 element5.Validate();
             }
         }
     }
 }
 public CatalogSpiderTests()
 {
     logger = new DebugLogger();
     mediaFactory = new MediaFactory(logger);
     securityContext = new SecurityContext(mediaFactory);
 }
Exemple #34
0
        public void GenerateReport(DistributedTask task, CancellationToken cancellationToken)
        {
            try
            {
                Status = ReportStatus.Started;
                PublishTaskInfo();

                if (HttpContext.Current == null && !WorkContext.IsMono && !string.IsNullOrEmpty(ContextUrl))
                {
                    HttpContext.Current = new HttpContext(
                        new HttpRequest("hack", ContextUrl, string.Empty),
                        new HttpResponse(new System.IO.StringWriter()));
                }

                CoreContext.TenantManager.SetCurrentTenant(TenantId);
                SecurityContext.AuthenticateMe(UserId);

                Dictionary <string, string> urls;
                BuilderKey = DocumentServiceConnector.DocbuilderRequest(null, Script, true, out urls);

                while (true)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException();
                    }

                    Task.Delay(1500, cancellationToken).Wait(cancellationToken);
                    var builderKey = DocumentServiceConnector.DocbuilderRequest(BuilderKey, null, true, out urls);
                    if (builderKey == null)
                    {
                        throw new NullReferenceException();
                    }

                    if (urls != null && !urls.Any())
                    {
                        throw new Exception("Empty response");
                    }

                    if (urls != null && urls.ContainsKey(TmpFileName))
                    {
                        break;
                    }
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                SaveFileAction(this, urls[TmpFileName]);

                Status = ReportStatus.Done;
            }
            catch (Exception e)
            {
                Global.Logger.Error("DocbuilderReportsUtility error", e);
                Exception = e.Message;
                Status    = ReportStatus.Failed;
            }

            PublishTaskInfo();
        }
Exemple #35
0
		/// <summary>
		/// 从请求中初始化 Current 属性,这可将 SecurityContext 当前实例初始化化,后续对 Current 属性的访问不再依赖于具体的请求上下文,可避免访问已经释放的 OperationContext.Current 时发生错误,
		/// 并可提高后续访问的性能,但必须在执行结束时成对调用 ResetCurrent 方法,以防止在线程被复用时误用之前的上下文实例。
		/// </summary>
		public static void InitCurrent()
		{
			current = GetFromRequest();
		}
Exemple #36
0
        public NTStatus CreateFile(out object handle, out FileStatus fileStatus, string path, AccessMask desiredAccess, FileAttributes fileAttributes, ShareAccess shareAccess, CreateDisposition createDisposition, CreateOptions createOptions, SecurityContext securityContext)
        {
            handle     = null;
            fileStatus = FileStatus.FILE_DOES_NOT_EXIST;
            CreateRequest request = new CreateRequest();

            request.Name               = path;
            request.DesiredAccess      = desiredAccess;
            request.FileAttributes     = fileAttributes;
            request.ShareAccess        = shareAccess;
            request.CreateDisposition  = createDisposition;
            request.CreateOptions      = createOptions;
            request.ImpersonationLevel = ImpersonationLevel.Impersonation;
            TrySendCommand(request);

            SMB2Command response = m_client.WaitForCommand(SMB2CommandName.Create);

            if (response != null)
            {
                if (response.Header.Status == NTStatus.STATUS_SUCCESS && response is CreateResponse)
                {
                    CreateResponse createResponse = ((CreateResponse)response);
                    handle     = createResponse.FileId;
                    fileStatus = ToFileStatus(createResponse.CreateAction);
                }
                return(response.Header.Status);
            }

            return(NTStatus.STATUS_INVALID_SMB);
        }
Exemple #37
0
		private static SecurityContext GetFromRequest()
		{
			SecurityContext securityContext;

			// 经测试,访问 1亿次 System.ServiceModel.OperationContext.Current 用时 5 秒左右,每次 0.5 时间刻度(即2万分之一毫秒),完全不需要担心判断它是否存在会有性能问题
			OperationContext operationContext = OperationContext.Current;
			if (operationContext != null)
			{
				securityContext = OperationContextExtension.GetItem(operationContext, "_SecurityContext") as SecurityContext;

				if (securityContext == null)
				{
					securityContext = new SecurityContext(null, operationContext);

					OperationContextExtension.RegisterItem(operationContext, "_SecurityContext", securityContext);
				}

				return securityContext;
			}

			// 经测试,访问 1亿次 HttpContext.Current 用时 6 秒左右,每次 0.6 时间刻度(即2万分之一毫秒),完全不需要担心判断它是否存在会有性能问题
			HttpContext httpContext = HttpContext.Current;

			if (httpContext != null)
			{
				securityContext = httpContext.Items["_SecurityContext"] as SecurityContext;

				if (securityContext == null)
				{
					securityContext = new SecurityContext(httpContext, null);

					httpContext.Items["_SecurityContext"] = securityContext;
				}

				return securityContext;
			}

			// 即不存在服务上下文又不存在http上下文时,返回本地安全上下文(local)。
			return SecurityContext.local;
		}
Exemple #38
0
        public NTStatus CreateFile(out object handle, out FileStatus fileStatus, string path, AccessMask desiredAccess, FileAttributes fileAttributes, ShareAccess shareAccess, CreateDisposition createDisposition, CreateOptions createOptions, SecurityContext securityContext)
        {
            handle     = null;
            fileStatus = FileStatus.FILE_DOES_NOT_EXIST;
            NTCreateAndXRequest request = new NTCreateAndXRequest();

            request.FileName           = path;
            request.DesiredAccess      = desiredAccess;
            request.ExtFileAttributes  = ToExtendedFileAttributes(fileAttributes);
            request.ShareAccess        = shareAccess;
            request.CreateDisposition  = createDisposition;
            request.CreateOptions      = createOptions;
            request.ImpersonationLevel = ImpersonationLevel.Impersonation;

            TrySendMessage(request);
            SMB1Message reply = m_client.WaitForMessage(CommandName.SMB_COM_NT_CREATE_ANDX);

            if (reply != null)
            {
                if (reply.Commands[0] is NTCreateAndXResponse)
                {
                    NTCreateAndXResponse response = reply.Commands[0] as NTCreateAndXResponse;
                    handle     = response.FID;
                    fileStatus = ToFileStatus(response.CreateDisposition);
                    return(reply.Header.Status);
                }
                else if (reply.Commands[0] is ErrorResponse)
                {
                    return(reply.Header.Status);
                }
            }
            return(NTStatus.STATUS_INVALID_SMB);
        }
        // [TestMethod]
        public void RequestingAToken_ForTesterL_ReturnsValidToken()
        {
            var securityContext =
                new SecurityContext(new NetworkCredential("testerl", Passwords["testerl"], "fcsamerica"),
                    "MyAppName", "MyPartnerName");
            securityContext.AuditInfoServiceEndpoint = "https://devfcma.fcsamerica.net/mcgruff/web/";
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT;

            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));
        }
Exemple #40
0
 public List <object> GetServiceStatusList()
 {
     SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
     return(GetServiceNames().Select(serviceName => ToAjaxResponse(serviceName, GetServiceController(serviceName))).ToList());
 }
            SecurityContextInstance_WithProvidedConstructorWithNetworkCredentialsCalledMoreThanOnce_ReturnsTokenForThoseCredentials()
        {
           var securityContext =
                new SecurityContext(new NetworkCredential("agrilytic_o", Passwords["agrilytic_o"], "fcsamerica"),
                    "MyApplicationName", "MyPartnerName");
            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT;


            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            securityContext =
              new SecurityContext(new NetworkCredential("agrilytic_o", Passwords["agrilytic_o"], "fcsamerica"),
                  "MyApplicationName", "MyPartnerName");
            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = AUTHENTICATION_ENDPOINT;


            serviceToken = securityContext.ServiceToken;
            auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));
        }
 public DbContext Create()
 {
     SecurityContext dbContent = new SecurityContext();
     //dbContent.Configuration.LazyLoadingEnabled = false;下了這條,表示Lazy Loading不作用,但不表示eager Loading就會作用
     return dbContent;
 }
            SecurityContextInstance_WithProvidedConstructorWithNetworkCredentialsForNWFCS_ReturnsTokenForThoseCredentials
            ()
        {
            var securityContext = new SecurityContext(new NetworkCredential("drawal", Passwords["drawal"], "NFCS"),
                "MyApplicationName", "MyPartnerName");
            securityContext.AuditInfoServiceEndpoint = AUDITINFO_SERVICE_ENDPOINT;
            securityContext.AuthenticationEndpoint = "https://inttestnwfcs.fcsamerica.net/mcgruff/adminui/";


            var serviceToken = securityContext.ServiceToken;
            var auditInfo = securityContext.AuditInfo;

            Assert.IsFalse(String.IsNullOrEmpty(serviceToken));
            Assert.IsFalse(String.IsNullOrEmpty(auditInfo));
        }
 public static void Run(SecurityContext securityContext, System.Threading.ContextCallback callback, object state)
 {
 }
Exemple #45
0
 public object GetServiceStatus(string serviceName)
 {
     SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
     return(ToAjaxResponse(serviceName, GetServiceController(serviceName)));
 }
Exemple #46
0
 protected void RestrictAccess(Guid userID, ProjectTeamSecurity projectTeamSecurity, bool visible)
 {
     SecurityContext.AuthenticateMe(Owner);
     ProjectEngine.SetTeamSecurity(Project, ParticipantEngine.GetByID(userID), projectTeamSecurity, visible);
 }
Exemple #47
0
        /// <summary>
        /// Updates dk COIN Resource Type displayed by default (Admins only)
        /// </summary>
        /// <param name="dkResourceTypeID">ID object</param>
        /// <param name="DisplayResource">bool object</param>
        /// <param name="sc">Security Context object</param>
        public virtual void UpdateDKCoinResourceType(ID dkResourceTypeID, bool DisplayResource, SecurityContext sc)
        {
            if (sc == null || !sc.Member.IsAdministrator)
                throw new InsufficientPrivilegesException();

            try
            {
                BeginTransaction();
                DbCommand cmd = OpenDbCommand("DKC_UpdateDKCoinResourceType");
                cmd.AddInputParameter("@p_ResourceTypeID", dkResourceTypeID);
                cmd.AddInputParameter("@p_DisplayResource", DisplayResource);

                cmd.ExecuteNonQuery();

                CommitTransaction();
            }
            catch (Exception e)
            {
                throw new UpdateObjectException(typeof(DKCoinResourceType), dkResourceTypeID);
            }
            finally
            {
                EndTransaction();
            }
        }
Exemple #48
0
        public List <MailTag> GetTagsList(int id_tenant, string id_user, bool mail_only)
        {
            var tags = new Dictionary <int, MailTag>();

            using (var db = GetDb())
            {
                db.ExecuteList(new SqlQuery(MAIL_TAG)
                               .Select(TagFields.id, TagFields.name, TagFields.style, TagFields.addresses, TagFields.count, TagFields.crm_id)
                               .Where(GetUserWhere(id_user, id_tenant)))
                .ForEach(r =>
                         tags.Add(0 < Convert.ToInt32(r[5]) ? -Convert.ToInt32(r[5]) : Convert.ToInt32(r[0]),
                                  new MailTag((0 < Convert.ToInt32(r[5]) && !mail_only) ? -Convert.ToInt32(r[5]) : Convert.ToInt32(r[0])
                                              , (string)r[1]
                                              , !string.IsNullOrEmpty(r[3].ToString()) ? r[3].ToString().Split(';').ToList() : new List <string>()
                                              , ConvertToString(r[2])
                                              , Convert.ToInt32(r[4])))
                         );
            }

            if (mail_only)
            {
                return(tags.Values.Where(p => p.Name != "").OrderByDescending(p => p.Id).ToList());
            }

            #region Set up connection to CRM sequrity
            CoreContext.TenantManager.SetCurrentTenant(id_tenant);
            SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(new Guid(id_user)));

            if (!WebItemSecurity.IsAvailableForUser(WebItemManager.CRMProductID.ToString(),
                                                    SecurityContext.CurrentAccount.ID))
            {
                return(tags.Values.Where(p => p.Name != "").OrderByDescending(p => p.Id).ToList());
            }

            if (!DbRegistry.IsDatabaseRegistered("crm"))
            {
                DbRegistry.RegisterDatabase("crm", ConfigurationManager.ConnectionStrings["crm"]);
            }

            #endregion

            using (var db = new DbManager("crm"))
            {
                var q = new SqlQuery(CRM_TAG + " t")
                        .Select("t." + CrmTagFields.id, "t." + CrmTagFields.title)
                        .Where(Exp.Eq("t." + CrmTagFields.tenant_id, id_tenant))
                        .Where(Exp.Eq("t." + CrmTagFields.entity_type, CRM_CONTACT_ENTITY_TYPE));

                var crm_tags = db.ExecuteList(q)
                               .ConvertAll(r =>
                                           new MailTag(-Convert.ToInt32(r[0])
                                                       , (string)r[1]
                                                       , new List <string>()
                                                       , ""
                                                       , 0));

                foreach (var tag in crm_tags)
                {
                    if (tags.ContainsKey(tag.Id))
                    {
                        tags[tag.Id].Name = tag.Name;
                    }
                    else
                    {
                        tags.Add(tag.Id, tag);
                    }
                }
            }

            return(tags.Values.Where(t => t.Name != "").OrderByDescending(p => p.Id).ToList());
        }
 public ListViewEnfermeiro(ApplicationContext _db, SecurityContext _seguranca_db)
 {
     this.Create(_db, _seguranca_db);
 }
 public EnfermeiroModel(ApplicationContext _db, SecurityContext _seguranca_db)
 {
     this.Create(_db, _seguranca_db);
 }
 public AuthenticatedAsyncRequestDispatcher(IAsyncRequestProcessor requestProcessor, SecurityContext securityContext)
     : base(requestProcessor)
 {
     _securityContext = securityContext;
 }
		/// <summary>
		/// Initialize the appender based on the options set.
		/// </summary>
		/// <remarks>
		/// <para>
		/// This is part of the <see cref="IOptionHandler"/> delayed object
		/// activation scheme. The <see cref="ActivateOptions"/> method must 
		/// be called on this object after the configuration properties have
		/// been set. Until <see cref="ActivateOptions"/> is called this
		/// object is in an undefined state and must not be used. 
		/// </para>
		/// <para>
		/// If any of the configuration properties are modified then 
		/// <see cref="ActivateOptions"/> must be called again.
		/// </para>
		/// <para>
		/// The appender will be ignored if no <see cref="Recipient" /> was specified.
		/// </para>
		/// </remarks>
		/// <exception cref="ArgumentNullException">The required property <see cref="Recipient" /> was not specified.</exception>
		public override void ActivateOptions()
		{
			base.ActivateOptions();
	
			if (this.Recipient == null) 
			{
				throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified.");
			}

			if (m_securityContext == null)
			{
				m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this);
			}
		}