Example #1
0
        protected void Page_Init(object sender, EventArgs e)
        {
            // Security stuff
            // Current authentication

            string identity = HttpContext.Current.User.Identity.Name;

            string[] identityTokens = identity.Split(',');

            string userIdentityString         = identityTokens[0];
            string organizationIdentityString = identityTokens[1];

            int currentUserId         = Convert.ToInt32(userIdentityString);
            int currentOrganizationId = Convert.ToInt32(organizationIdentityString);

            _currentUser = Person.FromIdentity(currentUserId);
            _authority   = _currentUser.GetAuthority();
            try
            {
                _currentOrganization = Organization.FromIdentity(currentOrganizationId);
            }
            catch (ArgumentException)
            {
                if (PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
                {
                    // It's possible this organization was deleted. Log on to Sandbox instead.
                    _currentOrganization = Organization.Sandbox;
                }
            }
        }
Example #2
0
    protected override void OnLoad(EventArgs e)
    {
        int currentUserId         = 0;
        int currentOrganizationId = 0;

        string identity = HttpContext.Current.User.Identity.Name;

        string[] identityTokens = identity.Split(',');

        string userIdentityString         = identityTokens[0];
        string organizationIdentityString = identityTokens[1];

        currentUserId         = Convert.ToInt32(userIdentityString);
        currentOrganizationId = Convert.ToInt32(organizationIdentityString);
        this._currentUser     = Person.FromIdentity(currentUserId);
        this._authority       = this._currentUser.GetAuthority();
        try
        {
            this._currentOrganization = Organization.FromIdentity(currentOrganizationId);
        }
        catch (ArgumentException)
        {
            if (PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
            {
                // It's possible this organization was deleted. Log on to Sandbox instead.
                this._currentOrganization = Organization.Sandbox;
            }
        }

        base.OnLoad(e);
    }
Example #3
0
        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                this._authority = CommonV5.GetAuthenticationDataAndCulture(HttpContext.Current).Authority;
            }
            catch (Exception)
            {
                // if this fails FOR WHATEVER REASON then we're not authenticated

                this._authority = null;
                FormsAuthentication.SignOut();
                Response.Redirect("/", true);
            }

            // BEGIN TEST CODE

            // VatReports.CreateNewReports();

            // END TEST CODE


            if (this._authority.Organization.Identity == 3 &&
                PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
            {
                this._authority = null;
                FormsAuthentication.SignOut();
                Response.Redirect("/", true);
            }
        }
Example #4
0
        private void PopulateRepeater()
        {
            Participations participations = CurrentUser.GetMemberships();

            List <OrganizationParameters> availableOrganizations = new List <OrganizationParameters>();

            foreach (Participation membership in participations)
            {
                if (membership.OrganizationId == 1 && !PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                {
                    // sandbox. Ignore.
                    continue;
                }

                OrganizationParameters newOrganization = new OrganizationParameters();
                newOrganization.LogoUrl          = "/Images/Flags/txl-64px.png";
                newOrganization.OrganizationId   = membership.OrganizationId;
                newOrganization.OrganizationName = membership.Organization.Name;

                availableOrganizations.Add(newOrganization);
            }

            OrganizationCount = availableOrganizations.Count;

            this.RepeaterOrganizations.DataSource = availableOrganizations;
            this.RepeaterOrganizations.DataBind();
        }
        public static AjaxCallResult ExecuteSend(int recipientTypeId, int geographyId, string mode, string subject,
                                                 string body, string dummyMail, bool live)
        {
            AuthenticationData authData = GetAuthenticationDataAndCulture();

            if (PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox) && authData.CurrentUser.Identity == 1 && !live)
            {
                OutboundComm.CreateSandboxMail(subject, body, dummyMail);
                return(new AjaxCallResult {
                    Success = true
                });
            }
            else if (!live)
            {
                // Test mail

                OutboundComm.CreateParticipantMail(subject, body,
                                                   authData.CurrentUser.ParticipationOf(authData.CurrentOrganization), authData.CurrentUser);

                return(new AjaxCallResult {
                    Success = true
                });
            }
            else // Send live
            {
                // TODO: change resolver to match selected group

                OutboundComm.CreateParticipantMail(subject, body, authData.CurrentUser, authData.CurrentUser, authData.CurrentOrganization, Geography.FromIdentity(geographyId));
                return(new AjaxCallResult {
                    Success = true
                });
            }
        }
Example #6
0
    /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);

        string identity = HttpContext.Current.User.Identity.Name;

        if (!string.IsNullOrEmpty(identity))
        {
            string[] identityTokens = identity.Split(',');

            string userIdentityString         = identityTokens[0];
            string organizationIdentityString = identityTokens[1];

            CurrentUser = Person.FromIdentity(Int32.Parse(userIdentityString));
            try
            {
                CurrentOrganization = Organization.FromIdentity(Int32.Parse(organizationIdentityString));
            }
            catch (ArgumentException)
            {
                if (PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
                {
                    // It's possible this organization was deleted. Log on to Sandbox instead.
                    CurrentOrganization = Organization.Sandbox;
                }
            }
        }
        else
        {
            CurrentUser         = null; // unauthenticated!
            CurrentOrganization = null; // unauthenticated!
        }
    }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check if this is the first run ever. If so, redirect to Init.

            if (!SwarmDb.Configuration.IsConfigured())
            {
                Response.Redirect("/Pages/v5/Init/", true);
                return;
            }

            // If this is the Dev Sandbox, autologin

            if (Request.Url.Host == "dev.swarmops.com" &&
                PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
            {
                Response.AppendCookie(new HttpCookie("DashboardMessage",
                                                     HttpUtility.UrlEncode(
                                                         "<p>You have been logged on as <strong>Sandbox Administrator</strong> to the Swarmops Development Sandbox.</p><br/><p>This machine runs the latest development build, so you may run into diagnostic code and half-finished features. All data here is bogus test data and is reset every night.</p><br/><p><strong>In other words, welcome, and play away!</strong></p><br/><br/>")));
                FormsAuthentication.RedirectFromLoginPage("1,1", true);
            }


            // THE DAMN BITID NEEDS TO GO INTO ANDROID WALLET SO WE CAN STREAMLINE AND REWRITE THIS POS


            this.LabelLoginFailed.Visible = false;
            this.TextLogin.Focus();


            // Check for SSL and force it

            // Special case for CloudFlare deployments - there is a case where somebody will get their connections de-SSLed at the server

            string cloudFlareVisitorScheme = Request.Headers["CF-Visitor"];
            bool   cloudFlareSsl           = false;

            if (!string.IsNullOrEmpty(cloudFlareVisitorScheme))
            {
                if (cloudFlareVisitorScheme.Contains("\"scheme\":\"https\""))
                {
                    cloudFlareSsl = true;
                }
            }

            // TODO: Same thing for Pound deployments

            // Rewrite if applicable

            if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl)
            // only check client-side as many server sites de-SSL the connection before reaching the web server
            {
                if (!Request.Url.ToString().StartsWith("http://dev.swarmops.com/") &&
                    !Request.Url.ToString().StartsWith("http://localhost:") &&
                    !Request.Url.ToString().StartsWith("http://swarmops-"))
                {
                    Response.Redirect(Request.Url.ToString().Replace("http:", "https:"));
                }
            }
        }
Example #8
0
        public static void VerifyBitcoinHotWallet()
        {
            // This must only be run from the backend

            if (HttpContext.Current != null)
            {
                throw new InvalidOperationException("Checking root keys cannot be done from the frontend");
            }

            // Make sure there's always a private hotwallet root, regardless of whether it's used or not

            if (!File.Exists(SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet"))
            {
                ExtKey privateRoot = new ExtKey();
                File.WriteAllText(SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet",
                                  privateRoot.GetWif(Network.Main).ToWif(), Encoding.ASCII);
                File.WriteAllText(
                    SystemSettings.EtcFolder + Path.DirectorySeparatorChar + "hotwallet-created-" +
                    DateTime.UtcNow.ToString("yyyy-MM-dd--HH-mm-ss--fff.backup"),
                    privateRoot.GetWif(Network.Main).ToWif(), Encoding.ASCII);  // an extra backup

                if (String.IsNullOrEmpty(Persistence.Key["BitcoinHotPublicRoot"]))
                {
                    Persistence.Key["BitcoinHotPublicRoot"] = privateRoot.Neuter().GetWif(Network.Main).ToWif();
                }
            }
            else
            {
                // The file exists. Does the database have the hotwallet public root?

                if (Persistence.Key["BitcoinHotPublicRoot"].Length < 3)
                {
                    // No, it has disappeared, which can happen for a few bad reasons

                    Persistence.Key["BitcoinHotPublicRoot"] =
                        BitcoinHotPrivateRoot.Neuter().GetWif(Network.Main).ToWif();
                    if (!PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
                    {
                        // TODO: Log some sort of exception (the sandbox db is reset every night, so it's ok to lose the public key from there)
                    }
                }

                // Is the hotwallet public root equal to the private root, while in production environment?

                // ReSharper disable once RedundantCheckBeforeAssignment
                if (Persistence.Key["BitcoinHotPublicRoot"] !=
                    BitcoinHotPrivateRoot.Neuter().GetWif(Network.Main).ToWif() && !Debugger.IsAttached)
                {
                    // SERIOUS CONDITION - the public root key did not match the private root key. This needs to be logged somewhere.
                    OutboundComm.CreateNotification(NotificationResource.System_PublicRootReset);

                    // Reset it
                    Persistence.Key["BitcoinHotPublicRoot"] =
                        BitcoinHotPrivateRoot.Neuter().GetWif(Network.Main).ToWif();
                }
            }
        }
Example #9
0
        // ReSharper disable once InconsistentNaming
        public static string TestCredentials(string credentialsLogin, string credentialsPass, string credentials2FA,
                                             string logonUriEncoded)
        {
            if (!string.IsNullOrEmpty(credentialsLogin.Trim()) && !string.IsNullOrEmpty(credentialsPass.Trim()))
            {
                string logonUri = HttpUtility.UrlDecode(logonUriEncoded);

                try
                {
                    Person authenticatedPerson = Authentication.Authenticate(credentialsLogin,
                                                                             credentialsPass);

                    int lastOrgId = authenticatedPerson.LastLogonOrganizationId;

                    if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE) && (lastOrgId == 3 || lastOrgId == 0))
                    {
                        lastOrgId = 1;                                   // legacy: log on to Piratpartiet SE if indeterminate; prevent sandbox for this pilot
                        authenticatedPerson.LastLogonOrganizationId = 1; // avoid future legacy problems
                    }
                    else if (lastOrgId == 0)
                    {
                        lastOrgId = Organization.SandboxIdentity;
                    }

                    Authority testAuthority = Authority.FromLogin(authenticatedPerson,
                                                                  Organization.FromIdentity(lastOrgId));

                    if (!authenticatedPerson.MemberOfWithInherited(lastOrgId) && !testAuthority.HasSystemAccess(AccessType.Read))
                    {
                        // If the person doesn't have access to the last organization (anymore), log on to Sandbox
                        // unless first pilot, in which case throw (deny login)

                        if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                        {
                            throw new UnauthorizedAccessException();
                        }

                        lastOrgId = Organization.SandboxIdentity;
                    }

                    GuidCache.Set(logonUri + "-LoggedOn",
                                  Authority.FromLogin(authenticatedPerson, Organization.FromIdentity(lastOrgId)).ToEncryptedXml());

                    return("Success");  // Prepare here for "2FARequired" return code
                }
                catch (UnauthorizedAccessException)
                {
                    return("Fail");
                }
            }

            return("Fail");
        }
Example #10
0
    public static AuthenticationData GetAuthenticationDataAndCulture(HttpContext suppliedContext)
    {
        // This function is called from static page methods in AJAX calls to get
        // the current set of authentication data. Static page methods cannot access
        // the instance data of PageV5Base.

        AuthenticationData result = new AuthenticationData();

        // Find various credentials

        string identity = suppliedContext.User.Identity.Name;

        // TODO: If identity is null or empty, set null user + org

        string[] identityTokens = identity.Split(',');

        string userIdentityString         = identityTokens[0];
        string organizationIdentityString = identityTokens[1];

        int currentUserId         = Convert.ToInt32(userIdentityString);
        int currentOrganizationId = Convert.ToInt32(organizationIdentityString);

        result.CurrentUser = Person.FromIdentity(currentUserId);
        try
        {
            result.CurrentOrganization = Organization.FromIdentity(currentOrganizationId);
        }
        catch (ArgumentException)
        {
            if (PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
            {
                // It's possible this organization was deleted. Log on to Sandbox instead.
                result.CurrentOrganization = Organization.Sandbox;
            }
        }

        CulturePreInit(HttpContext.Current.Request);
        // OnPreInit() isn't called in the static methods calling this fn

        /*
         * string userCultureString = result.CurrentUser.PreferredCulture;
         *
         * if (!string.IsNullOrEmpty(userCultureString))
         * {
         *  CultureInfo userCulture = new CultureInfo(userCultureString); // may throw on invalid database data
         *  Thread.CurrentThread.CurrentCulture = userCulture;
         *  Thread.CurrentThread.CurrentUICulture = userCulture;
         * }*/

        return(result);
    }
        private void PopulateRepeater()
        {
            Participations participations = CurrentUser.GetParticipations();

            List <OrganizationParameters> availableOrganizations = new List <OrganizationParameters>();

            foreach (Participation membership in participations)
            {
                if (membership.OrganizationId == 1 && !PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                {
                    // sandbox. Ignore.
                    continue;
                }

                Organization           organization = membership.Organization;
                OrganizationParameters newOrganizationParameters = new OrganizationParameters();

                string logoUrl = "/Images/Other/blank-logo-640x360.png";

                Document logoLandscape = organization.LogoLandscape;

                try
                {
                    if (logoLandscape != null)
                    {
                        newOrganizationParameters.LogoImage = logoLandscape.Image.GetBase64(64, 36);
                    }
                }
                catch (Exception)
                {
                    newOrganizationParameters.LogoImage = "/Images/Flags/txl-64px.png";
                }
                newOrganizationParameters.OrganizationId   = membership.OrganizationId;
                newOrganizationParameters.OrganizationName = membership.Organization.Name;

                availableOrganizations.Add(newOrganizationParameters);
            }

            OrganizationCount = availableOrganizations.Count;

            this.RepeaterOrganizations.DataSource = availableOrganizations;
            this.RepeaterOrganizations.DataBind();
        }
Example #12
0
        public static void InitializeProcessing(string guid)
        {
            // Start an async thread that does all the work, then return


            // FORMAT OF FILE
            //
            // Tab separated fields
            //
            // [countrycode] [tab] [geo1] [tab] [geo2] [tab] .. [tab] [geo_n]
            //
            // example:
            //
            // NL [Tab] Noord-Holland [Tab] Greater Amsterdam
            // NL [Tab] Noord-Holland [Tab] Greater Amsterdam [Tab] Amsterdam
            // NL [Tab] Noord-Holland [Tab] Greater Amsterdam [Tab] Amsterdam [Tab] Wallen
            //
            // To populate all five nodes (including country), only the last line is necessary, but all these lines are valid.
            //
            // Nodes are not re-populated on repetition. Node names within a country scope are required to
            // be unique.


            if (!PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && !Debugger.IsAttached)
            {
                // throw new UnauthorizedAccessException("This may only run on Swarmops Master");
            }

            AuthenticationData authData = GetAuthenticationDataAndCulture();

            if (
                !authData.CurrentUser.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Unknown,
                                                           AccessType.Write)))
            {
                throw new UnauthorizedAccessException();
            }

            Thread initThread = new Thread(ProcessUploadThread);

            initThread.Start(guid);
        }
Example #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string externalScriptUrl = "//hostedscripts.falkvinge.net";

            string testFolderName = Server.MapPath("~/Scripts/ExternalScripts");

            if (Directory.Exists(testFolderName))
            {
                externalScriptUrl = "/Scripts/ExternalScripts";
            }
            else if (Debugger.IsAttached ||
                     PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
            {
                externalScriptUrl += "/staging";
                // use staging area for new script versions on Sandbox and for all debugging
            }

            if (Package == "easyui")
            {
                StringBuilder scriptRef = new StringBuilder();

                scriptRef.Append("<script src=\"" + externalScriptUrl +
                                 "/easyui/jquery.easyui.min.js\" type=\"text/javascript\"></script>\r\n");
                scriptRef.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + externalScriptUrl +
                                 "/easyui/themes/icon.css\" />\r\n");
                string[] controlNames = Controls.Split(',');
                foreach (string controlName in controlNames)
                {
                    string controlNameLower = controlName.Trim().ToLowerInvariant();
                    if (controlNameLower != "unknown")
                    {
                        scriptRef.AppendFormat(
                            "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + externalScriptUrl +
                            "/easyui/themes/default/{0}.css\" />\r\n",
                            controlNameLower);
                    }
                }

                this.LiteralReference.Text = scriptRef.ToString();
            }
        }
        public static void InitializeProcessing(string guid)
        {
            // Start an async thread that does all the work, then return


            // FORMAT OF FILE
            //
            // Tab separated fields
            //
            // [countrycode] [tab] [postalCode] [tab] [cityName] [tab] [geoNodeName]
            //
            // example:
            //
            // NL [Tab] 1026 [Tab] Amsterdam-Zuid [Tab] Amsterdam
            //
            // For countries that don't use postal codes, leave the postal code field empty.
            //
            // Node names within a country scope are required to be unique.


            if (!PilotInstallationIds.IsPilot(PilotInstallationIds.SwarmopsLive) && !Debugger.IsAttached)
            {
                // throw new UnauthorizedAccessException("This may only run on Swarmops Master");
            }



            AuthenticationData authData = GetAuthenticationDataAndCulture();

            if (
                !authData.CurrentUser.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.Unknown,
                                                           AccessType.Write)))
            {
                throw new UnauthorizedAccessException();
            }

            Thread initThread = new Thread(ProcessUploadThread);

            initThread.Start(guid);
        }
Example #15
0
        private static void Main(string[] args)
        {
            // Are we running yet?

            if (!SystemSettings.DatabaseInitialized)
            {
                // will restart the service every 15s until db initialized on OOBE
                // also, the read of DatabaseInitialized can and will fail if
                // we're not initalized enough to even have a database

                throw new InvalidOperationException();
            }

            // Check if we're Sandbox

            if (PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
            {
                _isSandbox = true;
            }

            // Disable SSL cert checking (because Mono doesn't have a cert repo, dammit)
            Swarmops.Logic.Support.SupportFunctions.DisableSslCertificateChecks();

            // Other one-off initializations
            SupportFunctions.OperatingTopology = OperatingTopology.FrontendSocket;

            // Initiate main loop

            UnixSignal[] killSignals = null;
            _activeAlarms = new Dictionary <FrontendMalfunctions, bool>();

            if (!Debugger.IsAttached)
            {
                killSignals = new UnixSignal[] { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGTERM) };
            }

            Console.WriteLine(" * Swarmops Frontend Socket Server starting up.");

            OutboundComm.CreateNotification(null, NotificationResource.System_Startup_Frontend);

            // Initialize socket server and client

            _socketServer = new WebSocketServer(SystemSettings.WebsocketPortFrontend);
            _socketServer.AddWebSocketService <FrontendServices>("/Front");
            // _socketServer.KeepClean = false; // as per the author's recommendation - this may be bad in the long run
            _socketServer.Start();

            DateTime cycleStartTime = DateTime.UtcNow;
            DateTime cycleEndTime;

            int lastSecond = cycleStartTime.Second;
            int lastMinute = cycleStartTime.Minute;
            int lastHour   = cycleStartTime.Hour;

            string backendHostname = SystemSettings.BackendHostnameOverride;

            if (String.IsNullOrEmpty(backendHostname))
            {
                backendHostname = SystemSettings.BackendHostname;
            }

            string backendSocketUri = "ws://" + backendHostname + ":" +
                                      SystemSettings.WebsocketPortBackend.ToString(CultureInfo.InvariantCulture) +
                                      "/Backend?Auth=" + Authority.GetSystemAuthorityToken("Frontend");

            bool exitFlag = false;

            Console.WriteLine("Connecting backend socket " + backendSocketUri);

            using (_backendSocket = new WebSocket(backendSocketUri))
            {
                _backendSocket.OnMessage += new EventHandler <MessageEventArgs>(OnBackendMessage);
                _backendSocket.OnOpen    += new EventHandler(OnBackendOpen);
                _backendSocket.OnClose   += new EventHandler <CloseEventArgs>(OnBackendClose);
                _backendSocket.OnError   += new EventHandler <ErrorEventArgs>(OnBackendError);
                _backendSocket.Connect();

                while (!exitFlag) // exit is handled by signals handling at end of loop
                {
                    cycleStartTime = DateTime.UtcNow;
                    cycleEndTime   = cycleStartTime.AddSeconds(10);

                    try
                    {
                        OnEveryTenSeconds();

                        if (cycleStartTime.Second < lastSecond)
                        {
                            OnEveryMinute();

                            if (cycleStartTime.Minute % 5 == 0)
                            {
                                OnEveryFiveMinutes();
                            }

                            if (cycleStartTime.Minute % 30 == 0)
                            {
                                OnEveryHalfHour();
                            }
                        }

                        if (cycleStartTime.Minute < lastMinute)
                        {
                            OnEveryHour();

                            if (DateTime.Now.Hour == 10 && DateTime.Today.DayOfWeek == DayOfWeek.Tuesday)
                            {
                                // OnTuesdayMorning();
                            }
                        }

                        if (cycleStartTime.Hour >= 12 && lastHour < 12)
                        {
                            // OnNoon();
                        }

                        if (cycleStartTime.Hour < lastHour)
                        {
                            // OnMidnight();
                        }
                    }

                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());

                        // Note each "OnEvery..." catches its own errors and sends Exception mails,
                        // so that failure in one should not stop the others from running. This particular
                        // code should never run.

                        // ExceptionMail.Send (new Exception ("Failed in swarmops-backend main loop", e), true);
                    }

                    lastSecond = cycleStartTime.Second;
                    lastMinute = cycleStartTime.Minute;
                    lastHour   = cycleStartTime.Hour;

                    // Wait for a maximum of ten seconds (the difference between cycleStartTime and cycleEndTime)

                    DateTime utcNow = DateTime.UtcNow;
                    while (utcNow < cycleEndTime && !exitFlag)
                    {
                        int signalIndex = 250;

                        // Block until a SIGINT or SIGTERM signal is generated, or 1/4 second has passed.
                        // However, we can't do that in a development environment - it won't have the
                        // Mono.Posix assembly, and won't understand UnixSignals. So people running this in
                        // a dev environment will need to stop it manually.

                        if (!Debugger.IsAttached)
                        {
                            signalIndex = UnixSignal.WaitAny(killSignals, 250);
                        }
                        else
                        {
                            Thread.Sleep(250);
                        }

                        if (signalIndex < 250)
                        {
                            exitFlag = true;
                            Console.WriteLine(" * Swarmops Frontend Socket Server caught signal " +
                                              killSignals[signalIndex].Signum + ", exiting");
                        }

                        utcNow = DateTime.UtcNow;
                    }
                }

                _socketServer.Stop();
                Thread.Sleep(2000);

                Console.WriteLine(" * Swarmops Frontend Socket Server exiting");
            }
        }
Example #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check if this is the first run ever. If so, redirect to Init.

            if (!SwarmDb.Configuration.IsConfigured())
            {
                Response.Redirect("/Pages/v5/Init/", true);
                return;
            }

            // Persistence.Key["Debug_RawData"] = Request.ToRaw();

            // Check for POST data - for BitId via Webform

            if (Request.HttpMethod == "POST")
            {
                // We should ONLY get here if we're getting a BitId by Webform submission.

                Persistence.Key["BitId_RawData"] = Request.ToRaw();

                if (Request.Params["address"] != null)
                {
                    // yes, indeed looks like it

                    BitIdCredentials credentials = new BitIdCredentials
                    {
                        address   = Request.Params["address"],
                        uri       = Request.Params["uri"],
                        signature = Request.Params["signature"]
                    };

                    ProcessRespondBitId(credentials, Response);
                    return;
                }
                if (Request.ContentType == "application/json")
                {
                    BitIdCredentials credentials =
                        new JavaScriptSerializer().Deserialize <BitIdCredentials> (
                            new StreamReader(Request.InputStream).ReadToEnd());
                    // TODO: untested but seems to work. Throws?

                    ProcessRespondBitId(credentials, Response);
                    return;
                }
            }


            // If this is the Dev Sandbox, autologin

            if (Request.Url.Host == "dev.swarmops.com" &&
                PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox) &&
                Request.QueryString["SuppressAutologin"] != "true")
            {
                Response.AppendCookie(new HttpCookie("DashboardMessage",
                                                     HttpUtility.UrlEncode(
                                                         "<p>You have been logged on as <strong>Sandbox Administrator</strong> to the Swarmops Development Sandbox.</p><br/><p>This machine runs the latest development build, so you may run into diagnostic code and half-finished features. All data here is bogus test data and is reset every night.</p><br/><p><strong>In other words, welcome, and play away!</strong></p>")));
                FormsAuthentication.SetAuthCookie("1,1", true);
                Response.Redirect("/");
            }

            // Check for SSL and force it

            // Special case for CloudFlare deployments - there is a case where somebody will get their connections de-SSLed at the server

            string cloudFlareVisitorScheme = Request.Headers["CF-Visitor"];
            bool   cloudFlareSsl           = false;

            if (!string.IsNullOrEmpty(cloudFlareVisitorScheme))
            {
                if (cloudFlareVisitorScheme.Contains("\"scheme\":\"https\""))
                {
                    cloudFlareSsl = true;
                }
            }

            // TODO: Same thing for Pound deployments

            // Rewrite if applicable

            if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl)
            // only check client-side as many server sites de-SSL the connection before reaching the web server
            {
                if (!Request.Url.ToString().StartsWith("http://dev.swarmops.com/") &&
                    !Request.Url.ToString().StartsWith("http://localhost:"))
                {
                    Response.Redirect(Request.Url.ToString().Replace("http:", "https:"));
                }
            }

            this.ImageCultureIndicator.Style[HtmlTextWriterStyle.MarginTop]   = "-3px";
            this.ImageCultureIndicator.Style[HtmlTextWriterStyle.MarginRight] = "3px";
            this.ImageCultureIndicator.Style[HtmlTextWriterStyle.Cursor]      = "pointer";

            Localize();

            // Generate BitID tokens

            Guid   guid       = Guid.NewGuid();
            string guidString = guid.ToString().Replace("-", "");

            string nonce = guidString + DateTime.UtcNow.Ticks.ToString("x8");

            string hostName = Request.Url.Host;

            string bitIdUri = "bitid://" + hostName + "/Security/Login.aspx?x=" + nonce;

            if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl)
            {
                bitIdUri += "&u=1";
            }

            this.LiteralUri.Text   = HttpUtility.UrlEncode(bitIdUri);
            this.LiteralNonce.Text = nonce;

            GuidCache.Set(bitIdUri + "-Logon", "Unauth");

            // TODO: need to NOT USE GOOGLE CHARTS for this but bring home a free QR package

            this.ImageBitIdQr.ImageUrl =
                "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=" + HttpUtility.UrlEncode(bitIdUri);
        }
Example #17
0
        /// <summary>
        ///     Returns one authenticated user from login token and password.
        /// </summary>
        /// <param name="loginToken">The login token provided.</param>
        /// <param name="password">The password provided.</param>
        /// <returns>Exactly one authenticated user, if successful.</returns>
        /// <exception cref="UnauthorizedAccessException">
        ///     This function will throw an UnauthorizedAccessException if the user
        ///     cannot be authenticated using the supplied credentials.
        /// </exception>
        public static Person Authenticate(string loginToken, string password)
        {
            // Get the list of people that match the login token.

            People candidatePeople   = GetPeopleByLoginToken(loginToken);
            Person authenticatedUser = null;

            // For every person in the list, test the supplied password against the current and legacy hash schemes.

            foreach (Person candidate in candidatePeople)
            {
                // Check that the candidate has at least one valid membership.

                bool hasActiveMemberships = false;

                Memberships memberships = candidate.GetMemberships();

                foreach (Membership membership in memberships)
                {
                    if (membership.Active)
                    {
                        hasActiveMemberships = true;
                        break;
                    }
                }

                // If no active memberships, do not authenticate against this candidate.

                if (!hasActiveMemberships)
                {
                    continue;
                }

                // Check the credentials.

                bool goodCredentials = false;

                if (CheckPassword(candidate, password))
                {
                    goodCredentials = true;
                }
                else if (PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                {
                    // If the most recent password hash mechanism fails, try legacy hashes IF on pilot installation

                    string[] legacyHashes = GenerateLegacyPasswordHashes(candidate, password);

                    foreach (string legacyHash in legacyHashes)
                    {
                        if (legacyHash == candidate.PasswordHash)
                        {
                            goodCredentials = true;
                        }
                    }
                }

                // Now we've iterated over the possible password hashes for the candidate. Were the credentials good?

                if (goodCredentials)
                {
                    // We have a set of good credentials. As a security mechanism, make sure that we haven't approved another
                    // user already using these credentials. In theory, the chances of this happening with SHA-1 hashes is less
                    // than astronomical, but anyway.

                    if (authenticatedUser != null)
                    {
                        // We have a double credentials hit. This becomes a serious security concern.
                        // TODO: Alert operator about this, it's a serious condition.

                        throw new UnauthorizedAccessException("Double credentials hit");
                    }

                    // The current candidate has good credentials:

                    authenticatedUser = candidate;
                }
            }

            // If a user came through as authenticated, return him/her. Otherwise, sod off.

            if (authenticatedUser != null)
            {
                return(authenticatedUser);
            }

            throw new UnauthorizedAccessException();
        }
Example #18
0
        private static void OnNoon()
        {
            BotLog.Write(0, "MainCycle", "Noon entry");

            try
            {
                if (!PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                {
                    // PPSE is still running PW4 code for this, so don't run for PPSE

                    Payroll.ProcessMonthly(); // will only actually run on the 1st, but no harm in testing every noon
                }


                if (!testMode)
                {
                    /*TestTrace("Running RosterHousekeeping.RemindAllExpiries()...");
                     * RosterHousekeeping.RemindAllExpiries();
                     * TestTrace(" done.\r\n");*/
                }
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }

            try
            {
                if (!testMode)
                {
                    /*TestTrace("Running SupportDatabase.NotifyBouncingEmails()...");
                     * SupportDatabase.NotifyBouncingEmails();
                     * TestTrace(" done.\r\n");*/
                }
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }

            try
            {
                /*TestTrace("Running SupportDatabase.CloseDelayWarnings()...");
                 * SupportDatabase.CloseDelayWarnings();
                 * TestTrace(" done.\r\n");*/
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }

            try
            {
                /*TestTrace("Running SupportMailReview.Run()...");
                 * SupportMailReview.Run();
                 * TestTrace(" done.\r\n");*/
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }


            BotLog.Write(0, "MainCycle", "Noon exit");
        }
Example #19
0
        private void AddBitcoinChecks(Authority authority)
        {
            // Does this person have a bitcoin address set in an org with bitcoin hotwallets?

            if (string.IsNullOrEmpty(authority.Person.BitcoinPayoutAddress))
            {
                if (authority.Organization.FinancialAccounts.AssetsBitcoinHot != null && authority.Organization.Identity != Organization.SandboxIdentity && !PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
                {
                    DashboardTodo todo = new DashboardTodo();
                    todo.Description = Logic_Swarm_DashboardTodos.Bitcoin_SetPayoutAddress;

                    todo.Icon       = "/Images/Icons/bitcoin-icon-256px.png";
                    todo.JavaScript = "alertify.prompt(decodeURIComponent('" +
                                      Uri.EscapeDataString(
                        Logic_Swarm_DashboardTodos.Bitcoin_SetPayoutAddress_Prompt.Replace(
                            "[InstallationName]", SystemSettings.InstallationName)) +
                                      "' + '<br/><br/>'), function(okPressed, enteredData) { " +
                                      " if (okPressed) { " +
                                      "SwarmopsJS.ajaxCall('/Automation/FinancialFunctions.aspx/SetBitcoinPayoutAddress', { bitcoinAddress: enteredData }, function (result) { " +
                                      "if (result.Success) { alertify.log('Payout address set.'); $('div#divDashboardTodo').fadeOut(); } else { alertify.alert('Could not set payout address: ' + result.DisplayMessage); } " +
                                      "} ); " +
                                      " }}); return false;";

                    Add(todo);
                }
            }
        }
Example #20
0
        public void LoadData(string data, Organization organization)
        {
            List <ExternalBankDataRecord> recordList = new List <ExternalBankDataRecord>();

            if (Profile == null)
            {
                throw new InvalidOperationException("Cannot call LoadData before a profile has been set");
            }

            if (Profile.BankDataAccountReader != StockBankDataReaders.TabSeparatedValuesAccountReader)
            {
                throw new NotImplementedException("Only tab separated values are supported at this point");
            }

            // TODO: Implement bank data reader factory here

            string organizationCurrencyCode = organization.Currency.Code;


            // Replace any strings initially to force the bank data into readability (per profile)

            if (!String.IsNullOrEmpty(Profile.InitialReplacements))
            {
                string[] replacements = Profile.InitialReplacements.Split('|');

                for (int loop = 0; loop < replacements.Length / 2; loop++)
                {
                    data = data.Replace(replacements[loop * 2], replacements[loop * 2 + 1]);
                }
            }

            int crlfIndex;

            for (int loop = 0; loop < Profile.IgnoreInitialLines && !String.IsNullOrEmpty(data); loop++)
            {
                crlfIndex = data.IndexOfAny(new[] { '\n', '\r' });
                if (crlfIndex > 0)
                {
                    data = data.Substring(crlfIndex).Trim();
                }
                else
                {
                    data = string.Empty;
                }
            }

            crlfIndex = data.IndexOfAny(new[] { '\n', '\r' });

            string fieldKeyLine = data.Substring(0, crlfIndex);

            string[] dataKeyFields = fieldKeyLine.Split('\t');

            Dictionary <ExternalBankDataFieldName, int> fieldNameLookup =
                new Dictionary <ExternalBankDataFieldName, int>();

            // below is an N^2 loop but doesn't matter in such a small context

            foreach (ExternalBankDataFieldName fieldName in Profile.FieldNames.Keys)
            {
                for (int index = 0; index < dataKeyFields.Length; index++)
                {
                    if (StripQuotes(dataKeyFields[index]).Trim() == Profile.FieldNames[fieldName])
                    {
                        fieldNameLookup[fieldName] = index;
                        break;
                    }
                }

                if (!fieldNameLookup.ContainsKey(fieldName))  // wasn't found
                {
                    throw new InvalidOperationException("Field key \"" + fieldName +
                                                        "\" was not supplied or found in data file");
                }
            }


            data = data.Substring(crlfIndex).Trim();

            string[] lines = data.Split(new[] { '\r', '\n' });

            foreach (string lineData in lines)
            {
                string line = lineData.Trim();

                if (line.Length < 1)
                {
                    continue; // empty lines may exist due to split on either CR or LF
                }

                string[] lineFields = line.Split('\t');

                // If wrong currency, ignore

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Currency))
                {
                    string currency = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Currency]]);

                    if (currency != organizationCurrencyCode)
                    {
                        continue; // ignore this record
                    }
                }

                ExternalBankDataRecord newRecord = new ExternalBankDataRecord();

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.DescriptionPrimary))
                {
                    newRecord.Description =
                        StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.DescriptionPrimary]]);
                }

                // If primary description is empty, try to apply a secondary description

                if (String.IsNullOrEmpty(newRecord.Description))
                {
                    if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.DescriptionSecondary))
                    {
                        newRecord.Description =
                            StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.DescriptionSecondary]]);
                    }
                }

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.AccountBalance))
                {
                    // Dividing up to step-by-step statements instead of one long statement assists debugging
                    // of culture and other error sources

                    string balanceString =
                        StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.AccountBalance]]);
                    try
                    {
                        newRecord.AccountBalanceCents = ParseAmountString(balanceString);
                    }
                    catch (Exception innerException)
                    {
                        throw new FormatException("Couldn't parse account balance string - \"" + balanceString + "\"",
                                                  innerException);
                    }
                }

                if (!fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Date) &&
                    !fieldNameLookup.ContainsKey(ExternalBankDataFieldName.DateTime))
                {
                    throw new InvalidOperationException("Cannot parse transactions file without at least a date field");
                }

                DateTime dateTime = Constants.DateTimeLow;

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Date))
                {
                    string dateString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Date]]);
                    dateTime = DateTime.Parse(dateString, new CultureInfo(Profile.Culture));

                    if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.Time))
                    {
                        string   timeString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.Time]]);
                        TimeSpan timeOfDay  = TimeSpan.Parse(timeString);

                        dateTime += timeOfDay;
                    }
                    else
                    {
                        // move transaction to like mid-day of the organization's time zone. For now, all orgs are in Europe, so add 12 hours
                        // this is a HACK HACK HACK

                        dateTime = dateTime.AddHours(12);
                    }
                }
                else // no Date field, so by earlier logic, must have a DateTime field
                {
                    dateTime =
                        DateTime.Parse(StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.DateTime]]),
                                       new CultureInfo(Profile.Culture));
                }

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TimeZone))
                {
                    // Valid time zone formats are "XXX+hh:mm". The XXX are ignored.

                    // Throws exception if this doesn't parse, which is what we want

                    string timeZoneString = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TimeZone]]);
                    timeZoneString = timeZoneString.Substring(timeZoneString.Length - 6);
                    TimeSpan timeZone = TimeSpan.Parse(timeZoneString);

                    dateTime -= timeZone;
                    // minus, to bring the time to UTC. If time 13:00 is in tz +01:00, the UTC time is 12:00

                    // Then move from UTC to local time, to match various bookkeeping laws. TODO: local time per organization, perhaps?

                    dateTime = dateTime.ToLocalTime();
                }

                // PILOT SPECIAL CASE: if Paypal and PPSE Pilot program, ignore everything before 2014

                if (dateTime.Year < 2014 && organization.Identity == 1 &&
                    fieldNameLookup.ContainsKey(ExternalBankDataFieldName.UniqueId) &&
                    PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                {
                    continue; // Do not import PayPal records from before 2013
                }

                newRecord.DateTime = dateTime;

                if (!fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TransactionNet))
                {
                    throw new ArgumentException("There must be a transaction amount field in the bank data profile");
                }

                string amountNetString =
                    StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionNet]]);

                newRecord.TransactionNetCents = ParseAmountString(amountNetString);

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TransactionGross))
                {
                    string amountGrossString =
                        StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionGross]]);
                    newRecord.TransactionGrossCents = ParseAmountString(amountGrossString);

                    if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.TransactionFee))
                    {
                        string amountFeeString =
                            StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.TransactionFee]]);
                        newRecord.FeeCents = ParseAmountString(amountFeeString);

                        if (Profile.FeeSignage == FeeSignage.Positive)
                        {
                            newRecord.FeeCents = -newRecord.FeeCents;
                        }
                    }
                }
                else
                {
                    newRecord.TransactionGrossCents = newRecord.TransactionNetCents;
                    // if no "Gross" field, copy from net
                }

                // Check for consistency of gross/net/fee:

                if (newRecord.TransactionNetCents != newRecord.TransactionGrossCents + newRecord.FeeCents)
                {
                    throw new InvalidDataException(
                              "For a record, the net transaction amount does not match the gross less the fee.");
                }

                if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.UniqueId))
                {
                    newRecord.UniqueId = StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.UniqueId]]);
                }
                else if (fieldNameLookup.ContainsKey(ExternalBankDataFieldName.NotUniqueId))
                {
                    newRecord.NotUniqueId =
                        StripQuotes(lineFields[fieldNameLookup[ExternalBankDataFieldName.NotUniqueId]]);
                }

                recordList.Add(newRecord);
            }

            if (Profile.LatestTransactionLocation == LatestTransactionLocation.Top)
            {
                this.LatestAccountBalanceCents = recordList[0].AccountBalanceCents;
            }
            else if (Profile.LatestTransactionLocation == LatestTransactionLocation.Bottom)
            {
                this.LatestAccountBalanceCents = recordList[recordList.Count - 1].AccountBalanceCents;
            }
            else
            {
                throw new ArgumentException("LatestTransactionLocation is undefined");
            }

            recordList.Sort(new ExternalBankDataRecord());

            Records = recordList.ToArray();
        }
Example #21
0
        private static void OnNoon()
        {
            BotLog.Write(0, "MainCycle", "Noon entry");

            try
            {
                if (!PilotInstallationIds.IsPilot(PilotInstallationIds.PiratePartySE))
                {
                    // PPSE is still running PW4 code for this, so don't run for PPSE

                    Payroll.ProcessMonthly(); // will only actually run on the 1st, but no harm in testing every noon
                }

                // Check all bitcoin accounts for previously-unseen transactions once a day

                Organizations allOrganizations = Organizations.GetAll();
                foreach (Organization organization in allOrganizations)
                {
                    // this actually checks hot storage too, but that's supposed
                    // to be up to date since we're the ones handling it
                    BitcoinUtility.CheckColdStorageForOrganization(organization);
                }

                if (!testMode)
                {
                    /*TestTrace("Running RosterHousekeeping.RemindAllExpiries()...");
                     * RosterHousekeeping.RemindAllExpiries();
                     * TestTrace(" done.\r\n");*/
                }
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }

            try
            {
                if (!testMode)
                {
                    /*TestTrace("Running SupportDatabase.NotifyBouncingEmails()...");
                     * SupportDatabase.NotifyBouncingEmails();
                     * TestTrace(" done.\r\n");*/
                }
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }

            try
            {
                /*TestTrace("Running SupportDatabase.CloseDelayWarnings()...");
                 * SupportDatabase.CloseDelayWarnings();
                 * TestTrace(" done.\r\n");*/
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }

            try
            {
                /*TestTrace("Running SupportMailReview.Run()...");
                 * SupportMailReview.Run();
                 * TestTrace(" done.\r\n");*/
            }
            catch (Exception e)
            {
                TraceAndReport(e);
            }


            BotLog.Write(0, "MainCycle", "Noon exit");
        }
Example #22
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Check if this is the first run ever. If so, redirect to Init.

            if (!SupportFunctions.DatabaseConfigured)
            {
                // ReSharper disable once Html.PathError   <-- this line is required for Resharper to not flag the next line as invalid
                Response.Redirect("/Initialize", true);
                return;
            }

            // Persistence.Key["Debug_RawData"] = Request.ToRaw();

            // Check for POST data - for BitId via Webform

            if (Request.HttpMethod == "POST")
            {
                // We should ONLY get here if we're getting a BitId by Webform submission.

                // Persistence.Key["BitId_RawData"] = Request.ToRaw();

                if (Request.Params["address"] != null)
                {
                    // yes, indeed looks like it

                    BitIdCredentials credentials = new BitIdCredentials
                    {
                        address   = Request.Params["address"],
                        uri       = Request.Params["uri"],
                        signature = Request.Params["signature"]
                    };

                    ProcessRespondBitId(credentials, Response);
                    return;
                }
                if (Request.ContentType == "application/json")
                {
                    BitIdCredentials credentials =
                        new JavaScriptSerializer().Deserialize <BitIdCredentials> (
                            new StreamReader(Request.InputStream).ReadToEnd());
                    // TODO: untested but seems to work. Throws?

                    ProcessRespondBitId(credentials, Response);
                    return;
                }
            }

            string requestHost = Request.Url.Host;

            // If this is the Dev Sandbox, autologin

            if ((requestHost == "sandbox.swarmops.com" || requestHost == "dev.swarmops.com") &&
                PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox) &&
                Request.QueryString["SuppressAutologin"] != "true")
            {
                DashboardMessage.Set("<p>You have been logged on as <strong>Sandbox Administrator</strong> to the Swarmops Development Sandbox.</p><br/><p>This machine runs the latest development build, so you may run into diagnostic code and half-finished features. All data here is bogus test data and is reset every night.</p><br/><p><strong>In other words, welcome, and play away!</strong></p>");
                FormsAuthentication.SetAuthCookie(Authority.FromLogin(Person.FromIdentity(1), Organization.Sandbox).ToEncryptedXml(), true);
                Response.Redirect(HttpContext.Current.Request ["ReturnUrl"]);   // Returns to the requested URL with auth cookie set
            }

            // If we're on an Open Ledgers domain, autologin as Open Ledgers

            Organization organizationOpenLedgers = Organization.FromOpenLedgersDomain(requestHost); // returns null if doesn't exist

            if (organizationOpenLedgers != null)
            {
                DashboardMessage.Set(String.Format(Resources.Pages.Security.Login_AsOpenLedgers, organizationOpenLedgers.Name));
                FormsAuthentication.SetAuthCookie(Authority.FromLogin(Person.FromIdentity(Person.OpenLedgersIdentity), organizationOpenLedgers).ToEncryptedXml(), true);
                if (HttpContext.Current.Request["ReturnUrl"] == "/")
                {
                    Response.Redirect(@"/Ledgers/Balance");
                }
                else
                {
                    Response.Redirect(HttpContext.Current.Request["ReturnUrl"]);  // Returns to the requested URL with auth cookie set
                }
            }

            // Check for SSL and force it

            // Special case for CloudFlare deployments - there is a case where somebody will get their connections de-SSLed at the server

            string cloudFlareVisitorScheme = Request.Headers["CF-Visitor"];
            bool   cloudFlareSsl           = false;

            if (!string.IsNullOrEmpty(cloudFlareVisitorScheme))
            {
                if (cloudFlareVisitorScheme.Contains("\"scheme\":\"https\""))
                {
                    cloudFlareSsl = true;
                }
            }

            // TODO: Same thing for Pound/HAProxy deployments

            // Rewrite if applicable

            if (Request.Url.ToString().StartsWith("http://") && !cloudFlareSsl)
            // only check client-side as many server sites de-SSL the connection before reaching the web server
            {
                if (!Request.Url.ToString().StartsWith("http://dev.swarmops.com/") &&
                    !(Request.Url.ToString().StartsWith("http://*****:*****@"//" + vanityOrganization.VanityDomain + @"/Signup";
                // this.LabelSelfSignup.Text = String.Format (Resources.Pages.Security.Login_SelfSignup, vanityOrganization.Name);
                // this.LabelSelfSignupHeader.Text = Resources.Pages.Security.Login_SelfSignupHeader;
                // this.PanelJoin.Visible = true;
            }


            // If we're debugging, enable the auto- / impersonation login. This MUST NEVER fire outside of development environment.

            if (Debugger.IsAttached && Path.DirectorySeparatorChar == '\\')
            // on Windows, with a debugger attached, so this is not a production environment
            {
                // but check that we're running against Localhost as well

                if (Request.Url.ToString().StartsWith("http://localhost:"))
                {
                    this.PanelCheat.Visible = true;
                }
            }


            // this.ImageCultureIndicator.Style[HtmlTextWriterStyle.MarginTop] = "-3px";
            // this.ImageCultureIndicator.Style[HtmlTextWriterStyle.MarginRight] = "3px";
            // this.ImageCultureIndicator.Style[HtmlTextWriterStyle.Cursor] = "pointer";

            _cacheVersionMark = Logic.Support.Formatting.SwarmopsVersion;
            if (_cacheVersionMark.StartsWith("Debug"))
            {
                _cacheVersionMark = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.ffff");
            }
            _cacheVersionMark = SHA1.Hash(_cacheVersionMark).Replace(" ", "").Substring(0, 8);

            Localize();

            // Generate BitID tokens

            Guid   guid       = Guid.NewGuid();
            string guidString = guid.ToString().Replace("-", "");

            string nonce = guidString + DateTime.UtcNow.Ticks.ToString("x8");

            string hostName = Request.Url.Host;

            string bitIdUri = "bitid://" + hostName + "/Security/Login.aspx/BitIdLogin?x=" + nonce;

            /*   -- commented out: NEVER permit BitId over non-SSL
             * if (Request.Url.ToString().StartsWith ("http://") && !cloudFlareSsl)
             * {
             *  bitIdUri += "&u=1";
             * }*/

            this.LiteralUri.Text   = HttpUtility.UrlEncode(bitIdUri);
            this.LiteralNonce.Text = nonce;

            GuidCache.Set(bitIdUri + "-Logon", "Unauth");

            // TODO: need to NOT USE GOOGLE CHARTS for this but bring home a free QR package

            this.ImageBitIdQr.ImageUrl =
                "https://chart.googleapis.com/chart?cht=qr&chs=400x400&chl=" + HttpUtility.UrlEncode(bitIdUri);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string externalScriptUrl = "//hostedscripts.falkvinge.net";

            string testFolderName = Server.MapPath("~/Scripts/ExternalScripts");

            if (Directory.Exists(testFolderName))
            {
                externalScriptUrl = "/Scripts/ExternalScripts";
            }
            else if (Debugger.IsAttached ||
                     PilotInstallationIds.IsPilot(PilotInstallationIds.DevelopmentSandbox))
            {
                externalScriptUrl += "/staging";
                // use staging area for new script versions on Sandbox and for all debugging
            }

            // If we're debugging a seriously experimental new version of JEasyUI, look for it in /Scripts/Experimental
            // (a folder which doesn't commit to the github repo)

            if (File.Exists(Server.MapPath("~/Scripts/Experimental/easyui/jquery.easyui.min.js")))
            {
                externalScriptUrl = "/Scripts/Experimental";
            }

            if (Package == "easyui")
            {
                StringBuilder scriptRef = new StringBuilder();

                scriptRef.Append("<script src=\"" + externalScriptUrl +
                                 "/easyui/jquery.easyui.min.js\" type=\"text/javascript\"></script>\r\n");
                scriptRef.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + externalScriptUrl +
                                 "/easyui/themes/icon.css\" />\r\n");
                scriptRef.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + externalScriptUrl +
                                 "/easyui/themes/default/easyui.css\" />\r\n");   // Supposed to contain all CSS

                if (Thread.CurrentThread.CurrentCulture.TextInfo.IsRightToLeft)
                {
                    scriptRef.Append("<script src=\"" + externalScriptUrl +
                                     "/easyui/extensions/easyui-rtl.js\" type=\"text/javascript\"></script>\r\n");
                    scriptRef.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + externalScriptUrl +
                                     "/easyui/extensions/easyui-rtl.css\" />\r\n");
                }

                /* -- with the inclusion of the catchall CSS file, this code _should_ no longer be necessary...
                 * string[] controlNames = Controls.Split(',');
                 * foreach (string controlName in controlNames)
                 * {
                 *  string controlNameLower = controlName.Trim().ToLowerInvariant();
                 *  if (controlNameLower != "unknown")
                 *  {
                 *      scriptRef.AppendFormat (
                 *          "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + externalScriptUrl +
                 *          "/easyui/themes/default/{0}.css\" />\r\n",
                 *          controlNameLower);
                 *  }
                 * }*/

                this.LiteralReference.Text = scriptRef.ToString();
            }
        }