aboutsummaryrefslogtreecommitdiffstats
path: root/license-generator/src/bin/license.rs
blob: 859ddfac6c19406f5d4d0da1a55e474969de7894 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
///! FastCGI script that displays a thank-you page with a link to download a
///! custom-generated license.

extern crate aquatic_prime;
extern crate fastcgi;
extern crate exitcode;

#[macro_use]
extern crate log;
extern crate mysql;

#[macro_use]
extern crate serde_derive;

extern crate license_generator;

use std::borrow::Cow;
use std::io::{Cursor, Read, Write};

use aquatic_prime::AquaticPrime;

use license_generator::database;
use license_generator::errors::*;
use license_generator::logger;
use license_generator::params;
use license_generator::response;
use license_generator::zip;

#[derive(Serialize)]
struct LicenseData<'a> {
    #[serde(rename = "Name")]
    name: &'a str,

    #[serde(rename = "Email")]
    email: &'a str,
}

fn query_purchaser(
    cx: &mut mysql::PooledConn,
    name: &str,
    email: &str,
    secret: &str,
) -> Result<Option<std::result::Result<mysql::Row, mysql::Error>>> {
    let mut tx = cx.start_transaction(false, None, None)?;
    let row = tx.prep_exec("
        SELECT id FROM purchasers
        WHERE
            name = ?
        AND
            email = ?
        AND
            secret = ?",
        (
            &name,
            &email,
            &secret,
        )
    )?.next();

    tx.commit()?;

    Ok(row)
}

fn main() -> Result<()> {
    logger::init()?;

    let pool = match database::get_database_pool()
        .chain_err(|| "failed to create a database connection pool")
    {
        Ok(pool) => pool,
        Err(e) => {
            error!("{}", e);
            return Err(e);
        },
    };

    let public_key = include_str!("../../private/public_key.txt");
    let private_key = include_str!("../../private/private_key.txt");
    let aquatic_prime = AquaticPrime::new(&public_key, &private_key);

    fastcgi::run(move |mut req| {
        let mut params = String::new();
        match req.stdin().read_to_string(&mut params) {
            Ok(_) => (),
            Err(e) => error!("{}", e),
        }

        logger::log_request(&req, &params);

        let mut cx = match pool.get_conn() {
            Ok(cx) => cx,
            Err(e) => {
                return response::error_500(
                    &mut req.stdout(),
                    Some(e.into())
                );
            },
        };

        if let Some(path) = req.param("REQUEST_URI") {
            match path.as_ref() {
                "/license" => {
                    // Get params name, email, secret
                    // Render thank-you page with link to download file
                },

                // Respond with a zip archive of the license file
                "/license/download" => {
                    match req.param("REQUEST_METHOD") {
                        Some(method) => {
                            if method != "POST" {
                                return response::error_405(&mut req.stdout(), "POST");
                            }
                        },
                        None => {
                            return response::error_500(&mut req.stdout(), None);
                        },
                    };

                    let ps = params::parse(&params);
                    let name = ps.get("name");
                    let email = ps.get("email");
                    let secret = ps.get("secret");

                    if name.is_some() && email.is_some() && secret.is_some() {
                        let name = name.unwrap().to_string();
                        let email = email.unwrap().to_string();
                        let secret = secret.unwrap().to_string();

                        let purchaser = match query_purchaser(&mut cx, &name, &email, &secret) {
                            Ok(p) => p,
                            Err(e) => return response::error_500(
                                &mut req.stdout(),
                                Some(e.into())
                            ),
                        };

                        if let Some(purchaser) = purchaser {
                            match purchaser {
                                Ok(p) => p,
                                Err(e) => return response::error_500(
                                    &mut req.stdout(),
                                    Some(e.into())
                                ),
                            };

                            let license_data = LicenseData {
                                name: &name,
                                email: &email,
                            };

                            let license = match aquatic_prime.plist(license_data) {
                                Ok(p) => p,
                                Err(e) => return response::error_500(
                                    &mut req.stdout(),
                                    Some(e.into())
                                ),
                            };

                            let mut zip_data = Cursor::new(vec![]);
                            match zip::license(&mut zip_data, license.as_bytes()) {
                                Ok(p) => p,
                                Err(e) => return response::error_500(
                                    &mut req.stdout(),
                                    Some(e.into())
                                ),
                            }

                            write!(&mut req.stdout(), "Content-Type: application/zip
Content-Disposition: attachment; filename=\"dome-key-license.zip\"\n\n")
                                .and_then(|_|
                                    req.stdout().write_all(&zip_data.into_inner())
                                ).unwrap_or(());
                        } else {
                            return response::error_404(&mut req.stdout());
                        }
                    } else {
                        error!(
                            "Missing request parameters: name: '{}', email: '{}', secret: '{}'",
                            name.unwrap_or(&Cow::Borrowed("")),
                            email.unwrap_or(&Cow::Borrowed("")),
                            secret.unwrap_or(&Cow::Borrowed("")),
                        );

                        return response::error_400(&mut req.stdout());
                    }
                },
                _ => (),
            }
        }
    });

    Ok(())
}