diff --git a/src/config.rs b/src/config.rs index fb9c7d1..75aa351 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,7 +23,7 @@ pub struct MiscSettings { } #[derive(Deserialize)] -pub struct User { +pub struct ConfigUser { pub name: String, pub password: String, } @@ -33,7 +33,7 @@ pub struct UserConfig { pub album_art_pattern: Option, pub reindex_every_n_seconds: Option, pub mount_dirs: Option>, - pub users: Option>, + pub users: Option>, pub ydns: Option, } @@ -94,7 +94,7 @@ pub fn ammend(db: &T, new_config: &UserConfig) -> Result<()> if let Some(ref config_users) = new_config.users { for config_user in config_users { - let new_user = NewUser::new(&config_user.name, &config_user.password); + let new_user = User::new(&config_user.name, &config_user.password); diesel::insert(&new_user) .into(users::table) .execute(connection)?; diff --git a/src/user.rs b/src/user.rs index 547d819..d06abad 100644 --- a/src/user.rs +++ b/src/user.rs @@ -7,28 +7,9 @@ use db::ConnectionSource; use db::users; use errors::*; -#[derive(Debug, Queryable)] -pub struct User { - id: i32, - pub name: String, - pub password_salt: Vec, - pub password_hash: Vec, -} - -impl User { - pub fn verify_password(&self, attempted_password: &str) -> bool { - pbkdf2::verify(DIGEST_ALG, - HASH_ITERATIONS, - &self.password_salt, - attempted_password.as_bytes(), - &self.password_hash) - .is_ok() - } -} - -#[derive(Debug, Insertable)] +#[derive(Debug, Insertable, Queryable)] #[table_name="users"] -pub struct NewUser { +pub struct User { pub name: String, pub password_salt: Vec, pub password_hash: Vec, @@ -39,18 +20,27 @@ const CREDENTIAL_LEN: usize = digest::SHA256_OUTPUT_LEN; const HASH_ITERATIONS: u32 = 10000; type PasswordHash = [u8; CREDENTIAL_LEN]; -impl NewUser { - pub fn new(name: &str, password: &str) -> NewUser { +impl User { + pub fn new(name: &str, password: &str) -> User { let salt = rand::random::<[u8; 16]>().to_vec(); - let hash = NewUser::hash_password(&salt, password); - NewUser { + let hash = User::hash_password(&salt, password); + User { name: name.to_owned(), password_salt: salt, password_hash: hash, } } - pub fn hash_password(salt: &Vec, password: &str) -> Vec { + pub fn verify_password(&self, attempted_password: &str) -> bool { + pbkdf2::verify(DIGEST_ALG, + HASH_ITERATIONS, + &self.password_salt, + attempted_password.as_bytes(), + &self.password_hash) + .is_ok() + } + + fn hash_password(salt: &Vec, password: &str) -> Vec { let mut hash: PasswordHash = [0; CREDENTIAL_LEN]; pbkdf2::derive(DIGEST_ALG, HASH_ITERATIONS, @@ -68,6 +58,9 @@ pub fn auth(db: &T, username: &str, password: &str) -> Result let connection = db.get_connection(); let connection = connection.lock().unwrap(); let connection = connection.deref(); - let user: User = users.filter(name.eq(username)).get_result(connection)?; + let user: User = users + .select((name, password_hash, password_salt)) + .filter(name.eq(username)) + .get_result(connection)?; Ok(user.verify_password(password)) }