user_management.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. use crate::{schema,user};
  2. use microrm::prelude::*;
  3. pub fn list(realm: &str, db: microrm::DB) {
  4. // get realm ID
  5. let qi = db.query_interface();
  6. let realm_id = qi.get().by(schema::Realm::Shortname, realm).one().expect("couldn't query db").expect("No such realm").id();
  7. let users = qi.get().by(schema::User::Realm, &realm_id).all().expect("couldn't query db");
  8. println!("User list ({} users):", users.len());
  9. for user in &users {
  10. println!("- {:20}", user.username);
  11. let auth_challenges = qi.get().by(schema::AuthChallenge::User, &user.id()).all().expect("Can't get authentication challenges?");
  12. for ch in &auth_challenges {
  13. println!(" - Has {:?} authentication challenge", ch.challenge_type);
  14. }
  15. }
  16. }
  17. pub fn create(realm: &str, db: microrm::DB, username: &str) {
  18. // get realm ID
  19. let qi = db.query_interface();
  20. let realm_id = qi.get().by(schema::Realm::Shortname, realm).one().expect("couldn't query db").expect("No such realm").id();
  21. // check that the user doesn't exist already
  22. let existing_user = qi.get().by(schema::User::Realm, &realm_id).by(schema::User::Username, &username).one().expect("couldn't query db");
  23. if existing_user.is_some() {
  24. log::error!("Can't create user {} in {} realm as a user with that username already exists", username, realm);
  25. return;
  26. }
  27. qi.add(&schema::User { realm: realm_id, username: username.to_owned() }).expect("couldn't add user");
  28. }
  29. pub fn change_auth(realm: &str, db: microrm::DB, username: &str, change_password: bool) {
  30. // get realm ID
  31. let qi = db.query_interface();
  32. let realm_id = qi.get().by(schema::Realm::Shortname, realm).one().expect("couldn't query db").expect("No such realm").id();
  33. // check that the user exists
  34. let existing_user = qi.get().by(schema::User::Realm, &realm_id).by(schema::User::Username, &username).one().expect("couldn't query db");
  35. if existing_user.is_none() {
  36. log::error!("User {} does not exist in the {} realm!", username, realm);
  37. return;
  38. }
  39. let user = user::User::from_model(existing_user.unwrap());
  40. if change_password {
  41. let raw_pass = rpassword::prompt_password("Enter new user password: ").unwrap();
  42. user.set_new_password(&qi, raw_pass.as_bytes());
  43. }
  44. }