Exemple #1
0
        private FrontPorchUser GetFrontPorchUser(PersonalDevice device)
        {
            var url = string.Format("https://{0}/api/user/get?fpid={1}", fpHost, device.PersonAliasId);

            HttpWebRequest request = ( HttpWebRequest )WebRequest.Create(url);

            request.Headers.Add(fpAuthenticationHeader);
            try
            {
                HttpWebResponse response  = ( HttpWebResponse )request.GetResponse();
                Stream          resStream = response.GetResponseStream();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        var objText             = reader.ReadToEnd();
                        var obj = ( FrontPorchUser )js.Deserialize(objText, typeof(FrontPorchUser));
                        obj.userId = device.PersonAliasId.Value;
                        return(obj);
                    }
                }
            }
            catch (Exception e)
            {
                LogException(e);
                return(null);
            }
            return(null);
        }
Exemple #2
0
        public Dictionary <string, string> RegisterFCM()
        {
            HttpContent requestContent = Request.Content;
            string      content        = requestContent.ReadAsStringAsync().Result;
            Dictionary <string, string> tokenDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(content);
            var person = GetPerson();

            if (tokenDictionary.ContainsKey("Token") &&
                !string.IsNullOrWhiteSpace(tokenDictionary["Token"]) &&
                person != null)
            {
                var userAgent = Request.Headers.UserAgent.ToString();
                var deviceId  = Regex.Match(userAgent, "(?<=-).+(?=\\))").Value.Trim();
                if (deviceId.Length > 20)
                {
                    deviceId = deviceId.Substring(0, 20);
                }
                RockContext    rockContext    = new RockContext();
                PersonalDevice personalDevice = AvalancheUtilities.GetPersonalDevice(deviceId, person.PrimaryAliasId, rockContext);
                if (personalDevice != null && personalDevice.DeviceRegistrationId != tokenDictionary["Token"])
                {
                    personalDevice.DeviceRegistrationId = tokenDictionary["Token"];
                    personalDevice.NotificationsEnabled = true;
                    rockContext.SaveChanges();
                }
            }
            return(new Dictionary <string, string> {
                { "Status", "Ok" }
            });
        }
        private PersonalDevice GetPersonalDevice(string deviceId, RockContext rockContext)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                return(null);
            }

            PersonalDeviceService personalDeviceService = new PersonalDeviceService(rockContext);
            var device = personalDeviceService.Queryable().Where(d => d.DeviceUniqueIdentifier == deviceId).FirstOrDefault();

            if (device != null)
            {
                if (device.PersonAliasId == PersonAliasId)
                {
                    return(device);
                }
                device.PersonAliasId = PersonAliasId;
                rockContext.SaveChanges();
                return(device);
            }

            device = new PersonalDevice()
            {
                PersonAliasId             = PersonAliasId,
                DeviceUniqueIdentifier    = deviceId,
                PersonalDeviceTypeValueId = DefinedTypeCache.Read(Rock.SystemGuid.DefinedValue.PERSONAL_DEVICE_TYPE_MOBILE.AsGuid()).Id
            };
            personalDeviceService.Add(device);
            rockContext.SaveChanges();
            return(device);
        }
Exemple #4
0
 private void RemoveDeviceMAC(PersonalDevice device, RockContext rockContext)
 {
     device.LoadAttributes();
     //Archive the mac address
     device.SetAttributeValue("ArchivedMACAddress", device.MACAddress);
     device.MACAddress = "";
     device.SaveAttributeValues();
     rockContext.SaveChanges();
 }
Exemple #5
0
        private void EditDevice(int personalDeviceId)
        {
            var rockContext           = new RockContext();
            var personalDeviceService = new PersonalDeviceService(rockContext);
            var personalDevice        = personalDeviceService.Get(personalDeviceId);

            if (personalDevice == null)
            {
                personalDevice = new PersonalDevice();
                mdEdit.Title   = "Add Device";
                //default to the current context person
                ppPerson.SetValue(_person);
            }
            else
            {
                mdEdit.Title = "Edit Device";
                ppPerson.SetValue(personalDevice.PersonAlias.Person);
            }

            tbdeviceregistration.Text = personalDevice.DeviceRegistrationId;
            var notifications = personalDevice.NotificationsEnabled;

            if (notifications)
            {
                rblnotifications.SetValue("true");
            }
            else
            {
                rblnotifications.SetValue("false");
            }
            ddldevicetype.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSONAL_DEVICE_TYPE).Id;
            ddldevicetype.Items.Insert(0, new ListItem());
            ddldevicetype.SetValue(personalDevice.PersonalDeviceTypeValueId);
            ddlplatform.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSONAL_DEVICE_PLATFORM).Id;
            ddlplatform.Items.Insert(0, new ListItem());
            ddlplatform.SetValue(personalDevice.PlatformValueId);
            tbdeviceuniqueid.Text = personalDevice.DeviceUniqueIdentifier;
            tbdeviceversion.Text  = personalDevice.DeviceVersion;
            tbmaddress.Text       = personalDevice.MACAddress;
            hfDeviceId.SetValue(personalDeviceId);
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SecureNetworkSSID")))
            {
                var tmp = GetFrontPorchUser(personalDevice);
                if (tmp != null)
                {
                    cbSecureNetwork.Checked = tmp.secureNetworkSSID != null;
                }
            }
            else
            {
                cbSecureNetwork.Visible = false;
            }
            mdEdit.Show();
        }
Exemple #6
0
        protected void mdEdit_SaveClick(object sender, EventArgs e)
        {
            var rockContext           = new RockContext();
            var personalDeviceService = new PersonalDeviceService(rockContext);
            var personAliasService    = new PersonAliasService(rockContext);
            var personalDevice        = personalDeviceService.Get(hfDeviceId.ValueAsInt());

            if (personalDevice == null)
            {
                personalDevice = new PersonalDevice
                {
                    Guid = Guid.NewGuid()
                };
                personalDeviceService.Add(personalDevice);
            }

            personalDevice.PersonAliasId = ppPerson.PersonAliasId;

            personalDevice.NotificationsEnabled = rblnotifications.SelectedValue.AsBoolean();

            personalDevice.PersonalDeviceTypeValueId = ddldevicetype.SelectedValueAsInt();
            personalDevice.PlatformValueId           = ddlplatform.SelectedValueAsInt();
            personalDevice.DeviceUniqueIdentifier    = tbdeviceuniqueid.Text;
            personalDevice.DeviceVersion             = tbdeviceversion.Text;

            var previousMACAddress = personalDevice.MACAddress != null?personalDevice.MACAddress.ToLower() : "";

            personalDevice.MACAddress = tbmaddress.Text.RemoveAllNonAlphaNumericCharacters().ToLower();

            ModifyFrontPorchUser(personAliasService.Get(personalDevice.PersonAliasId ?? ppPerson.PersonAliasId.Value));
            AddDeviceToFP(personalDevice.MACAddress);

            // Archive any mac addresses that match for other devices
            if (personalDevice.MACAddress != previousMACAddress)
            {
                var personalDevices = personalDeviceService
                                      .Queryable()
                                      .Where(d => d.MACAddress == personalDevice.MACAddress)
                                      .ToList();

                foreach (var device in personalDevices)
                {
                    RemoveDeviceMAC(device, rockContext);
                }
                RemoveDeviceFromFP(previousMACAddress);   //Remove the previous device from FP
            }

            rockContext.SaveChanges();

            mdEdit.Hide();
            BindRepeater();
        }
        public void deleteDevice(PersonalDevice personalDevice, RockContext rockContext)
        {
            // Check to see if a mac address exists, if so, delete from front Porch

            string macAddress = personalDevice.MACAddress;

            if (macAddress != null)
            {
                var authToken      = GlobalAttributesCache.Value("APIAuthorizationToken");
                var hostAddr       = GlobalAttributesCache.Value("Host");
                var authentication = string.Format("authorization-token:{0}", authToken);
                var url            = string.Format("https://{0}/api/user/delete?mac={1}", hostAddr, macAddress);
                if (authToken.IsNotNullOrWhiteSpace() && hostAddr.IsNotNullOrWhiteSpace())
                {
                    HttpWebRequest request = ( HttpWebRequest )WebRequest.Create(url);

                    try
                    {
                        HttpWebResponse response = ( HttpWebResponse )request.GetResponse();

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            devicesProcessed++;
                            personalDevice.ModifiedDateTime = RockDateTime.Now;
                            if (personalDevice.MACAddress != null)
                            {
                                personalDevice.LoadAttributes();
                                if (personalDevice.Attributes.ContainsKey("ArchivedMACAddress"))
                                {
                                    personalDevice.SetAttributeValue("ArchivedMACAddress", personalDevice.MACAddress);
                                }
                                personalDevice.MACAddress = null;
                                personalDevice.SaveAttributeValues(rockContext);
                                rockContext.SaveChanges();
                            }
                        }
                        else
                        {
                            deviceErrors++;
                            _processingErrors.Add(string.Format("{0}", macAddress));
                        }
                    }
                    catch (Exception ex)
                    {
                        string deviceDetails = string.Format("{0}", macAddress);
                        _exceptionMsgs.Add(deviceDetails + ": " + ex.Message);
                        //throw new Exception( "Exception occurred processing workflow: " + deviceDetails, ex );
                    }
                }
            }
        }
        private void RemoveDeviceFromFrontPorch(PersonalDevice device, List <string> errors)
        {
            var            url     = string.Format("https://{0}/api/user/delete?mac={1}", host, device.MACAddress);
            HttpWebRequest request = ( HttpWebRequest )WebRequest.Create(url);

            request.Headers.Add(authentication);
            try
            {
                HttpWebResponse response = ( HttpWebResponse )request.GetResponse();
            }
            catch (Exception e)
            {
                ExceptionLogService.LogException(e);
                errors.Add(e.Message);
            }
        }
        private void RedirectToUrl(string url)
        {
            var    mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson);
            string resolvedUrl = url.ResolveMergeFields(mergeFields);

            // create or get device
            if (hfMacAddress.Value.IsNotNullOrWhiteSpace())
            {
                string macAddress = hfMacAddress.Value;
                PersonalDeviceService personalDeviceService = new PersonalDeviceService(new RockContext());
                PersonalDevice        personalDevice        = null;

                bool isAnExistingDevice = DoesPersonalDeviceExist(macAddress);
                if (isAnExistingDevice)
                {
                    personalDevice = VerifyDeviceInfo(macAddress);
                }
                else
                {
                    personalDevice = CreateDevice(macAddress);
                    CreateDeviceCookie(macAddress);
                }

                // Time to link this device to the person.
                if (personalDevice.PersonAliasId != CurrentPersonAliasId && CurrentPersonAliasId.HasValue)
                {
                    RockPage.LinkPersonAliasToDevice(CurrentPersonAliasId.Value, macAddress);
                }

                // Create/Modify the user in Front Porch
                if (CurrentPersonAliasId.HasValue)
                {
                    ModifyFrontPorchUser(CurrentPersonAliasId.Value);
                }
            }

            if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
            {
                nbAlert.Text = string.Format("If you did not have Administrate permissions on this block, you would have been redirected to here: <a href='{0}'>{0}</a>.", Page.ResolveUrl(resolvedUrl));
            }
            else
            {
                Response.Redirect(resolvedUrl, false);
                Context.ApplicationInstance.CompleteRequest();
                return;
            }
        }
Exemple #10
0
        /// <summary>
        /// Gets the current device platform info and updates the obj if needed.
        /// </summary>
        /// <param name="personalDevice">The personal device.</param>
        private PersonalDevice VerifyDeviceInfo(string macAddress)
        {
            UAParser.ClientInfo client = UAParser.Parser.GetDefault().Parse(Request.UserAgent);

            RockContext           rockContext           = new RockContext();
            PersonalDeviceService personalDeviceService = new PersonalDeviceService(rockContext);

            PersonalDevice personalDevice = personalDeviceService.GetByMACAddress(macAddress);

            personalDevice.PersonalDeviceTypeValueId = GetDeviceTypeValueId();
            personalDevice.PlatformValueId           = GetDevicePlatformValueId(client);
            personalDevice.DeviceVersion             = GetDeviceOsVersion(client);

            rockContext.SaveChanges();

            return(personalDevice);
        }
        private void EditDevice(int personalDeviceId)
        {
            var rockContext           = new RockContext();
            var personalDeviceService = new PersonalDeviceService(rockContext);
            var personalDevice        = personalDeviceService.Get(personalDeviceId);

            if (personalDevice == null)
            {
                personalDevice = new PersonalDevice();
                mdEdit.Title   = "Add Device";
                //default to the current context person
                ppPerson.SetValue(_person);
            }
            else
            {
                mdEdit.Title = "Edit Device";
                ppPerson.SetValue(personalDevice.PersonAlias.Person);
            }

            tbdeviceregistration.Text = personalDevice.DeviceRegistrationId;
            var notifications = personalDevice.NotificationsEnabled;

            if (notifications)
            {
                rblnotifications.SetValue("true");
            }
            else
            {
                rblnotifications.SetValue("false");
            }

            ddldevicetype.BindToDefinedType(DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSONAL_DEVICE_TYPE), true);
            ddldevicetype.SetValue(personalDevice.PersonalDeviceTypeValueId);
            ddlplatform.BindToDefinedType(DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.PERSONAL_DEVICE_PLATFORM), true);
            ddlplatform.SetValue(personalDevice.PlatformValueId);
            tbdeviceuniqueid.Text = personalDevice.DeviceUniqueIdentifier;
            tbdeviceversion.Text  = personalDevice.DeviceVersion;
            tbmaddress.Text       = personalDevice.MACAddress;
            hfDeviceId.SetValue(personalDeviceId);
            mdEdit.Show();
        }
        protected void mdEdit_SaveClick(object sender, EventArgs e)
        {
            var rockContext           = new RockContext();
            var personalDeviceService = new PersonalDeviceService(rockContext);
            var personalDevice        = personalDeviceService.Get(hfDeviceId.ValueAsInt());

            if (personalDevice == null)
            {
                personalDevice = new PersonalDevice
                {
                    Guid = Guid.NewGuid()
                };
                personalDeviceService.Add(personalDevice);
            }

            personalDevice.PersonAliasId = ppPerson.PersonAliasId;

            personalDevice.NotificationsEnabled = rblnotifications.SelectedValue.AsBoolean();

            personalDevice.PersonalDeviceTypeValueId = ddldevicetype.SelectedValueAsInt();
            personalDevice.PlatformValueId           = ddlplatform.SelectedValueAsInt();
            personalDevice.DeviceUniqueIdentifier    = tbdeviceuniqueid.Text;
            personalDevice.DeviceVersion             = tbdeviceversion.Text;

            var previousMACAddress = personalDevice.MACAddress != null?personalDevice.MACAddress.ToLower() : "";

            personalDevice.MACAddress = tbmaddress.Text.RemoveAllNonAlphaNumericCharacters().ToLower();

            if (personalDevice.MACAddress != previousMACAddress)
            {
                UpdateMAC(personalDevice.MACAddress, previousMACAddress);
            }

            rockContext.SaveChanges();
            mdEdit.Hide();
            BindRepeater();
        }
Exemple #13
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            nbAlert.Visible = false;

            // Go through the UA ignore list and don't load anything we don't care about or want.
            foreach (string userAgentToIgnore in _userAgentsToIgnore)
            {
                if (Request.UserAgent == null || Request.UserAgent.StartsWith(userAgentToIgnore))
                {
                    return;
                }
            }

            if (!IsPostBack)
            {
                string macAddress = RockPage.PageParameter(GetAttributeValue("MacAddressParam"));
                if (string.IsNullOrWhiteSpace(macAddress) || !macAddress.IsValidMacAddress())
                {
                    nbAlert.Text    = "Missing or invalid MAC Address";
                    nbAlert.Visible = true;
                    ShowControls(false);
                    return;
                }

                string releaseLink = GetAttributeValue("ReleaseLink");
                if (string.IsNullOrWhiteSpace(releaseLink) || !releaseLink.IsValidUrl())
                {
                    nbAlert.Text    = "Missing or invalid Release Link";
                    nbAlert.Visible = true;
                    ShowControls(false);
                    return;
                }

                // Save the supplied MAC address to the page removing any non-Alphanumeric characters
                macAddress         = macAddress.RemoveAllNonAlphaNumericCharacters();
                hfMacAddress.Value = macAddress;

                // create or get device
                PersonalDeviceService personalDeviceService = new PersonalDeviceService(new RockContext());
                PersonalDevice        personalDevice        = null;

                if (DoesPersonalDeviceExist(macAddress))
                {
                    personalDevice = VerifyDeviceInfo(macAddress);
                }
                else
                {
                    personalDevice = CreateDevice(macAddress);
                }

                // We are going to create this everytime they hit the captive portal page. Otherwise if the device is saved but not linked to an actual user (not the fake one created here),
                // and then deleted by the user/browser/software, then they'll never get the cookie again and won't automatically get linked by RockPage.
                CreateDeviceCookie(macAddress);

                // See if user is logged in and link the alias to the device.
                if (CurrentPerson != null)
                {
                    Prefill(CurrentPerson);
                    RockPage.LinkPersonAliasToDevice(( int )CurrentPersonAliasId, macAddress);
                }

                // Direct connect if no controls are visible
                if (!ShowControls())
                {
                    // Nothing to show means nothing to enter. Redirect user back to FP with the primary alias ID and query string
                    if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
                    {
                        nbAlert.Text = string.Format("If you did not have Administrative permissions on this block you would have been redirected to: <a href='{0}'>{0}</a>.", CreateRedirectUrl(null));
                    }
                    else
                    {
                        Response.Redirect(CreateRedirectUrl(null));
                        return;
                    }
                }
            }
        }
Exemple #14
0
        public IHttpActionResult GetLaunchPacket(string deviceIdentifier = null)
        {
            var site = MobileHelper.GetCurrentApplicationSite();
            var additionalSettings = site?.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>();
            var rockContext        = new Rock.Data.RockContext();
            var person             = GetPerson(rockContext);
            var deviceData         = Request.GetHeader("X-Rock-DeviceData").FromJsonOrNull <DeviceData>();

            if (additionalSettings == null || !additionalSettings.LastDeploymentDate.HasValue)
            {
                return(NotFound());
            }

            var launchPacket = new LaunchPacket
            {
                LatestVersionId     = ( int )(additionalSettings.LastDeploymentDate.Value.ToJavascriptMilliseconds() / 1000),
                IsSiteAdministrator = site.IsAuthorized(Authorization.EDIT, person)
            };

            if (deviceData.DeviceType == DeviceType.Phone)
            {
                launchPacket.LatestVersionSettingsUrl = additionalSettings.PhoneUpdatePackageUrl;
            }
            else if (deviceData.DeviceType == DeviceType.Tablet)
            {
                launchPacket.LatestVersionSettingsUrl = additionalSettings.TabletUpdatePackageUrl;
            }
            else
            {
                return(NotFound());
            }

            if (person != null)
            {
                var principal = ControllerContext.Request.GetUserPrincipal();

                launchPacket.CurrentPerson           = MobileHelper.GetMobilePerson(person, site);
                launchPacket.CurrentPerson.AuthToken = MobileHelper.GetAuthenticationToken(principal.Identity.Name);
            }

            //
            // Get or create the personal device.
            //
            if (deviceIdentifier.IsNotNullOrWhiteSpace())
            {
                var mobileDeviceTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSONAL_DEVICE_TYPE_MOBILE).Id;
                var personalDeviceService   = new PersonalDeviceService(rockContext);
                var personalDevice          = personalDeviceService.Queryable()
                                              .AsNoTracking()
                                              .Where(a => a.DeviceUniqueIdentifier == deviceIdentifier && a.PersonalDeviceTypeValueId == mobileDeviceTypeValueId)
                                              .FirstOrDefault();

                if (personalDevice == null)
                {
                    personalDevice = new PersonalDevice
                    {
                        DeviceUniqueIdentifier    = deviceIdentifier,
                        PersonalDeviceTypeValueId = mobileDeviceTypeValueId,
                        PlatformValueId           = deviceData.DevicePlatform.GetDevicePlatformValueId(),
                        PersonAliasId             = person?.PrimaryAliasId,
                        NotificationsEnabled      = true
                    };

                    personalDeviceService.Add(personalDevice);
                    rockContext.SaveChanges();
                }

                launchPacket.PersonalDeviceGuid = personalDevice.Guid;
            }

            return(Ok(launchPacket));
        }
Exemple #15
0
        public PersonalDevice UpdateByMACAddress(string macAddress, string deviceIdentifier = "", string devicePlatform = "", string deviceVersion = "", int?personAliasId = null)
        {
            var rockContext = new Data.RockContext();
            var service     = new PersonalDeviceService(rockContext);

            // MAC address
            var personalDevice = service.GetByMACAddress(macAddress);

            if (personalDevice == null)
            {
                personalDevice            = new PersonalDevice();
                personalDevice.MACAddress = macAddress;
                service.Add(personalDevice);
            }

            // unique identifier
            if (deviceIdentifier.IsNotNullOrWhitespace())
            {
                personalDevice.DeviceUniqueIdentifier = deviceIdentifier;
            }

            // Platform
            if (devicePlatform.IsNotNullOrWhitespace())
            {
                var dt = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.PERSONAL_DEVICE_PLATFORM.AsGuid());
                DefinedValueCache dv = null;
                if (dt != null)
                {
                    dv = dt.DefinedValues.FirstOrDefault(v => v.Value == devicePlatform);
                }
                if (dv == null)
                {
                    dv = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSONAL_DEVICE_PLATFORM_OTHER.AsGuid());
                }
                personalDevice.PlatformValueId = dv != null ? dv.Id : (int?)null;
            }

            // Version
            if (deviceVersion.IsNotNullOrWhitespace())
            {
                personalDevice.DeviceVersion = deviceVersion;
            }

            // Person
            if (personAliasId.HasValue)
            {
                var person = new PersonAliasService(rockContext).GetPerson(personAliasId.Value);
                if (person != null)
                {
                    if (personalDevice.PersonAlias == null || personalDevice.PersonAlias.PersonId != person.Id)
                    {
                        personalDevice.PersonAliasId = personAliasId.Value;
                    }

                    // Update any associated interaction records for the device that do not have an associated person.
                    if (personalDevice.Id != 0)
                    {
                        var interactionService = new InteractionService(rockContext);
                        foreach (var interaction in interactionService.Queryable()
                                 .Where(i =>
                                        i.PersonalDeviceId == personalDevice.Id &&
                                        !i.PersonAliasId.HasValue))
                        {
                            interaction.PersonAliasId = personAliasId.Value;
                        }
                    }
                }
            }

            rockContext.SaveChanges();

            return(GetById(personalDevice.Id));
        }
Exemple #16
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            nbAlert.Visible = false;

            // Go through the UA ignore list and don't load anything we don't care about or want.
            foreach (string userAgentToIgnore in _userAgentsToIgnore)
            {
                if (Request.UserAgent.StartsWith(userAgentToIgnore))
                {
                    return;
                }
            }

            if (!IsPostBack)
            {
                string macAddress = RockPage.PageParameter(GetAttributeValue("MacAddressParam"));
                Regex  regex      = new Regex("^([0-9a-fA-F]{2}(?:[:-]?[0-9a-fA-F]{2}){5})$");
                if (string.IsNullOrWhiteSpace(macAddress) || !regex.IsMatch(macAddress))
                {
                    nbAlert.Text    = "Missing or invalid MAC Address";
                    nbAlert.Visible = true;
                    ShowControls(false);
                    return;
                }

                string releaseLink = GetAttributeValue("ReleaseLink");

                Uri     uriResult;
                Boolean validUrl = Uri.TryCreate(releaseLink, UriKind.Absolute, out uriResult) &&
                                   (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
                if (string.IsNullOrWhiteSpace(releaseLink) || !validUrl)
                {
                    nbAlert.Text    = "Missing or invalid Release Link";
                    nbAlert.Visible = true;
                    ShowControls(false);
                    return;
                }

                // Save the supplied MAC address to the page removing any non-Alphanumeric characters
                macAddress         = string.Concat(macAddress.Where(c => char.IsLetterOrDigit(c)));
                hfMacAddress.Value = macAddress;

                RockContext rockContext = new RockContext();

                // create or get device
                PersonalDeviceService personalDeviceService = new PersonalDeviceService(rockContext);
                PersonalDevice        personalDevice        = null;

                bool isAnExistingDevice = DoesPersonalDeviceExist(macAddress);
                if (isAnExistingDevice)
                {
                    personalDevice = VerifyDeviceInfo(macAddress);
                }
                else
                {
                    personalDevice = CreateDevice(macAddress);
                    CreateDeviceCookie(macAddress);
                }

                // See if user is logged and link the alias to the device.
                if (CurrentPerson != null)
                {
                    Prefill(CurrentPerson);
                    RockPage.LinkPersonAliasToDevice(( int )CurrentPersonAliasId, macAddress);
                    hfPersonAliasId.Value = CurrentPersonAliasId.ToString();
                }
                else if (isAnExistingDevice)
                {
                    // if the user is not logged in but we have the device lets try to get a person
                    if (personalDevice.PersonAliasId != null)
                    {
                        // Get the person
                        PersonService personService = new PersonService(rockContext);
                        Person        person        = personService.Get(personalDevice.PersonAlias.PersonId);

                        if (person != null)
                        {
                            Prefill(person);
                            RockPage.LinkPersonAliasToDevice(( int )personalDevice.PersonAliasId, macAddress);
                            hfPersonAliasId.Value = personalDevice.PersonAliasId.ToString();
                        }
                    }
                }

                // Direct connect if no controls are visible
                if (!ShowControls())
                {
                    // Nothing to show means nothing to enter. Redirect user back to FP with the primary alias ID and query string
                    if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
                    {
                        nbAlert.Text = string.Format("If you did not have Administrative permissions on this block you would have been redirected to: <a href='{0}'>{0}</a>.", CreateRedirectUrl(null));
                    }
                    else
                    {
                        Response.Redirect(CreateRedirectUrl(null));
                        return;
                    }
                }
            }
        }
Exemple #17
0
        public IHttpActionResult GetLaunchPacket()
        {
            // Read site Id from the request header
            var siteId = this.Request.GetHeader("X-Rock-App-Id").AsIntegerOrNull();

            // Get device data from the request header
            // Get device data
            var deviceData = JsonConvert.DeserializeObject <DeviceData>(this.Request.GetHeader("X-Rock-DeviceData"));

            if (deviceData == null)
            {
                StatusCode(HttpStatusCode.InternalServerError);
            }

            if (!siteId.HasValue)
            {
                return(NotFound());
            }

            var site = SiteCache.Get(siteId.Value);

            // If the site was not found then return 404
            if (site == null)
            {
                return(NotFound());
            }

            // Return the launch packet
            try
            {
                var rockContext = new RockContext();
                var person      = GetPerson(rockContext);

                var launchPacket = new AppleLaunchPacket();
                launchPacket.EnablePageViews = site.EnablePageViews;

                if (person != null)
                {
                    var principal = ControllerContext.Request.GetUserPrincipal();

                    launchPacket.CurrentPerson           = TvHelper.GetTvPerson(person);
                    launchPacket.CurrentPerson.AuthToken = TvHelper.GetAuthenticationTokenFromUsername(principal.Identity.Name);

                    UserLoginService.UpdateLastLogin(principal.Identity.Name);
                }

                // Get or create the personal device.
                var tvDeviceTypeValueId   = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSONAL_DEVICE_TYPE_TV).Id;
                var personalDeviceService = new PersonalDeviceService(rockContext);
                var personalDevice        = personalDeviceService.Queryable()
                                            .Where(a => a.DeviceUniqueIdentifier == deviceData.DeviceIdentifier && a.PersonalDeviceTypeValueId == tvDeviceTypeValueId && a.SiteId == site.Id)
                                            .FirstOrDefault();

                if (personalDevice == null)
                {
                    personalDevice = new PersonalDevice
                    {
                        DeviceUniqueIdentifier    = deviceData.DeviceIdentifier,
                        PersonalDeviceTypeValueId = tvDeviceTypeValueId,
                        SiteId               = site.Id,
                        PersonAliasId        = person?.PrimaryAliasId,
                        NotificationsEnabled = true,
                        Manufacturer         = deviceData.Manufacturer,
                        Model            = deviceData.Model,
                        Name             = deviceData.Name,
                        IsActive         = true,
                        LastSeenDateTime = RockDateTime.Now,
                        DeviceVersion    = deviceData.Version
                    };

                    personalDeviceService.Add(personalDevice);
                    rockContext.SaveChanges();
                }
                else
                {
                    // A change is determined as one of the following:
                    // 1) A change in Name, Manufacturer, Model, or NotificationsEnabled.
                    // 2) Device not being active.
                    // 3) Not seen in 24 hours.
                    // 4) Signed in with a different person.
                    var hasDeviceChanged = !personalDevice.IsActive ||
                                           personalDevice.Name != deviceData.Name ||
                                           personalDevice.Manufacturer != deviceData.Manufacturer ||
                                           personalDevice.Model != deviceData.Model ||
                                           !personalDevice.LastSeenDateTime.HasValue ||
                                           personalDevice.LastSeenDateTime.Value.AddDays(1) < RockDateTime.Now ||
                                           (person != null && personalDevice.PersonAliasId != person.PrimaryAliasId);

                    if (hasDeviceChanged)
                    {
                        personalDevice.IsActive         = true;
                        personalDevice.Manufacturer     = deviceData.Manufacturer;
                        personalDevice.Model            = deviceData.Model;
                        personalDevice.Name             = deviceData.Name;
                        personalDevice.LastSeenDateTime = RockDateTime.Now;

                        // Update the person tied to the device, but never blank it out.
                        if (person != null && personalDevice.PersonAliasId != person.PrimaryAliasId)
                        {
                            personalDevice.PersonAliasId = person.PrimaryAliasId;
                        }

                        rockContext.SaveChanges();
                    }
                }

                launchPacket.PersonalDeviceGuid = personalDevice.Guid;
                launchPacket.HomepageGuid       = site.DefaultPage.Guid;

                launchPacket.RockVersion = VersionInfo.VersionInfo.GetRockProductVersionNumber();

                return(Ok(launchPacket));
            }
            catch (Exception)
            {
                // Ooops...
                return(StatusCode(HttpStatusCode.InternalServerError));
            }
        }
Exemple #18
0
        public IHttpActionResult GetLaunchPacket(string deviceIdentifier = null, bool?notificationsEnabled = null)
        {
            var site = MobileHelper.GetCurrentApplicationSite();
            var additionalSettings = site?.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>();
            var rockContext        = new Rock.Data.RockContext();
            var person             = GetPerson(rockContext);
            var deviceData         = Request.GetHeader("X-Rock-DeviceData").FromJsonOrNull <DeviceData>();

            if (additionalSettings == null || !additionalSettings.LastDeploymentDate.HasValue)
            {
                return(NotFound());
            }

            // Ensure the user login is still active, otherwise log them out.
            var principal = ControllerContext.Request.GetUserPrincipal();

            if (person != null && !principal.Identity.Name.StartsWith("rckipid="))
            {
                var userLogin = new UserLoginService(rockContext).GetByUserName(principal.Identity.Name);

                if (userLogin?.IsConfirmed != true || userLogin?.IsLockedOut == true)
                {
                    person = null;
                }
            }

            var launchPacket = new LaunchPacket
            {
                RockVersion         = Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber(),
                LatestVersionId     = additionalSettings.LastDeploymentVersionId ?? ( int )(additionalSettings.LastDeploymentDate.Value.ToJavascriptMilliseconds() / 1000),
                IsSiteAdministrator = site.IsAuthorized(Rock.Security.Authorization.EDIT, person)
            };

            if (deviceData.DeviceType == DeviceType.Phone)
            {
                launchPacket.LatestVersionSettingsUrl = additionalSettings.PhoneUpdatePackageUrl;
            }
            else if (deviceData.DeviceType == DeviceType.Tablet)
            {
                launchPacket.LatestVersionSettingsUrl = additionalSettings.TabletUpdatePackageUrl;
            }
            else
            {
                return(NotFound());
            }

            if (person != null)
            {
                //var principal = ControllerContext.Request.GetUserPrincipal();

                launchPacket.CurrentPerson           = MobileHelper.GetMobilePerson(person, site);
                launchPacket.CurrentPerson.AuthToken = MobileHelper.GetAuthenticationToken(principal.Identity.Name);

                UserLoginService.UpdateLastLogin(principal.Identity.Name);
            }

            //
            // Get or create the personal device.
            //
            if (deviceIdentifier.IsNotNullOrWhiteSpace())
            {
                var mobileDeviceTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSONAL_DEVICE_TYPE_MOBILE).Id;
                var personalDeviceService   = new PersonalDeviceService(rockContext);
                var personalDevice          = personalDeviceService.Queryable()
                                              .Where(a => a.DeviceUniqueIdentifier == deviceIdentifier && a.PersonalDeviceTypeValueId == mobileDeviceTypeValueId && a.SiteId == site.Id)
                                              .FirstOrDefault();

                if (personalDevice == null)
                {
                    personalDevice = new PersonalDevice
                    {
                        DeviceUniqueIdentifier    = deviceIdentifier,
                        PersonalDeviceTypeValueId = mobileDeviceTypeValueId,
                        SiteId               = site.Id,
                        PlatformValueId      = deviceData.DevicePlatform.GetDevicePlatformValueId(),
                        PersonAliasId        = person?.PrimaryAliasId,
                        NotificationsEnabled = true,
                        Manufacturer         = deviceData.Manufacturer,
                        Model            = deviceData.Model,
                        Name             = deviceData.Name,
                        LastSeenDateTime = RockDateTime.Now
                    };

                    personalDeviceService.Add(personalDevice);
                    rockContext.SaveChanges();
                }
                else
                {
                    // A change is determined as one of the following:
                    // 1) A change in Name, Manufacturer, Model, or NotificationsEnabled.
                    // 2) Device not being active.
                    // 3) Not seen in 24 hours.
                    // 4) Signed in with a different person.
                    var hasDeviceChanged = !personalDevice.IsActive ||
                                           personalDevice.Name != deviceData.Name ||
                                           personalDevice.Manufacturer != deviceData.Manufacturer ||
                                           personalDevice.Model != deviceData.Model ||
                                           personalDevice.NotificationsEnabled != (notificationsEnabled ?? true) ||
                                           !personalDevice.LastSeenDateTime.HasValue ||
                                           personalDevice.LastSeenDateTime.Value.AddDays(1) < RockDateTime.Now ||
                                           (person != null && personalDevice.PersonAliasId != person.PrimaryAliasId);

                    if (hasDeviceChanged)
                    {
                        personalDevice.IsActive         = true;
                        personalDevice.Manufacturer     = deviceData.Manufacturer;
                        personalDevice.Model            = deviceData.Model;
                        personalDevice.Name             = deviceData.Name;
                        personalDevice.LastSeenDateTime = RockDateTime.Now;

                        if (notificationsEnabled.HasValue)
                        {
                            personalDevice.NotificationsEnabled = notificationsEnabled.Value;
                        }

                        // Update the person tied to the device, but never blank it out.
                        if (person != null && personalDevice.PersonAliasId != person.PrimaryAliasId)
                        {
                            personalDevice.PersonAliasId = person.PrimaryAliasId;
                        }

                        rockContext.SaveChanges();
                    }
                }

                launchPacket.PersonalDeviceGuid = personalDevice.Guid;
            }

            return(Ok(launchPacket));
        }
        public void Execute()
        {
            if (PageId.HasValue || !string.IsNullOrWhiteSpace(ComponentName))
            {
                using (var rockContext = new RockContext())
                {
                    int channelMediumTypeValueId  = DefinedValueCache.Get(AvalancheUtilities.AppMediumValue.AsGuid()).Id;
                    var interactionChannelService = new InteractionChannelService(rockContext);
                    var interactionService        = new InteractionService(rockContext);
                    var interactionChannel        = interactionChannelService.Queryable()
                                                    .Where(a =>
                                                           a.ChannelTypeMediumValueId == channelMediumTypeValueId &&
                                                           a.ChannelEntityId == this.SiteId)
                                                    .FirstOrDefault();
                    if (interactionChannel == null)
                    {
                        interactionChannel      = new InteractionChannel();
                        interactionChannel.Name = SiteCache.Get(SiteId ?? 1).Name;
                        interactionChannel.ChannelTypeMediumValueId = channelMediumTypeValueId;
                        interactionChannel.ChannelEntityId          = this.SiteId;
                        interactionChannel.ComponentEntityTypeId    = EntityTypeCache.Get <Rock.Model.Page>().Id;
                        interactionChannelService.Add(interactionChannel);
                        rockContext.SaveChanges();
                    }

                    InteractionComponent interactionComponent = null;
                    var interactionComponentService           = new InteractionComponentService(rockContext);

                    if (PageId.HasValue)
                    {
                        interactionComponent = interactionComponentService.GetComponentByEntityId(interactionChannel.Id, PageId.Value, PageTitle);
                    }
                    else
                    {
                        interactionComponent = interactionComponentService.GetComponentByComponentName(interactionChannel.Id, ComponentName);
                    }
                    rockContext.SaveChanges();

                    // Add the interaction
                    if (interactionComponent != null)
                    {
                        var deviceId = Regex.Match(UserAgent, "(?<=-).+(?=\\))").Value.Trim();
                        if (deviceId.Length > 20)
                        {
                            deviceId = deviceId.Substring(0, 20);
                        }
                        var deviceApplication = Regex.Match(UserAgent, "^[\\S]{0,}").Value.Trim() + " " + deviceId;
                        var clientOs          = Regex.Match(UserAgent, "(?<=;).+(?=-)").Value.Trim();
                        var clientType        = Regex.Match(UserAgent, "(?<=\\().+(?=;)").Value.Trim();

                        var deviceType = interactionService.GetInteractionDeviceType(deviceApplication, clientOs, clientType, UserAgent);
                        var interactionSessionService = new InteractionSessionService(rockContext);
                        var interactionSession        = interactionSessionService.Queryable().Where(s => s.IpAddress == IPAddress && s.DeviceTypeId == deviceType.Id).FirstOrDefault();

                        if (interactionSession == null)
                        {
                            interactionSession = new InteractionSession()
                            {
                                DeviceTypeId = deviceType.Id,
                                IpAddress    = TrimString(IPAddress, 25)
                            };
                            interactionSessionService.Add(interactionSession);
                            rockContext.SaveChanges();
                        }

                        Operation          = TrimString(Operation, 25);
                        InteractionSummary = TrimString(InteractionSummary, 500);
                        clientType         = TrimString(clientType, 25);
                        deviceApplication  = TrimString(deviceApplication, 100);
                        clientOs           = TrimString(clientOs, 100);

                        var interaction = new InteractionService(rockContext).AddInteraction(interactionComponent.Id, null, Operation, InteractionData, PersonAliasId, DateViewed,
                                                                                             deviceApplication, clientOs, clientType, UserAgent, IPAddress, interactionSession.Guid);

                        interaction.InteractionSummary = InteractionSummary;

                        PersonalDevice personalDevice = AvalancheUtilities.GetPersonalDevice(deviceId, PersonAliasId, rockContext);
                        if (personalDevice != null)
                        {
                            interaction.PersonalDeviceId = personalDevice.Id;
                        }

                        rockContext.SaveChanges();
                    }
                }
            }
        }
Exemple #20
0
        public HttpResponseMessage Post(List <MACPresence> presenceList)
        {
            using (var rockContext = new RockContext())
            {
                var interactionChannel = new InteractionChannelService(rockContext).Get(Rock.SystemGuid.InteractionChannel.WIFI_PRESENCE.AsGuid());
                if (interactionChannel != null)
                {
                    var interactionComponentIds = new Dictionary <string, int>();

                    var personalDeviceService       = new PersonalDeviceService(rockContext);
                    var interactionService          = new InteractionService(rockContext);
                    var interactionComponentService = new InteractionComponentService(rockContext);

                    // Can't set to local time here as it won't compute DST correctly later.
                    var epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

                    foreach (var macPresence in presenceList.Where(l => l.Mac != null && l.Mac != ""))
                    {
                        var device = personalDeviceService.GetByMACAddress(macPresence.Mac);
                        if (device == null)
                        {
                            device            = new PersonalDevice();
                            device.MACAddress = macPresence.Mac;
                            personalDeviceService.Add(device);

                            rockContext.SaveChanges();
                        }

                        if (macPresence.Presence != null && macPresence.Presence.Any())
                        {
                            foreach (var presence in macPresence.Presence)
                            {
                                // Calc data needed for new and existing data
                                DateTime interactionStart = epochTime.AddSeconds(presence.Arrive).ToLocalTime();
                                DateTime interactionEnd   = epochTime.AddSeconds(presence.Depart).ToLocalTime();
                                TimeSpan ts       = interactionEnd.Subtract(interactionStart);
                                string   duration = (ts.TotalMinutes >= 60 ? $"{ts:%h} hours and " : "") + $"{ts:%m} minutes";

                                Interaction interaction = interactionService.Queryable().Where(i => i.ForeignKey != null && i.ForeignKey == presence.SessionId).FirstOrDefault();
                                if (interaction == null)
                                {
                                    if (!interactionComponentIds.ContainsKey(presence.Space))
                                    {
                                        var component = interactionComponentService
                                                        .Queryable().AsNoTracking()
                                                        .Where(c =>
                                                               c.InteractionChannelId == interactionChannel.Id &&
                                                               c.Name == presence.Space)
                                                        .FirstOrDefault();
                                        if (component == null)
                                        {
                                            component = new InteractionComponent();
                                            interactionComponentService.Add(component);
                                            component.InteractionChannelId = interactionChannel.Id;
                                            component.Name = presence.Space;
                                            rockContext.SaveChanges();
                                        }

                                        interactionComponentIds.Add(presence.Space, component.Id);
                                    }

                                    interaction = new Interaction();
                                    interaction.InteractionDateTime    = interactionStart;
                                    interaction.InteractionEndDateTime = interactionEnd;
                                    interaction.Operation              = "Present";
                                    interaction.InteractionSummary     = $"Arrived at {presence.Space} on {interactionStart.ToShortDateTimeString()}. Stayed for {duration}.";
                                    interaction.InteractionComponentId = interactionComponentIds[presence.Space];
                                    interaction.InteractionData        = presence.ToJson();
                                    interaction.PersonalDeviceId       = device.Id;
                                    interaction.PersonAliasId          = device.PersonAliasId;
                                    interaction.ForeignKey             = presence.SessionId;

                                    interactionService.Add(interaction);
                                }
                                else
                                {
                                    // Update the existing interaction
                                    interaction.InteractionEndDateTime = interactionEnd;
                                    interaction.InteractionSummary     = $"Arrived at {presence.Space} on {interactionStart.ToShortDateTimeString()}. Stayed for {duration}.";
                                    interaction.InteractionData        = presence.ToJson();
                                }

                                rockContext.SaveChanges();
                            }
                        }
                    }

                    var response = ControllerContext.Request.CreateResponse(HttpStatusCode.Created);
                    return(response);
                }
                else
                {
                    var response = ControllerContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "A WiFi Presense Interaction Channel Was Not Found!");
                    throw new HttpResponseException(response);
                }
            }
        }