summaryrefslogtreecommitdiff
path: root/src/server.rs
blob: 58027e9100eb1f5a1e3f819c916ae766cbfeb1cd (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
use iron;
use iron::error::HttpResult;
use iron::headers::ContentType;
use iron::modifiers::{Header, Redirect};
use iron::status;
use iron::{Iron, IronError, Request, IronResult, Response, Chain, Listening, Plugin, Url};
use iron_sessionstorage::SessionStorage;
use iron_sessionstorage::backends::SignedCookieBackend;
use iron_sessionstorage::traits::*;
use iron_sessionstorage;
use params::{Params, Value};
use regex::Regex;
use render;
use router::Router;
use staticfile::Static;
use systemd::journal;
use systemd::unit;
use persistent::Write;
use rusqlite::Connection;
use db;
use auth;

#[derive(Debug)]
pub struct Context {
    pub base_url: String,
    pub conn: Connection,
}
impl iron::typemap::Key for Context {
    type Value = Context;
}

#[derive(Default, Debug, Clone)]
struct Login {
    user: String,
}

impl iron_sessionstorage::Value for Login {
    fn get_key() -> &'static str {
        "login"
    }
    fn into_raw(self) -> String {
        self.user
    }
    fn from_raw(v: String) -> Option<Self> {
        Some(Login { user: v })
    }
}

fn overview(r: &mut Request) -> IronResult<Response> {
    let mut _value = try!(r.session().get::<Login>());

    let units = unit::get_units("*").unwrap();

    let sections = ["service", "timer", "socket", "target", "slice", "mount", "path"];
    let units_by_section = sections
        .iter()
        .map(|&s| {
                 (s.to_owned(),
                  units
                      .iter()
                      .filter(|&u| &u.type_ == s)
                      .collect::<Vec<&unit::Unit>>())
             })
        .collect::<Vec<_>>();

    // let res = Ok(Response::with((status::Ok,
    //                              Header(ContentType::html()),
    //                              render_message(&format!("Hello, {} ({})",
    //                                                      name,
    //                                                      session_value.0),
    //                                             &units))));

    // info!("Updating session value. Current value: {}", session_value.0);
    // session_value.0.push('a');
    // try!(r.session().set(session_value));
    let renderer = make_renderer(r)?;
    Ok(Response::with((status::Ok,
                       Header(ContentType::html()),
                       renderer.system_status(&units_by_section))))
}

fn journal(r: &mut Request) -> IronResult<Response> {
    let unit = iexpect!(r.extensions.get::<Router>().unwrap().find("unit"),
                        status::BadRequest);
    let re = Regex::new(r"[-_\w\d]*").unwrap();
    if !re.is_match(unit) {
        return Ok(Response::with((status::BadRequest,
                                  format!("Unit ({}) does not match {}", unit, re))));
    }
    Ok(Response::with((status::Ok, itry!(journal::get_log(unit, 100)))))
}

fn unit_status(r: &mut Request) -> IronResult<Response> {
    let unit_name = iexpect!(r.extensions.get::<Router>().unwrap().find("unit"),
                             status::BadRequest)
            .to_string();
    let re = Regex::new(r"[-_\w\d]*").unwrap();
    if !re.is_match(&unit_name) {
        return Ok(Response::with((status::BadRequest,
                                  format!("Unit ({}) does not match {}", unit_name, re))));
    }
    let ref unit = itry!(unit::get_units(&unit_name))[0];
    let log = itry!(journal::get_log(&unit_name, 15));
    let renderer = make_renderer(r)?;
    Ok(Response::with((status::Ok, Header(ContentType::html()), renderer.unit_status(&unit, &log))))
}

fn get_logged_in_user(r: &mut Request) -> IronResult<Option<Login>> {
    let login = r.session().get::<Login>()?;
    // Session storage doesn't have a way to delete its cookie,
    // so we set the username to empty on logout.
    if let &Some(Login { ref user }) = &login {
        if user.is_empty() {
            return Ok(None);
        }
    }
    Ok(login)
}

fn login(r: &mut Request) -> IronResult<Response> {
    let renderer = make_renderer(r)?;
    let is_retry = r.method == iron::method::Method::Post;
    Ok(Response::with((status::Ok, Header(ContentType::html()), renderer.login_page(is_retry))))
}

fn authenticate(r: &mut Request) -> IronResult<Response> {
    let (user, password) = {
        let map = r.get_ref::<Params>().unwrap();
        let user = match map.get("username") {
            Some(&Value::String(ref v)) => v,
            _ => panic!("no username in params: {:?}", map),
        };
        let password = match map.get("password") {
            Some(&Value::String(ref v)) => v,
            _ => panic!("no password in params: {:?}", map),
        };
        (user.to_string(), password.to_string())
    };

    let hash = {
        let mutex = r.get::<Write<Context>>().unwrap();
        let context = mutex.lock().unwrap();
        db::lookup_user(&context.conn, &user).unwrap()
    };

    if let Some(true) = hash.map(|h| auth::validate(&password, &h)) {
        let login = Login { user: user.to_string() }; // TODO Make a validated login type
        info!("User logged in: {:?}", login);
        r.session().set(login)?;
        let url = Url::parse("http://localhost:8080/").unwrap();
        Ok(Response::with((status::Found, Redirect(url))))
    } else {
        login(r)
    }
}

fn logout(r: &mut Request) -> IronResult<Response> {
    r.session().set::<Login>(Default::default());
    let url = Url::parse("http://localhost:8080/").unwrap();
    Ok(Response::with((status::Found, Redirect(url))))
}

fn make_renderer(r: &mut Request) -> IronResult<render::Renderer> {
    let user = get_logged_in_user(r)?.map(|u| u.user);
    Ok(render::Renderer { user: user })
}

pub fn serve(context: Context, port: u16) -> HttpResult<Listening> {
    // TODO: Use a real secret.
    let secret = b"secret2".to_vec();
    let router = router!(
        root: get "/" => overview,
        login: get "/login" => login,
        authenticate: post "/login" => authenticate,
        logout: get "/logout" => logout,
        details: get "/status/:unit" => unit_status,
        journal: get "/journal/:unit" => journal,
        css: get "/static/main.css" => Static::new(""),
    );
    let mut chain = Chain::new(router);
    chain.link_around(SessionStorage::new(SignedCookieBackend::new(secret)));
    chain.link(Write::<Context>::both(context));
    let bind_address = format!("{}:{}", "::", port);
    Iron::new(chain).http(bind_address.as_str())
}