Пример #1
0
        public bool AuthenticateUser(string userName, string deviceResponse)
        {
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(deviceResponse))
                return false;

            User user = _userRepository.FindUser(userName);
            if (user == null)
                return false;

            AuthenticateResponse authenticateResponse = AuthenticateResponse.FromJson<AuthenticateResponse>(deviceResponse);

            var device = user.DeviceRegistrations.FirstOrDefault(f=> f.KeyHandle.SequenceEqual(Utils.Base64StringToByteArray(authenticateResponse.KeyHandle)));

            if (device == null || user.AuthenticationRequest == null)
                return false;

            // User will have a authentication request for each device they have registered so get the one that matches the device key handle
            AuthenticationRequest authenticationRequest = user.AuthenticationRequest.First(f => f.KeyHandle.Equals(authenticateResponse.KeyHandle));
            DeviceRegistration registration = new DeviceRegistration(device.KeyHandle, device.PublicKey, device.AttestationCert, Convert.ToUInt32(device.Counter));

            StartedAuthentication authentication = new StartedAuthentication(authenticationRequest.Challenge, authenticationRequest.AppId, authenticationRequest.KeyHandle);

            U2F.FinishAuthentication(authentication, authenticateResponse, registration);

            _userRepository.RemoveUsersAuthenticationRequests(user.Name);
            _userRepository.UpdateDeviceCounter(user.Name, device.PublicKey, registration.Counter);

            return true;
        }
Пример #2
0
        public async Task RegisterAsync(string handle, IEnumerable<string> tags)
        {
            var regId = await RetrieveRegistrationIdOrRequestNewOneAsync();

            var deviceRegistration = new DeviceRegistration
            {
                Platform = "wns",
                Handle = handle,
                Tags = tags.ToArray<string>()
            };

            var statusCode = await UpdateRegistrationAsync(regId, deviceRegistration);

            if (statusCode == HttpStatusCode.Gone)
            {
                // regId is expired, deleting from local storage & recreating
                var settings = ApplicationData.Current.LocalSettings.Values;
                settings.Remove("__NHRegistrationId");
                regId = await RetrieveRegistrationIdOrRequestNewOneAsync();
                statusCode = await UpdateRegistrationAsync(regId, deviceRegistration);
            }

            if (statusCode != HttpStatusCode.Accepted)
            {
                // log or throw
                //throw new System.Net.WebException(statusCode.ToString());
            }
        }
    // PUT api/register/5
    // This creates or updates a registration (with provided PNS handle) at the specified id
    public async void Put(string id, DeviceRegistration deviceUpdate)
    {
      // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags

      RegistrationDescription registration = null;
      switch (deviceUpdate.Platform)
      {
        case "mpns":
          registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
          break;
        case "wns":
          registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
          break;
        case "apns":
          registration = new AppleRegistrationDescription(deviceUpdate.Handle);
          break;
        case "gcm":
          registration = new GcmRegistrationDescription(deviceUpdate.Handle);
          break;
        default:
          throw new HttpResponseException(HttpStatusCode.BadRequest);
      }

      registration.RegistrationId = id;
      registration.Tags = new HashSet<string>(deviceUpdate.Tags);

      try
      {
        await hub.CreateOrUpdateRegistrationAsync(registration);
      }
      catch (MessagingException e)
      {
        ReturnGoneIfHubResponseIsGone(e);
      }
    }
Пример #4
0
        public void U2F_FinishAuthentication()
        {
            StartedAuthentication startedAuthentication = new StartedAuthentication(
                TestConts.SERVER_CHALLENGE_SIGN_BASE64,
                TestConts.APP_SIGN_ID,
                TestConts.KEY_HANDLE_BASE64);

            AuthenticateResponse authenticateResponse = new AuthenticateResponse(
                TestConts.CLIENT_DATA_AUTHENTICATE_BASE64,
                TestConts.SIGN_RESPONSE_DATA_BASE64,
                TestConts.KEY_HANDLE_BASE64);


            DeviceRegistration deviceRegistration = new DeviceRegistration(TestConts.KEY_HANDLE_BASE64_BYTE,
                                                                           TestConts.USER_PUBLIC_KEY_AUTHENTICATE_HEX,
                                                                           TestConts.ATTESTATION_CERTIFICATE.Base64StringToByteArray(),
                                                                           0);

            uint orginalValue = deviceRegistration.Counter;

            U2F.Core.Crypto.U2F.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration);

            Assert.True(deviceRegistration.Counter != 0);
            Assert.NotEqual(orginalValue, deviceRegistration.Counter);
            Assert.Equal(orginalValue + 1, deviceRegistration.Counter);
        }
        private async Task <RegistrationOperationStatus> RegisterDeviceAsync(
            AmqpClientConnection client,
            string correlationId,
            DeviceRegistration deviceRegistration)
        {
            AmqpMessage amqpMessage;

            if (deviceRegistration == null)
            {
                amqpMessage = AmqpMessage.Create(new MemoryStream(), true);
            }
            else
            {
                var customContentStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(deviceRegistration)));
                amqpMessage = AmqpMessage.Create(customContentStream, true);
            }
            amqpMessage.Properties.CorrelationId = correlationId;
            amqpMessage.ApplicationProperties.Map[MessageApplicationPropertyNames.OperationType] =
                DeviceOperations.Register;
            amqpMessage.ApplicationProperties.Map[MessageApplicationPropertyNames.ForceRegistration] = false;
            var outcome = await client.AmqpSession.SendingLink
                          .SendMessageAsync(amqpMessage, new ArraySegment <byte>(Guid.NewGuid().ToByteArray()),
                                            TimeoutConstant).ConfigureAwait(false);

            ValidateOutcome(outcome);
            var amqpResponse = await client.AmqpSession.ReceivingLink.ReceiveMessageAsync(TimeoutConstant)
                               .ConfigureAwait(false);

            client.AmqpSession.ReceivingLink.AcceptMessage(amqpResponse);
            string jsonResponse = await new StreamReader(amqpResponse.BodyStream).ReadToEndAsync()
                                  .ConfigureAwait(false);

            return(JsonConvert.DeserializeObject <RegistrationOperationStatus>(jsonResponse));
        }
Пример #6
0
        //public void SetupPushNotifications()
        //{
        //	Client.

        //}

        #region Push Notifications

        public async Task <string> RegisterForPushNotifications()
        {
            try
            {
                //List of Tags to Register With. In this example we are taking the email and "All"
                var tags = new List <string>
                {
                    Settings.CurrentUser.UserEmail,
                    "All"
                };

                var OS = Device.RuntimePlatform;
                Settings.CurrentUser.DevicePlatform = OS;

                var reg = new DeviceRegistration
                {
                    Handle   = Settings.DeviceToken,
                    Platform = OS,
                    Tags     = tags.ToArray()
                };

                var registrationId = await Client.InvokeApiAsync <DeviceRegistration, string>("registerWithHub", reg, HttpMethod.Put, null);

                return(registrationId);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                return(null);
            }
        }
        private async Task PublishRegisterAsync(IChannelHandlerContext context)
        {
            IByteBuffer packagePayload = Unpooled.Empty;

            if (_message.Payload != null && _message.Payload.Length > 0)
            {
                var deviceRegistration = new DeviceRegistration {
                    Payload = new JRaw(_message.Payload)
                };
                var customContentStream =
                    new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(deviceRegistration)));
                long streamLength = customContentStream.Length;
                int  length       = (int)streamLength;
                packagePayload = context.Channel.Allocator.Buffer(length, length);
                await packagePayload.WriteBytesAsync(customContentStream, length).ConfigureAwait(false);
            }

            int packetId = GetNextPacketId();
            var message  = new PublishPacket(Qos, false, false)
            {
                TopicName = string.Format(CultureInfo.InvariantCulture, RegisterTopic, packetId),
                PacketId  = packetId,
                Payload   = packagePayload
            };

            await context.WriteAndFlushAsync(message).ConfigureAwait(false);
        }
Пример #8
0
        public override void SetUp()
        {
            base.SetUp();
            _dataOnlyDeviceRegistration = new DeviceRegistration
            {
                UserId = "myUserId",
                PushNotificationServiceHandle = "myPnsHandle",
                DeviceIdentifier = "myDeviceId",
                Platform         = RuntimePlatform.iOS,
                Templates        = new List <IPushNotificationTemplate>
                {
                    new PushNotificationTemplate("DummyTemplate", "Dummy Title", "Dummy Body", new List <string>
                    {
                        "DummyPropertyOne",
                        "DummyPropertyTwo"
                    })
                }
            };

            _visibleTemplateDeviceRegistration = new DeviceRegistration
            {
                UserId = "myUserId",
                PushNotificationServiceHandle = "myPnsHandle",
                DeviceIdentifier = "myDeviceId",
                Platform         = RuntimePlatform.Android,
                Templates        = new List <IPushNotificationTemplate>
                {
                    new PushNotificationTemplate("VisibleTemplate", "Title", "Body", new List <string>
                    {
                        "VisibleTemplateProperty",
                        "SecondVisibleTemplateProperty"
                    })
                }
            };
        }
Пример #9
0
        public async Task <string> RegisterAsync(string handle, IEnumerable <string> tags)
        {
            ApplicationData.Current.LocalSettings.Values["categories"] = string.Join(",", tags);

            var regId = await RetrieveRegistrationIdOrRequestNewOneAsync();

            var deviceRegistration = new DeviceRegistration
            {
                Platform = "wns",
                Handle   = handle,
                Tags     = tags.ToArray <string>()
            };

            var statusCode = await UpdateRegistrationAsync(regId, deviceRegistration);

            if (statusCode == HttpStatusCode.Gone)
            {
                // regId is expired, deleting from local storage & recreating
                var settings = ApplicationData.Current.LocalSettings.Values;
                settings.Remove("__NHRegistrationId");
                regId = await RetrieveRegistrationIdOrRequestNewOneAsync();

                statusCode = await UpdateRegistrationAsync(regId, deviceRegistration);
            }

            if (statusCode == HttpStatusCode.OK)
            {
                return("Accepted");
            }
            else
            {
                return("Forbidden");
            }
        }
Пример #10
0
 /// <summary>
 /// Initiates the authentication process.
 /// </summary>
 /// <param name="appId">appId the U2F AppID. Set this to the Web Origin of the login page, unless you need to support logging in from multiple Web Origins.</param>
 /// <param name="deviceRegistration">the DeviceRegistration for which to initiate authentication.</param>
 /// <param name="challenge">random generated byte[] from ICrytoService.</param>
 /// <returns>a StartedAuthentication which should be sent to the client and temporary saved by the server.</returns>
 public static StartedAuthentication StartAuthentication(string appId, DeviceRegistration deviceRegistration, byte[] challenge)
 {
     return(new StartedAuthentication(
                challenge.ByteArrayToBase64String(),
                appId,
                deviceRegistration.KeyHandle.ByteArrayToBase64String()));
 }
Пример #11
0
        public static void ProcessDeviceToken(DeviceRegistration device, Address address, TokenRegistration token, decimal amount)
        {
            SendResponse sendResponse = null;

            try
            {
                if (string.IsNullOrEmpty(address.Name))
                {
                    sendResponse = FirebaseGateway.SendPush(device.token, token.Token, $"{token.Token} Deposit Received", $"You have received a deposit of {amount.ToString("0.##")} {token.Token}");
                }
                else
                {
                    sendResponse = FirebaseGateway.SendPush(device.token, token.Token, $"{token.Token} Deposit Received", $"{address.Name.ToUpper()} has received a deposit of {amount.ToString("0.##")} {token.Token}");
                }
                //Now update firestore so we dont send the user duplicate messages
                //token.lastBalance = IconGateway.GetBalance(address, token).ToString();
                //token.lastDepositPushSentDate = DateTime.UtcNow;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[MAIN] EXCEPTION processing Deposit check {ex.Message}");
            }

            if (sendResponse != null && sendResponse.failure > 0)
            {
                if (sendResponse.results.Any(a => a.error == "NotRegistered"))
                {
                    //This token has become stale, need to remove it from firestore
                    FirebaseGateway.DeleteDevice(device);
                }
            }
        }
        public bool AddDeviceRegistration(DeviceRegistrationModel device)
        {
            try
            {
                using (var dataContext = new BrownBagDataEntities())
                {
                    var deviceRegistration = new DeviceRegistration
                    {
                        AccessToken = device.AccessToken.Trim(),

                        CreatedOnUtc    = DateTime.Now.ToUniversalTime(),
                        IMEI_Number     = device.IMEINumber.Trim(),
                        IsActive        = true,
                        RefCustomerGuid = string.IsNullOrEmpty(device.CustomerGuid) ? (Guid?)null : Guid.Parse(device.CustomerGuid),
                        UpdatedOnUtc    = DateTime.Now.ToUniversalTime()
                    };
                    dataContext.DeviceRegistrations.Add(deviceRegistration);
                    return(dataContext.SaveChanges() > 0 ? true : false);
                }
            }
            catch
            {
                throw;
            }
        }
Пример #13
0
        public MessagingService()
        {
            Types.AddClientClassMapping("com.backendless.management.DeviceRegistrationDto", typeof(Messaging.DeviceRegistration));
            Types.AddClientClassMapping("com.backendless.services.messaging.MessageStatus", typeof(Messaging.MessageStatus));
            Types.AddClientClassMapping("com.backendless.services.messaging.PublishOptions", typeof(Messaging.PublishOptions));
            Types.AddClientClassMapping("com.backendless.services.messaging.DeliveryOptions", typeof(Messaging.DeliveryOptions));
            Types.AddClientClassMapping("com.backendless.services.messaging.PublishStatusEnum", typeof(Messaging.PublishStatusEnum));
            Types.AddClientClassMapping("com.backendless.services.messaging.Message", typeof(Messaging.Message));
            deviceId = Guid.NewGuid().ToString();

#if WINDOWS_PHONE8
            object deviceId;
            if (!Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out deviceId))
            {
                deviceId = HostInformation.PublisherHostId;

                if (deviceId == null)
                {
                    throw new BackendlessException(new BackendlessFault(ExceptionMessage.NO_DEVICEID_CAPABILITY));
                }
            }

            _deviceRegistrationDto = new DeviceRegistration
            {
                Os        = "WP",
                DeviceId  = BitConverter.ToString((byte[])deviceId).Replace("-", ""),
                OsVersion = System.Environment.OSVersion.Version.Major.ToString(CultureInfo.InvariantCulture)
            };
#elif UNITY
            _deviceRegistrationDto = new DeviceRegistration();
#endif
        }
        public bool CompleteRegistration(string userName, string deviceResponse)
        {
            if (string.IsNullOrWhiteSpace(deviceResponse))
            {
                return(false);
            }

            var user = _userRepository.FindUser(userName);

            if (user == null ||
                user.AuthenticationRequest == null ||
                user.AuthenticationRequest.Count == 0)
            {
                return(false);
            }


            RegisterResponse registerResponse = RegisterResponse.FromJson <RegisterResponse>(deviceResponse);

            // When the user is registration they should only ever have one auth request.
            AuthenticationRequest authenticationRequest = user.AuthenticationRequest.First();

            StartedRegistration startedRegistration = new StartedRegistration(authenticationRequest.Challenge, authenticationRequest.AppId);
            DeviceRegistration  registration        = U2F.FinishRegistration(startedRegistration, registerResponse);

            _userRepository.RemoveUsersAuthenticationRequests(userName);
            _userRepository.AddDeviceRegistration(userName, registration.AttestationCert, registration.Counter, registration.KeyHandle, registration.PublicKey);

            return(true);
        }
Пример #15
0
        public void RegisterDeviceInBackendless(string token)
        {
            string id         = null;
            var    OS_VERSION = UIDevice.CurrentDevice.SystemVersion.ToString();
            var    OS         = "IOS";

            try
            {
                id = Guid.NewGuid().ToString();
            }
            catch (Exception e)
            {
                Console.Write($"Error {e.Message}");
            }

            var DEVICE_ID = id;
            //"174677789761"
            var deviceReg = new DeviceRegistration();

            deviceReg.Os          = OS;
            deviceReg.OsVersion   = OS_VERSION;
            deviceReg.Expiration  = DateTime.Now.AddHours(3);
            deviceReg.DeviceId    = DEVICE_ID;
            deviceReg.DeviceToken = token;
            Backendless.Messaging.DeviceRegistration = deviceReg;

            Backendless.Messaging.RegisterDevice(token, "default", new AsyncCallback <string>(responseHanlder, errorHandler));
        }
Пример #16
0
        public bool AuthenticateUser(string userName, string deviceResponse)
        {
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(deviceResponse))
                return false;

            User user = _userRepository.FindUser(userName);
            if (user == null)
                return false;

            AuthenticateResponse authenticateResponse = AuthenticateResponse.FromJson<AuthenticateResponse>(deviceResponse);

            var device = user.DeviceRegistrations.FirstOrDefault();

            if (device == null || user.AuthenticationRequest == null)
                return false;

            DeviceRegistration registration = new DeviceRegistration(device.KeyHandle, device.PublicKey, device.AttestationCert, device.Counter);

            StartedAuthentication authentication = new StartedAuthentication(user.AuthenticationRequest.Challenge, user.AuthenticationRequest.AppId, user.AuthenticationRequest.KeyHandle);

            U2F.FinishAuthentication(authentication, authenticateResponse, registration);

            _userRepository.RemoveUsersAuthenticationRequest(user.Name);
            _userRepository.UpdateDeviceCounter(user.Name, device.PublicKey, registration.Counter);

            return true;
        }
        public async Task RegisterAsync(string handle, string platform, IEnumerable <string> tags)
        {
            var regId = await RetrieveRegistrationIdOrRequestNewOneAsync();

            var deviceRegistration = new DeviceRegistration
            {
                Platform = platform,
                Handle   = handle,
                Tags     = tags.ToArray <string>()
            };

            var statusCode = await UpdateRegistrationAsync(regId, deviceRegistration);

            if (statusCode == HttpStatusCode.Gone)
            {
                // regId is expired, deleting from local storage & recreating
                //var settings = ApplicationData.Current.LocalSettings.Values;
                //settings.Remove("__NHRegistrationId");
                regId = await RetrieveRegistrationIdOrRequestNewOneAsync();

                statusCode = await UpdateRegistrationAsync(regId, deviceRegistration);
            }

            if (statusCode != HttpStatusCode.Accepted)
            {
                // log or throw
            }
        }
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #19
0
        public void RegisterDeviceInBackendless(string token)
        {
            String id = null;

            id = Build.Serial;
            var OS_VERSION = (Build.VERSION.SdkInt).ToString();
            var OS         = "ANDROID";

            try
            {
                id = UUID.RandomUUID().ToString();
            }
            catch (Exception e)
            {
                Console.Write($"Error {e.Message}");
            }

            var DEVICE_ID = id;
            //"174677789761"
            var deviceReg = new DeviceRegistration();

            deviceReg.Os          = OS;
            deviceReg.OsVersion   = OS_VERSION;
            deviceReg.Expiration  = DateTime.Now.AddHours(3);
            deviceReg.DeviceId    = DEVICE_ID;
            deviceReg.DeviceToken = token;
            Backendless.Messaging.DeviceRegistration = deviceReg;

            Backendless.Messaging.RegisterDevice(token, "default", new AsyncCallback <string>(responseHanlder, errorHandler));
        }
Пример #20
0
 /// <summary>
 /// Gets the device registration status.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='registrationId'>
 /// Registration ID.
 /// </param>
 /// <param name='idScope'>
 /// </param>
 /// <param name='deviceRegistration'>
 /// Device registration
 /// </param>
 public static Models.DeviceRegistrationResult DeviceRegistrationStatusLookup(
     this IRuntimeRegistration operations,
     string registrationId,
     string idScope,
     DeviceRegistration deviceRegistration = default(DeviceRegistration))
 {
     return(operations.DeviceRegistrationStatusLookupAsync(registrationId, idScope, deviceRegistration).GetAwaiter().GetResult());
 }
Пример #21
0
        private DeviceRegistration InitializeDeviceId(DeviceRegistration dto)
        {
            String id = null;

            id           = Guid.NewGuid().ToString();
            dto.DeviceId = id;
            return(dto);
        }
Пример #22
0
        public async Task <IActionResult> Register(DeviceRegistration model)
        {
            // initalise registration process
            var challenge = await _fido.InitiateRegistration(User.Identity.Name, model.DeviceName);

            // challenge the device
            return(View(challenge.ToBase64Dto()));
        }
        public async Task <bool> EnablePushNotifications(string id, DeviceRegistration deviceUpdate)
        {
            string json     = JsonConvert.SerializeObject(deviceUpdate);
            var    content  = new StringContent(json, Encoding.UTF8, "application/json");
            var    response = await _client.PutAsync("notifications/enable/" + id, content);

            return(response.IsSuccessStatusCode);
        }
Пример #24
0
        public DeviceRegistration GetDeviceInfo()
        {
            DeviceRegistration deviceRegistration = new DeviceRegistration();

            deviceRegistration.DeviceToken = App.AppleDeviceToken;
            deviceRegistration.Platform    = "iOS";
            return(deviceRegistration);
        }
Пример #25
0
        public DeviceRegistration GetDeviceInfo()
        {
            DeviceRegistration device = new DeviceRegistration();

            device.DeviceToken = FirebaseInstanceId.Instance.Token;
            device.Platform    = "Android";
            return(device);
        }
Пример #26
0
 /// <summary>
 /// Registers the devices.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='registrationId'>
 /// Registration ID.
 /// </param>
 /// <param name='idScope'>
 /// </param>
 /// <param name='deviceRegistration'>
 /// Device registration request.
 /// </param>
 /// <param name='forceRegistration'>
 /// Force the device to re-register. Setting this option may assign the device
 /// to a different IotHub.
 /// </param>
 public static RegistrationOperationStatus RegisterDevice(
     this IRuntimeRegistration operations,
     string registrationId,
     string idScope,
     DeviceRegistration deviceRegistration = default(DeviceRegistration),
     bool?forceRegistration = default(bool?))
 {
     return(operations.RegisterDeviceAsync(registrationId, idScope, deviceRegistration, forceRegistration).GetAwaiter().GetResult());
 }
Пример #27
0
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            //case "mpns":
            //    var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            //        "<wp:Notification xmlns:wp=\"WPNotification\">" +
            //           "<wp:Toast>" +
            //                "<wp:Text1>$(message)</wp:Text1>" +
            //           "</wp:Toast> " +
            //        "</wp:Notification>";
            //    registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            //    break;
            //case "wns":
            //    toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
            //    registration = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            //    break;
            case "apns":
                var alertTemplate = "{\"aps\":{\"alert\":\"$(message)\"}}";
                registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                break;

            case "gcm":
                var messageTemplate = "{\"data\":{\"msg\":\"$(message)\"}}";
                registration = new FcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            var username = HttpContext.Current.User.Identity.Name;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            if (!registration.Tags.Contains("all"))
            {
                registration.Tags.Add("all");
            }
            registration.Tags.Add("username:" + username);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #28
0
        /**
         * Initiates the authentication process.
         *
         * @param appId the U2F AppID. Set this to the Web Origin of the login page, unless you need to
         * support logging in from multiple Web Origins.
         * @param deviceRegistration the DeviceRegistration for which to initiate authentication.
         * @return a StartedAuthentication which should be sent to the client and temporary saved by
         * the server.
         */
        public static StartedAuthentication StartAuthentication(String appId, DeviceRegistration deviceRegistration)
        {
            byte[] challenge = ChallengeGenerator.GenerateChallenge();

            return(new StartedAuthentication(
                       Utils.ByteArrayToBase64String(challenge),
                       appId,
                       Utils.ByteArrayToBase64String(deviceRegistration.KeyHandle)));
        }
Пример #29
0
 public static void UpdateDevice(DeviceRegistration device)
 {
     if (device.Dirty)
     {
         Console.WriteLine($"[FB] Updating Document data for {device.token}");
         db.Collection("devices").Document(device.token).SetAsync(device, SetOptions.MergeAll).Wait();
         device.ResetDirty();
     }
 }
        public async Task <bool> RegisterForPushNotifications(string id, DeviceRegistration deviceUpdate, UserManager <IdentityUser> userManager, ApplicationDbContext context)
        {
            RegistrationDescription registrationDescription = null;
            int deviceType = 0;

            switch (deviceUpdate.Platform)
            {
            case "apns":
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                deviceType = DeviceType.IOS;
                break;

            case "fcm":
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                deviceType = DeviceType.ANDROID;
                break;
            }

            registrationDescription.RegistrationId = id;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                var user = await userManager.FindByNameAsync(deviceUpdate.Tags[0].Split(":")[1]);

                if (!context.UserClaims.Any(x => x.UserId == user.Id && x.ClaimType == "PushNotificationsProvider"))
                {
                    IdentityUserClaim <string> claim = new IdentityUserClaim <string>()
                    {
                        UserId     = user.Id,
                        ClaimType  = "PushNotificationsProvider",
                        ClaimValue = deviceType.ToString()
                    };
                    context.Add(claim);
                }
                else
                {
                    var existingClaim = context.UserClaims.Single(x => x.UserId == user.Id && x.ClaimType == "PushNotificationsProvider");
                    existingClaim.ClaimValue = deviceType.ToString();
                    context.Update(existingClaim);
                }

                context.SaveChanges();

                await _hub.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #31
0
        private static DeviceRegistration GetDeviceRegistration(string handle)
        {
            var deviceRegistration = new DeviceRegistration
            {
                Platform = "wns",
                Handle   = handle
            };

            return(deviceRegistration);
        }
Пример #32
0
        public async Task EnablePushNotifications(string id, DeviceRegistration deviceUpdate)
        {
            var builder = new UriBuilder(AppSettings.PlantsEndpoint);

            builder.AppendToPath("api");
            builder.AppendToPath("notifications");
            builder.AppendToPath("enable");
            builder.AppendToPath(id);
            await requestService.PutAsync(builder.ToString(), deviceUpdate);
        }
Пример #33
0
        private async void OnDeleteDeviceClicked(object sender, RoutedEventArgs e)
        {
            Button             button = sender as Button;
            DeviceRegistration device = (button.DataContext) as DeviceRegistration;

            NotificationHubClient client = NotificationHubClient.CreateClientFromConnectionString(ConnectionString, "uwpsample");
            await client.DeleteRegistrationAsync(device.RegistrationId);

            devices.Remove(device);
        }
Пример #34
0
        private static bool IsEnabled(DeviceRegistration device)
        {
            if (device == null)
            {
                return(false);
            }

            return(!string.IsNullOrWhiteSpace(device.EvernoteDestinationEmail) &&
                   !string.IsNullOrWhiteSpace(device.EvernoteNotebook) &&
                   !string.IsNullOrWhiteSpace(device.EvernoteSourceEmail));
        }
Пример #35
0
        private async Task<HttpStatusCode> UpdateRegistrationAsync(string regId, DeviceRegistration deviceRegistration)
        {
            using (var httpClient = new HttpClient())
            {
                var settings = ApplicationData.Current.LocalSettings.Values;
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", (string)settings["AuthenticationToken"]);

                var putUri = POST_URL + "/" + regId;

                string json = JsonConvert.SerializeObject(deviceRegistration);
                var response = await httpClient.PutAsync(putUri, new StringContent(json, Encoding.UTF8, "application/json"));
                return response.StatusCode;
            }
        }
Пример #36
0
        /**
        * Finishes a previously started authentication.
        *
        * @param startedAuthentication
        * @param response the response from the token/client.
        * @return the new value of the DeviceRegistration's counter.
        */
        public static void FinishAuthentication(StartedAuthentication startedAuthentication,
                                                              AuthenticateResponse response,
                                                              DeviceRegistration deviceRegistration,
                                                              HashSet<String> facets = null)
        {
            ClientData clientData = response.GetClientData();
            clientData.CheckContent(AuthenticateTyp, startedAuthentication.Challenge, facets);

            RawAuthenticateResponse authenticateResponse = RawAuthenticateResponse.FromBase64(response.SignatureData);
            authenticateResponse.CheckSignature(startedAuthentication.AppId, clientData.AsJson(), deviceRegistration.PublicKey);
            authenticateResponse.CheckUserPresence();

            deviceRegistration.CheckAndUpdateCounter(authenticateResponse.Counter);
        }
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate,string userid) //ADDED STRING USERID
        {
            ApiServices.Log.Info("user id in put request: " + userid + "\t Time: " + DateTime.Now);
            RegistrationDescription registration = null;
            switch (deviceUpdate.Platform)
            {
                case "mpns":
                    registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "wns":
                    registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "apns":
                    registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "gcm":
                    registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            //var username = HttpContext.Current.User.Identity.Name;
            
            // add check if user is allowed to add these tags
            ApiServices.Log.Info("username = "******"\t Time: " + DateTime.Now);
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);
            registration.Tags.Add("username:"******"in the try for creating registration\t Time: " + DateTime.Now);
                
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ApiServices.Log.Error("in the catch\t Time: " + DateTime.Now);
               
                ReturnGoneIfHubResponseIsGone(e);
            }
 
            return Request.CreateResponse(HttpStatusCode.OK);
        }
Пример #38
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;
            switch (deviceUpdate.Platform)
            {
                case "mpns":
                    var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                        "<wp:Notification xmlns:wp=\"WPNotification\">" +
                           "<wp:Toast>" +
                                "<wp:Text1>$(message)</wp:Text1>" +
                           "</wp:Toast> " +
                        "</wp:Notification>";
                    registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
                    break;
                case "wns":
                    toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
                    registration = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
                    break;
                case "apns":
                    var alertTemplate = "{\"aps\":{\"alert\":\"$(message)\"}}";
                    registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                    break;
                case "gcm":
                    var messageTemplate = "{\"data\":{\"msg\":\"$(message)\"}}";
                    registration = new GcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            registration.RegistrationId = id;
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);
            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Пример #39
0
        // PUT api/put/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;
            switch (deviceUpdate.Platform)
            {
                case "mpns":
                    registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "wns":
                    registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "apns":
                    registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                    break;
                case "gcm":
                    registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            var username = HttpContext.Current.User.Identity.Name;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);
            registration.Tags.Add("username:" + username);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Пример #40
0
        public void U2F_FinishAuthentication()
        {
            StartedAuthentication startedAuthentication = new StartedAuthentication(
                TestConts.SERVER_CHALLENGE_SIGN_BASE64,
                TestConts.APP_SIGN_ID,
                TestConts.KEY_HANDLE_BASE64);

            AuthenticateResponse authenticateResponse = new AuthenticateResponse(
                TestConts.CLIENT_DATA_AUTHENTICATE_BASE64,
                TestConts.SIGN_RESPONSE_DATA_BASE64,
                TestConts.KEY_HANDLE_BASE64);

            DeviceRegistration deviceRegistration = new DeviceRegistration(TestConts.KEY_HANDLE_BASE64_BYTE, TestConts.USER_PUBLIC_KEY_AUTHENTICATE_HEX,
                Utils.Base64StringToByteArray(TestConts.ATTESTATION_CERTIFICATE), 0);

            uint orginalValue = deviceRegistration.Counter;

            U2F.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration);

            Assert.IsTrue(deviceRegistration.Counter != 0);
            Assert.AreNotEqual(orginalValue, deviceRegistration.Counter);
        }
Пример #41
0
        public List<ServerChallenge> GenerateServerChallenge(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName))
                return null;

            User user = _userRepository.FindUser(userName);

            if (user == null)
                return null;

            var device = user.DeviceRegistrations;

            if (device == null || device.Count == 0)
                return null;

            List<ServerChallenge> serverChallenges = new List<ServerChallenge>();
            foreach (var registeredDevice in device)
            {
                DeviceRegistration registration = new DeviceRegistration(registeredDevice.KeyHandle, registeredDevice.PublicKey, registeredDevice.AttestationCert, registeredDevice.Counter);
                StartedAuthentication startedAuthentication = U2F.StartAuthentication(DemoAppId, registration);

                serverChallenges.Add(new ServerChallenge
                {
                    appId = startedAuthentication.AppId,
                    challenge = startedAuthentication.Challenge,
                    keyHandle = startedAuthentication.KeyHandle,
                    version = startedAuthentication.Version
                });

                _userRepository.SaveUserAuthenticationRequest(userName, startedAuthentication.AppId, startedAuthentication.Challenge,
                                                              startedAuthentication.KeyHandle);
            }

            return serverChallenges;
        }
Пример #42
0
        public List<ServerChallenge> GenerateServerChallenges(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName))
                return null;

            User user = _userRepository.FindUser(userName);

            if (user == null)
                return null;

            // We only want to generate challenges for un-compromised devices
            List<Device> device = user.DeviceRegistrations.Where(w => w.IsCompromised == false).ToList();

            if (device.Count == 0)
                return null;

            _userRepository.RemoveUsersAuthenticationRequests(userName);

            List<ServerChallenge> serverChallenges = new List<ServerChallenge>();
            foreach (var registeredDevice in device)
            {
                DeviceRegistration registration = new DeviceRegistration(registeredDevice.KeyHandle, registeredDevice.PublicKey, registeredDevice.AttestationCert, Convert.ToUInt32(registeredDevice.Counter));
                StartedAuthentication startedAuthentication = U2F.StartAuthentication(DemoAppId, registration);

                serverChallenges.Add(new ServerChallenge
                {
                    appId = startedAuthentication.AppId,
                    challenge = startedAuthentication.Challenge,
                    keyHandle = startedAuthentication.KeyHandle,
                    version = startedAuthentication.Version
                });

                _userRepository.SaveUserAuthenticationRequest(userName, startedAuthentication.AppId, startedAuthentication.Challenge,
                                                              startedAuthentication.KeyHandle);
            }

            return serverChallenges;
        }
Пример #43
0
        /**
         * Initiates the authentication process.
         *
         * @param appId the U2F AppID. Set this to the Web Origin of the login page, unless you need to
         * support logging in from multiple Web Origins.
         * @param deviceRegistration the DeviceRegistration for which to initiate authentication.
         * @return a StartedAuthentication which should be sent to the client and temporary saved by
         * the server.
         */
        public static StartedAuthentication StartAuthentication(String appId, DeviceRegistration deviceRegistration)
        {
            byte[] challenge = ChallengeGenerator.GenerateChallenge();

            return new StartedAuthentication(
                Utils.ByteArrayToBase64String(challenge),
                appId,
                Utils.ByteArrayToBase64String(deviceRegistration.KeyHandle));
        }
Пример #44
0
        private void CreateResponses()
        {
            _deviceRegistration = new DeviceRegistration(
                TestConts.KEY_HANDLE_BASE64_BYTE,
                TestConts.USER_PUBLIC_KEY_AUTHENTICATE_HEX,
                Utils.Base64StringToByteArray(TestConts.ATTESTATION_CERTIFICATE),
                0);

            _authenticateResponse = new AuthenticateResponse(
                TestConts.CLIENT_DATA_AUTHENTICATE_BASE64,
                TestConts.SIGN_RESPONSE_DATA_BASE64,
                TestConts.KEY_HANDLE_BASE64);
        }
Пример #45
0
        private void CreateResponses()
        {
            _registerResponse = new RegisterResponse(TestConts.REGISTRATION_RESPONSE_DATA_BASE64,
                                                                     TestConts.CLIENT_DATA_REGISTER_BASE64);
            _rawAuthenticateResponse = RawRegisterResponse.FromBase64(_registerResponse.RegistrationData);
            _deviceRegistration = _rawAuthenticateResponse.CreateDevice();

            _authenticateResponse = new AuthenticateResponse(TestConts.CLIENT_DATA_AUTHENTICATE_BASE64,
                                                            TestConts.SIGN_RESPONSE_DATA_BASE64,
                                                            TestConts.KEY_HANDLE_BASE64);
        }