summaryrefslogtreecommitdiff
path: root/src/push/handlers/mod.rs
blob: afa76e07afab08113f371d687787148d23f824b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::env;

use axum::{
    extract::{Json},
};

use web_push::{
    SubscriptionInfo,
    VapidSignatureBuilder,
    WebPushMessageBuilder,
    ContentEncoding,
    WebPushClient,
    IsahcWebPushClient,
};


pub async fn vapid() -> String {
    let vapid_public_key = env::var("VAPID_PUBLIC_KEY").unwrap_or_default();
    String::from(vapid_public_key)
}


pub async fn register() -> String {
    String::from("OK")
}


pub async fn unregister() -> String {
    String::from("OK")
}


#[axum::debug_handler]
pub async fn echo(
    Json(echo): Json<Echo>,
) -> Result<(), crate::error::Internal> {
    // Look this up from a subscription record? Or get it from the client and trust?
    let endpoint = echo.endpoint;
    // Get these from client:
    let p256dh = echo.keys.p256dh;
    let auth = echo.keys.auth;

    println!("endpoint: {:?}", endpoint);
    println!("p256dh: {:?}", p256dh);
    println!("auth: {:?}", auth);

    // You would likely get this by deserializing a browser `pushSubscription` object.
    let subscription_info = SubscriptionInfo::new(endpoint, p256dh, auth);

    // This will need to come from the DB eventually.
    let private_key = String::from(env::var("VAPID_PRIVATE_KEY").unwrap_or_default());
    let sig_builder = VapidSignatureBuilder::from_base64(&private_key, &subscription_info)?.build()?;

    // Now add payload and encrypt.
    let mut builder = WebPushMessageBuilder::new(&subscription_info);
    // Eventually, this message will be something other than an echo:
    let content = echo.msg.as_bytes();
    builder.set_payload(ContentEncoding::Aes128Gcm, content);
    builder.set_vapid_signature(sig_builder);

    let client = IsahcWebPushClient::new()?;

    // Finally, send the notification!
    client.send(builder.build()?).await?;
    // Fix up return type?
    Ok(())
}


#[derive(serde::Deserialize)]
pub struct Keys {
    pub p256dh: String,
    pub auth: String,
}

#[derive(serde::Deserialize)]
pub struct Echo {
    pub msg: String,
    pub endpoint: String,
    pub expirationTime: Option<String>,
    pub keys: Keys,
}