Exemplo n.º 1
0
        private void OnExecute()
        {
            var vapidKeys = VapidHelper.GenerateVapidKeys();

            var publicKey  = $"const vapidPublicKey = '{vapidKeys.PublicKey}';";
            var privateKey = $"const vapidPrivateKey = '{vapidKeys.PrivateKey}';";

            File.WriteAllText("service-worker.js", serviceWorkerFile);
            File.WriteAllText("index.html", indexFile);
            File.WriteAllLines("app.js", new string[] { publicKey, privateKey, appFile });

            var bytes = Convert.FromBase64String(iconFile);

            using (var imageFile = new FileStream("icon.png", FileMode.Create))
            {
                imageFile.Write(bytes, 0, bytes.Length);
                imageFile.Flush();
            }

            Console.WriteLine(
                $"\nGenerated!\n\nPublic key: {vapidKeys.PublicKey}\nPrivate key: {vapidKeys.PrivateKey}\n\n" +
                "- Run dotnet serve -o\n" +
                "- Click the Subscribe button\n" +
                "- Copy command from textarea (Send command)\n" +
                "- Paste command into terminal to send push notification\n");
        }
Exemplo n.º 2
0
        private void CreateKeys_OnClick(object sender, RoutedEventArgs e)
        {
            VapidDetails keys = VapidHelper.GenerateVapidKeys();

            PrivateKeyTextBox.Text = keys.PrivateKey;
            PublicKeyTextBox.Text  = keys.PublicKey;
        }
Exemplo n.º 3
0
        public ActionResult <string> enviar(string pushEndpoint, string p256dh, string auth)
        {
            var keys = VapidHelper.GenerateVapidKeys();

            // "eC8kA5lfrjc:APA91bHHHh3ikNWPa-614pz7FbWdPvCTn01OvkNuas6m-ilwP-U_VPHLd5QPsjL8W5G8gLquoTJd-jUVRDOziyXvxXoeY8ua2sRvt6GnG8WLpFdOkk7SI8_AxFZnlug4t9FOU7S-XjzH"
            pushEndpoint = @"https://fcm.googleapis.com/fcm/send/" + pushEndpoint;
            //p256dh = @"BAGGIn3MC7LZRCFKuRRSjA28bwQRP7mO_9AEr2l7ety-dtSn7Fcw11-aZu5UCOE0C2gVXVEaWkFLu7PWCR1ufGI";
            //auth = @"VKMl5N1lJomQreFUjKlzeQ";

            var subject    = @"mailto:[email protected]";
            var publicKey  = keys.PublicKey;
            var privateKey = keys.PrivateKey;

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, "payload", vapidDetails);
            }
            catch (WebPushException exception)
            {
                return(exception.StatusCode.ToString());
            }

            return("OK");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Start the push server, this initialized vapid details from a file, if it exists else it will create the vapid details
        /// </summary>
        public static async void Start()
        {
            Console.WriteLine("Started push server");
            // Read Vapid details from cache or create new ones
            if (File.Exists(VapidDetailsFile))
            {
                Details = await ImportVapidDetails();
            }
            else
            {
                Details         = VapidHelper.GenerateVapidKeys();
                Details.Subject = Subject;
                await ExportVapidDetails(Details);
            }

            // Read list of clients from cache or create empty list
            if (File.Exists(ClientsFile))
            {
                Clients = await ImportClients();
            }
            else
            {
                Clients = new List <PushClient>();
                await ExportClients(Clients);
            }
        }
Exemplo n.º 5
0
 public async Task <IActionResult> GetKeysAsync(CancellationToken cancellationToken = default)
 {
     return(await Task.Run(() =>
     {
         VapidDetails keys = VapidHelper.GenerateVapidKeys();
         return Ok(keys);
     }, cancellationToken).ConfigureAwait(false));
 }
Exemplo n.º 6
0
 public string GetKey()
 {
     if (_keys == null)
     {
         _keys = VapidHelper.GenerateVapidKeys();
     }
     return(_keys.PublicKey);
 }
Exemplo n.º 7
0
        public void TestGenerateVapidKeysNoCache()
        {
            VapidDetails keys1 = VapidHelper.GenerateVapidKeys();
            VapidDetails keys2 = VapidHelper.GenerateVapidKeys();

            Assert.AreNotEqual(keys1.PublicKey, keys2.PublicKey);
            Assert.AreNotEqual(keys1.PrivateKey, keys2.PrivateKey);
        }
Exemplo n.º 8
0
        /// <summary>
        /// https://github.com/web-push-libs/web-push-csharp
        /// </summary>
        static void GenerateAndPrintVapidKeys()
        {
            VapidDetails vapidKeys = VapidHelper.GenerateVapidKeys();

            // Prints 2 URL Safe Base64 Encoded Strings
            Console.WriteLine("Public {0}", vapidKeys.PublicKey);
            Console.WriteLine("Private {0}", vapidKeys.PrivateKey);
        }
Exemplo n.º 9
0
        public IActionResult GenerateKeys()
        {
            var keys = VapidHelper.GenerateVapidKeys();

            ViewBag.PublicKey  = keys.PublicKey;
            ViewBag.PrivateKey = keys.PrivateKey;
            return(View());
        }
Exemplo n.º 10
0
        public void TestGenerateVapidKeysNoCache()
        {
            var keys1 = VapidHelper.GenerateVapidKeys();
            var keys2 = VapidHelper.GenerateVapidKeys();

            Assert.NotEqual(keys1.PublicKey, keys2.PublicKey);
            Assert.NotEqual(keys1.PrivateKey, keys2.PrivateKey);
        }
Exemplo n.º 11
0
        public void TestGenerateVapidKeys()
        {
            var keys       = VapidHelper.GenerateVapidKeys();
            var publicKey  = UrlBase64.Decode(keys.PublicKey);
            var privateKey = UrlBase64.Decode(keys.PrivateKey);

            Assert.AreEqual(32, privateKey.Length);
            Assert.AreEqual(65, publicKey.Length);
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            var vapidkeys = VapidHelper.GenerateVapidKeys();

            Console.WriteLine($"Public Key : {vapidkeys.PublicKey}");
            Console.WriteLine($"Private key : {vapidkeys.PrivateKey}");

            Console.Read();
        }
Exemplo n.º 13
0
 public ChatController(ILogger <ChatController> logger)
 {
     _logger           = logger;
     _client           = new WebPushClient();
     vapidKeys         = VapidHelper.GenerateVapidKeys();
     vapidKeys.Subject = "mailto:[email protected]";
     _logger.LogDebug($"Public {vapidKeys.PublicKey}");
     _logger.LogDebug($"Private {vapidKeys.PrivateKey}");
     _logger.LogDebug($"Subject {vapidKeys.Subject}");
 }
Exemplo n.º 14
0
        public void TestGenerateVapidKeys()
        {
            VapidDetails keys = VapidHelper.GenerateVapidKeys();

            byte[] publicKey  = UrlBase64.Decode(keys.PublicKey);
            byte[] privateKey = UrlBase64.Decode(keys.PrivateKey);

            Assert.AreEqual(32, privateKey.Length);
            Assert.AreEqual(65, publicKey.Length);
        }
Exemplo n.º 15
0
 public ActionResult <string> VapidPublicKey()
 {
     if (string.IsNullOrEmpty(_config.Value.PrivateKey))
     {
         var pair = VapidHelper.GenerateVapidKeys();
         _config.Value.PrivateKey = pair.PrivateKey;
         _config.Value.PublicKey  = pair.PublicKey;
         _configurationStore.Store(_config.Value);
     }
     return(Ok(_config.Value.PublicKey));
 }
        public IActionResult GenerateKeys()
        {
            VapidHelper.ValidateSubject("mailto:[email protected]");
            var keys = VapidHelper.GenerateVapidKeys();

            VapidHelper.ValidatePublicKey(keys.PublicKey);
            VapidHelper.ValidatePrivateKey(keys.PrivateKey);

            ViewBag.PublicKey  = keys.PublicKey;
            ViewBag.PrivateKey = keys.PrivateKey;
            return(View());
        }
        /// <summary>
        /// Sets the vapid details.
        /// </summary>
        /// <param name="p_options">Web push options.</param>
        private async Task SetVapidDetails(IOptions <WebPushOptions> p_options)
        {
            bool   v_validSubject = true;
            string v_vapidSubject;
            string v_vapidPublicKey;
            string v_vapidPrivateKey;

            try
            {
                VapidHelper.ValidateSubject(p_options.Value.VapidSubject);
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, "Vapid subject is not valid");
                v_validSubject = false;
            }

            if (!v_validSubject && String.IsNullOrWhiteSpace(GcmAPIKey))
            {
                throw new ApplicationException("You must set a valid vapid subject or GCM API Key");
            }

            if (v_validSubject)
            {
                v_vapidSubject = p_options.Value.VapidSubject;

                try
                {
                    VapidHelper.ValidatePublicKey(p_options.Value.VapidPublicKey);
                    VapidHelper.ValidatePrivateKey(p_options.Value.VapidPrivateKey);

                    v_vapidPublicKey  = p_options.Value.VapidPublicKey;
                    v_vapidPrivateKey = p_options.Value.VapidPrivateKey;
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Your Vapid keys are not valid. Using auto generated keys.");

                    var v_tempVapid = VapidHelper.GenerateVapidKeys();
                    v_vapidPublicKey  = v_tempVapid.PublicKey;
                    v_vapidPrivateKey = v_tempVapid.PrivateKey;

                    Logger.LogInformation("Flushing existing devices");
                    IEnumerable <Device> v_devices = this.DbContext.Devices;

                    this.DbContext.RemoveRange(v_devices);
                    await this.DbContext.SaveChangesAsync();
                }

                VapidDetails = new VapidDetails(v_vapidSubject, v_vapidPublicKey, v_vapidPrivateKey);
            }
        }
Exemplo n.º 18
0
        /// <inheritdoc />
        public void CheckOrGenerateVapidDetails(string vapidSubject, string vapidPublicKey, string vapidPrivateKey)
        {
            if (string.IsNullOrEmpty(vapidSubject) || string.IsNullOrEmpty(vapidPublicKey) ||
                string.IsNullOrEmpty(vapidPrivateKey))
            {
                var vapidKeys = VapidHelper.GenerateVapidKeys();

                // Prints 2 URL Safe Base64 Encoded Strings
                Debug.WriteLine($"Public {vapidKeys.PublicKey}");
                Debug.WriteLine($"Private {vapidKeys.PrivateKey}");

                throw new Exception(
                          "You must set the Vapid:Subject, Vapid:PublicKey and Vapid:PrivateKey application settings or pass them to the service in the constructor. You can use the ones just printed to the debug console.");
            }
        }
Exemplo n.º 19
0
        public IActionResult GenerateKeys()
        {
            string userEmail = User.FindFirst("email")?.Value ?? "NoUser";

            // Todo: Replace with role based access
            if (userEmail.ToUpper() != Constants.AdminEmail.ToUpper())
            {
                return(RedirectToAction("Index", "Home"));
            }
            var keys = VapidHelper.GenerateVapidKeys();

            ViewBag.PublicKey  = keys.PublicKey;
            ViewBag.PrivateKey = keys.PrivateKey;
            return(View());
        }
Exemplo n.º 20
0
        public ActionResult Index()
        {
            var model           = new HomeModel();
            var pushInformation = PushInformation.Load(AppDomain.CurrentDomain.BaseDirectory + "../info.xml"); // 保存先はてきとうに

            if (pushInformation == null)                                                                       // VAPIDで使用する公開鍵を作成
            {
                pushInformation = new PushInformation();
                var vapidKeys = VapidHelper.GenerateVapidKeys();
                pushInformation.VapidPublic  = vapidKeys.PublicKey;
                pushInformation.VapipPrivate = vapidKeys.PrivateKey;
                PushInformation.Save(pushInformation, AppDomain.CurrentDomain.BaseDirectory + "../info.xml");                    // 作ったら保存しとく
            }
            model.VapidPublic = pushInformation.VapidPublic;
            model.Data        = Request.QueryString.Get("data");
            return(View(model));
        }
Exemplo n.º 21
0
        public async Task <IActionResult> CreateApplication(Application model)
        {
            IdentityUser usr = await _userManager.GetUserAsync(HttpContext.User);

            var keys = VapidHelper.GenerateVapidKeys();

            model.userId      = usr.Id;
            model.privateKey  = keys.PrivateKey;
            model.publicKey   = keys.PublicKey;
            model.createdAt   = System.DateTime.Now;
            model.lastUpdated = System.DateTime.Now;

            _dbContext.Add(model);
            await _dbContext.SaveChangesAsync();


            return(RedirectToAction(nameof(Index)));
        }
Exemplo n.º 22
0
        private VapidProvider()
        {
            var persistance = new VapidPersistanceProvider();

            var model = persistance.GetFromFile();

            if (model == null)
            {
                _vapidDetails = VapidHelper
                                .GenerateVapidKeys();

                persistance
                .SaveToFile(
                    _vapidDetails);
            }
            else
            {
                _vapidDetails = model;
            }
        }
        public void Send()
        {
            var subText = File.ReadAllText(filePath);
            var sub     = JsonConvert.DeserializeObject <SubscriptionModel>(subText);

            VapidDetails vapidKeys = VapidHelper.GenerateVapidKeys();
            var          subject   = "mailto:[email protected]";

            var subscription = new PushSubscription(sub.Endpoint, sub.Keys.P256dh, sub.Keys.Auth);
            var vapidDetails = new VapidDetails(subject, vapidKeys.PublicKey, vapidKeys.PrivateKey);

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, "payload", vapidDetails);
            }
            catch (WebPushException exception)
            {
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 24
0
        public IActionResult GenerateVapidKeys()
        {
            var vapidKeys = VapidHelper.GenerateVapidKeys();

            return(Ok(vapidKeys));
        }
Exemplo n.º 25
0
 private BAL()
 {
     _keys = VapidHelper.GenerateVapidKeys();
 }
Exemplo n.º 26
0
 private BALServicesM()
 {
     _keys = VapidHelper.GenerateVapidKeys();
 }