2016-11-21 10:45:54 +03:00
|
|
|
use adm::result::Error;
|
|
|
|
use diesel::{insert, update};
|
|
|
|
use diesel::pg::PgConnection;
|
|
|
|
use diesel::prelude::*;
|
|
|
|
use djangohashers::make_password;
|
|
|
|
use rand::distributions::IndependentSample;
|
|
|
|
use rand::distributions::range::Range;
|
|
|
|
use rand::os::OsRng;
|
|
|
|
use std::iter::Iterator;
|
|
|
|
|
|
|
|
pub fn list(db: &PgConnection) -> Result<(), Error> {
|
2017-09-02 02:05:44 +04:00
|
|
|
use schema::users::dsl::*;
|
2017-11-09 00:17:42 +04:00
|
|
|
println!(
|
|
|
|
"Existing users: {:?}.",
|
2017-11-09 03:06:12 +04:00
|
|
|
users.select(username).load::<String>(db)?,
|
2017-11-09 00:17:42 +04:00
|
|
|
);
|
2016-11-21 10:45:54 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn passwd(db: &PgConnection, uname: &str) -> Result<(), Error> {
|
|
|
|
let pword = random_password(14);
|
|
|
|
let hashword = make_password(&pword);
|
2017-09-02 02:05:44 +04:00
|
|
|
use schema::users::dsl::*;
|
2017-05-09 00:01:59 +04:00
|
|
|
match update(users.filter(username.eq(&uname)))
|
2016-11-21 10:45:54 +03:00
|
|
|
.set(password.eq(&hashword))
|
2017-11-09 00:17:42 +04:00
|
|
|
.execute(db)?
|
|
|
|
{
|
2016-11-21 10:45:54 +03:00
|
|
|
1 => {
|
|
|
|
println!("Updated password for {:?} to {:?}", uname, pword);
|
|
|
|
}
|
|
|
|
0 => {
|
2017-09-02 02:05:44 +04:00
|
|
|
use models::NewUser;
|
2017-11-09 00:17:42 +04:00
|
|
|
insert(&NewUser { username: uname, password: &hashword })
|
2016-11-21 10:45:54 +03:00
|
|
|
.into(users)
|
2017-05-09 00:01:59 +04:00
|
|
|
.execute(db)?;
|
2016-11-21 10:45:54 +03:00
|
|
|
println!("Created user {:?} with password {:?}", uname, pword);
|
|
|
|
}
|
|
|
|
n => {
|
2017-11-09 00:17:42 +04:00
|
|
|
println!(
|
|
|
|
"Strange, updated {} passwords for {:?} to {:?}",
|
|
|
|
n,
|
|
|
|
uname,
|
2017-11-09 03:06:12 +04:00
|
|
|
pword,
|
2017-11-09 00:17:42 +04:00
|
|
|
);
|
2016-11-21 10:45:54 +03:00
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn random_password(len: usize) -> String {
|
|
|
|
let rng = &mut OsRng::new().expect("Init rng");
|
2017-09-27 02:19:03 +04:00
|
|
|
let nlc = b'z' - b'a' + 1;
|
2016-11-21 10:45:54 +03:00
|
|
|
let x = Range::new(0, 6 * nlc + 4 * 10 + 1);
|
|
|
|
(0..len)
|
2017-02-04 21:12:13 +04:00
|
|
|
.map(|_| match x.ind_sample(rng) {
|
2017-09-27 02:19:03 +04:00
|
|
|
n if n < (1 * nlc) => (b'A' + (n % nlc)) as char,
|
|
|
|
n if n < (6 * nlc) => (b'a' + (n % nlc)) as char,
|
|
|
|
n => (b'0' + n % 10) as char,
|
2016-11-21 10:45:54 +03:00
|
|
|
})
|
|
|
|
.collect()
|
|
|
|
}
|