summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorKjetil Orbekk <kjetil.orbekk@gmail.com>2017-06-17 22:31:27 -0400
committerKjetil Orbekk <kjetil.orbekk@gmail.com>2017-06-17 22:31:27 -0400
commit76b90acb735d3ed2b3052abc1d2403287af83619 (patch)
tree857de2ebee3d2b6ea802aa1ef249ea34bb0e0908 /src
parent1e5f237c20310cbf6ace17b6a7b05298429aca46 (diff)
rustfmt: Reformatted all the code.
Diffstat (limited to 'src')
-rw-r--r--src/auth/mod.rs5
-rw-r--r--src/bin/crypto.rs4
-rw-r--r--src/bin/main.rs20
-rw-r--r--src/db.rs28
-rw-r--r--src/render/mod.rs21
-rw-r--r--src/server.rs77
-rw-r--r--src/systemd/journal.rs5
-rw-r--r--src/systemd/unit.rs42
8 files changed, 104 insertions, 98 deletions
diff --git a/src/auth/mod.rs b/src/auth/mod.rs
index 7f995f8..2f4c313 100644
--- a/src/auth/mod.rs
+++ b/src/auth/mod.rs
@@ -11,11 +11,10 @@ pub struct HashedPassword {
// TODO: Configurable number of iterations.
pub fn encode(salt: &str, pw: &str) -> HashedPassword {
let mut enc = vec!(0; 32);
- let encrypted = bcrypt_pbkdf(pw.as_bytes(), salt.as_bytes(),
- 10, &mut enc);
+ let encrypted = bcrypt_pbkdf(pw.as_bytes(), salt.as_bytes(), 10, &mut enc);
HashedPassword {
salt: salt.to_string(),
- enc: base64::encode(&enc)
+ enc: base64::encode(&enc),
}
}
diff --git a/src/bin/crypto.rs b/src/bin/crypto.rs
index 5cc8549..775ea07 100644
--- a/src/bin/crypto.rs
+++ b/src/bin/crypto.rs
@@ -6,9 +6,7 @@ use crypto::bcrypt_pbkdf::bcrypt_pbkdf;
pub fn encode(pw: &str) -> Vec<u8> {
let salt = "hello";
let mut out = vec!(0; 32);
- let encrypted = bcrypt_pbkdf(
- pw.as_bytes(), salt.as_bytes(),
- 10, &mut out);
+ let encrypted = bcrypt_pbkdf(pw.as_bytes(), salt.as_bytes(), 10, &mut out);
out
}
diff --git a/src/bin/main.rs b/src/bin/main.rs
index ed9e179..245416c 100644
--- a/src/bin/main.rs
+++ b/src/bin/main.rs
@@ -21,12 +21,11 @@ fn create_user_prompt() -> Option<(String, String)> {
let mut user = String::new();
io::stdin().read_line(&mut user).unwrap();
let password = rpassword::prompt_password_stdout("Password: ").unwrap();
- let confirmation =
- rpassword::prompt_password_stdout("Repeat password: ").unwrap();
+ let confirmation = rpassword::prompt_password_stdout("Repeat password: ").unwrap();
if password != confirmation {
error!("Passwords don't match");
- return None
+ return None;
}
Some((user.trim().to_string(), password))
}
@@ -35,9 +34,7 @@ fn create_admin_user(conn: &rusqlite::Connection) {
info!("Create admin user");
if let Some((user, password)) = create_user_prompt() {
let enc = auth::encode("test_salt", password.as_str());
- systemhttp::db::insert_user(
- &conn, user.as_str(),
- &enc).expect("create user");
+ systemhttp::db::insert_user(&conn, user.as_str(), &enc).expect("create user");
}
}
@@ -67,8 +64,11 @@ fn main() {
.about("Add an admin user to the db"))
.get_matches();
- let port = matches.value_of("port").unwrap_or("8080")
- .parse::<u16>().expect("port number");
+ let port = matches
+ .value_of("port")
+ .unwrap_or("8080")
+ .parse::<u16>()
+ .expect("port number");
let db_file = matches.value_of("db_file").unwrap();
@@ -79,12 +79,12 @@ fn main() {
let mut context = systemhttp::server::Context {
base_url: "http://localhost:8080".to_string(),
- conn: conn
+ conn: conn,
};
match matches.subcommand_name() {
Some("serve") => serve(context, port),
Some("create_admin_user") => create_admin_user(&context.conn),
- x => panic!("Don't know about subcommand: {:?}", x)
+ x => panic!("Don't know about subcommand: {:?}", x),
}
}
diff --git a/src/db.rs b/src/db.rs
index ba4025f..872ae60 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -1,4 +1,4 @@
-use rusqlite::{Connection};
+use rusqlite::Connection;
use std;
use auth::HashedPassword;
@@ -19,25 +19,31 @@ pub fn init(conn: &mut Connection) -> Result<()> {
CREATE TABLE IF NOT EXISTS users
(username TEXT PRIMARY KEY, salt TEXT, passwd TEXT);
COMMIT;
- ").unwrap();
+ ")
+ .unwrap();
}
Ok(())
}
-pub fn insert_user(conn: &Connection,
- username: &str,
- password: &HashedPassword) -> Result<()> {
+pub fn insert_user(conn: &Connection, username: &str, password: &HashedPassword) -> Result<()> {
conn.execute("INSERT INTO users (username, salt, passwd)
VALUES (?1, ?2, ?3)",
- &[&username, &password.salt, &password.enc]).unwrap();
+ &[&username, &password.salt, &password.enc])
+ .unwrap();
Ok(())
}
-pub fn lookup_user(conn: &Connection,
- username: &str) -> Result<Option<HashedPassword>> {
- let mut stmt = conn.prepare("SELECT salt, passwd FROM users WHERE username = ?").unwrap();
+pub fn lookup_user(conn: &Connection, username: &str) -> Result<Option<HashedPassword>> {
+ let mut stmt = conn.prepare("SELECT salt, passwd FROM users WHERE username = ?")
+ .unwrap();
let result = stmt.query_map(&[&username], |row| {
- HashedPassword {salt: row.get(0), enc: row.get(1)}
- }).unwrap().map(|v| v.unwrap()).next();
+ HashedPassword {
+ salt: row.get(0),
+ enc: row.get(1),
+ }
+ })
+ .unwrap()
+ .map(|v| v.unwrap())
+ .next();
Ok(result)
}
diff --git a/src/render/mod.rs b/src/render/mod.rs
index fe0053a..b47ee55 100644
--- a/src/render/mod.rs
+++ b/src/render/mod.rs
@@ -5,14 +5,15 @@ use horrorshow::Raw;
#[derive(Debug)]
pub struct Renderer {
- pub user: Option<String>
+ pub user: Option<String>,
}
impl Renderer {
fn render_in_page<'a>(&self, content: Box<RenderBox + 'a>) -> String {
info!("Rendering page with context: {:?}", self);
let login_box: Box<RenderBox> = match self.user {
- Some(ref user) => box_html!{
+ Some(ref user) => {
+ box_html!{
: "Logged in as ";
: user;
: " (";
@@ -20,12 +21,15 @@ impl Renderer {
: "log out"
}
: ")";
- },
- None => box_html! {
+ }
+ }
+ None => {
+ box_html! {
a(href="login") { // TODO Get base url from context
: "Login"
}
}
+ }
};
(html!{
@@ -55,7 +59,9 @@ impl Renderer {
}
}
}
- }).into_string().unwrap()
+ })
+ .into_string()
+ .unwrap()
}
pub fn login_page(&self, is_retry: bool) -> String {
@@ -99,7 +105,7 @@ impl Renderer {
table {
tr {
th {
- : "Unit"
+ : "Unit"
}
th {
: "Active"
@@ -112,8 +118,7 @@ impl Renderer {
}
}
- pub fn system_status(&self, sections: &[(String, Vec<&unit::Unit>)])
- -> String {
+ pub fn system_status(&self, sections: &[(String, Vec<&unit::Unit>)]) -> String {
self.render_in_page(box_html! {
@ for &(ref type_, ref units) in sections {
h1 {
diff --git a/src/server.rs b/src/server.rs
index 3a03ea0..58027e9 100644
--- a/src/server.rs
+++ b/src/server.rs
@@ -1,5 +1,5 @@
use iron;
-use iron::error::{HttpResult};
+use iron::error::HttpResult;
use iron::headers::ContentType;
use iron::modifiers::{Header, Redirect};
use iron::status;
@@ -23,7 +23,7 @@ use auth;
#[derive(Debug)]
pub struct Context {
pub base_url: String,
- pub conn: Connection
+ pub conn: Connection,
}
impl iron::typemap::Key for Context {
type Value = Context;
@@ -42,7 +42,7 @@ impl iron_sessionstorage::Value for Login {
self.user
}
fn from_raw(v: String) -> Option<Self> {
- Some(Login{ user: v })
+ Some(Login { user: v })
}
}
@@ -51,12 +51,17 @@ fn overview(r: &mut Request) -> IronResult<Response> {
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 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()),
@@ -75,39 +80,29 @@ fn overview(r: &mut Request) -> IronResult<Response> {
}
fn journal(r: &mut Request) -> IronResult<Response> {
- let unit = iexpect!(r.extensions
- .get::<Router>()
- .unwrap()
- .find("unit"), status::BadRequest);
+ 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))));
+ return Ok(Response::with((status::BadRequest,
+ format!("Unit ({}) does not match {}", unit, re))));
}
- Ok(Response::with((status::Ok,
- itry!(journal::get_log(unit, 100)))))
+ 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 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))));
+ 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))))
+ Ok(Response::with((status::Ok, Header(ContentType::html()), renderer.unit_status(&unit, &log))))
}
fn get_logged_in_user(r: &mut Request) -> IronResult<Option<Login>> {
@@ -116,7 +111,7 @@ fn get_logged_in_user(r: &mut Request) -> IronResult<Option<Login>> {
// so we set the username to empty on logout.
if let &Some(Login { ref user }) = &login {
if user.is_empty() {
- return Ok(None)
+ return Ok(None);
}
}
Ok(login)
@@ -125,9 +120,7 @@ fn get_logged_in_user(r: &mut Request) -> IronResult<Option<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))))
+ Ok(Response::with((status::Ok, Header(ContentType::html()), renderer.login_page(is_retry))))
}
fn authenticate(r: &mut Request) -> IronResult<Response> {
@@ -135,11 +128,11 @@ fn authenticate(r: &mut Request) -> IronResult<Response> {
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)
+ _ => panic!("no username in params: {:?}", map),
};
let password = match map.get("password") {
Some(&Value::String(ref v)) => v,
- _ => panic!("no password in params: {:?}", map)
+ _ => panic!("no password in params: {:?}", map),
};
(user.to_string(), password.to_string())
};
@@ -151,12 +144,11 @@ fn authenticate(r: &mut Request) -> IronResult<Response> {
};
if let Some(true) = hash.map(|h| auth::validate(&password, &h)) {
- let login = Login{ user: user.to_string() }; // TODO Make a validated login type
+ 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))))
+ Ok(Response::with((status::Found, Redirect(url))))
} else {
login(r)
}
@@ -165,15 +157,12 @@ fn authenticate(r: &mut Request) -> IronResult<Response> {
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))))
+ 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
- })
+ Ok(render::Renderer { user: user })
}
pub fn serve(context: Context, port: u16) -> HttpResult<Listening> {
diff --git a/src/systemd/journal.rs b/src/systemd/journal.rs
index 86791ab..fa01c49 100644
--- a/src/systemd/journal.rs
+++ b/src/systemd/journal.rs
@@ -3,8 +3,7 @@ use std::io;
pub fn get_log(unit: &str, lines: i32) -> io::Result<String> {
let status = try!(Command::new("journalctl")
- .args(&["-u", unit,
- "-n", &lines.to_string()])
- .output());
+ .args(&["-u", unit, "-n", &lines.to_string()])
+ .output());
Ok(String::from_utf8_lossy(&status.stdout).into_owned())
}
diff --git a/src/systemd/unit.rs b/src/systemd/unit.rs
index 116ffdb..d43324a 100644
--- a/src/systemd/unit.rs
+++ b/src/systemd/unit.rs
@@ -14,31 +14,40 @@ pub struct Unit {
pub fn parse_key_value(line: &str) -> Option<(String, String)> {
let pos = line.find('=');
pos.map(|pos| {
- let (k, v) = line.split_at(pos);
- (k.to_owned(), v[1..].to_owned())
- })
+ let (k, v) = line.split_at(pos);
+ (k.to_owned(), v[1..].to_owned())
+ })
}
#[test]
fn test_parse_key_value() {
assert_eq!(None, parse_key_value("ab"));
- assert_eq!(Some(("a".to_owned(), "b".to_owned())), parse_key_value("a=b"));
- assert_eq!(Some(("a".to_owned(), "b=c".to_owned())), parse_key_value("a=b=c"));
+ assert_eq!(Some(("a".to_owned(), "b".to_owned())),
+ parse_key_value("a=b"));
+ assert_eq!(Some(("a".to_owned(), "b=c".to_owned())),
+ parse_key_value("a=b=c"));
}
fn make_unit(info: HashMap<String, String>) -> Option<Unit> {
fn from_id(id: &str) -> Option<String> {
id.rsplit('.').next().map(|t| t.to_owned())
};
- fn cloned(s: &String) -> String { s.clone() }
+ fn cloned(s: &String) -> String {
+ s.clone()
+ }
let id = info.get("Id").map(cloned);
let type_ = id.as_ref().and_then(|id| from_id(&id));
let active_state = info.get("ActiveState").map(cloned);
let sub_state = info.get("SubState").map(cloned);
-
+
if let (Some(id), Some(type_), Some(active_state), Some(sub_state)) =
(id, type_, active_state, sub_state) {
- Some(Unit { name: id, type_: type_, active_state: active_state, sub_state: sub_state })
+ Some(Unit {
+ name: id,
+ type_: type_,
+ active_state: active_state,
+ sub_state: sub_state,
+ })
} else {
None
}
@@ -47,13 +56,13 @@ fn make_unit(info: HashMap<String, String>) -> Option<Unit> {
#[test]
fn test_make_unit() {
let s = |s: &str| -> String { s.to_owned() };
- let info = [
- (s("Id"), s("Test.service")),
- (s("ActiveState"), s("active")),
- (s("SubState"), s("running")),
- ]
- .iter().cloned().collect::<HashMap<String, String>>();
- let actual = make_unit(info).unwrap();;
+ let info = [(s("Id"), s("Test.service")),
+ (s("ActiveState"), s("active")),
+ (s("SubState"), s("running"))]
+ .iter()
+ .cloned()
+ .collect::<HashMap<String, String>>();
+ let actual = make_unit(info).unwrap();
assert_eq!(s("Test.service"), actual.name);
let info = HashMap::new();
@@ -63,7 +72,8 @@ fn test_make_unit() {
pub fn get_units(filter: &str) -> io::Result<Vec<Unit>> {
let mut units = Vec::new();
let status = try!(Command::new("systemctl")
- .args(&["show", filter]).output());
+ .args(&["show", filter])
+ .output());
let mut unit_info = HashMap::new();
for line in String::from_utf8_lossy(&status.stdout).split('\n') {