user.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. use chrono::{NaiveDateTime, Utc};
  2. use serde_json::Value;
  3. use crate::crypto;
  4. use crate::CONFIG;
  5. db_object! {
  6. #[derive(Debug, Identifiable, Queryable, Insertable, AsChangeset)]
  7. #[table_name = "users"]
  8. #[changeset_options(treat_none_as_null="true")]
  9. #[primary_key(uuid)]
  10. pub struct User {
  11. pub uuid: String,
  12. pub created_at: NaiveDateTime,
  13. pub updated_at: NaiveDateTime,
  14. pub verified_at: Option<NaiveDateTime>,
  15. pub last_verifying_at: Option<NaiveDateTime>,
  16. pub login_verify_count: i32,
  17. pub email: String,
  18. pub email_new: Option<String>,
  19. pub email_new_token: Option<String>,
  20. pub name: String,
  21. pub password_hash: Vec<u8>,
  22. pub salt: Vec<u8>,
  23. pub password_iterations: i32,
  24. pub password_hint: Option<String>,
  25. pub akey: String,
  26. pub private_key: Option<String>,
  27. pub public_key: Option<String>,
  28. #[column_name = "totp_secret"] // Note, this is only added to the UserDb structs, not to User
  29. _totp_secret: Option<String>,
  30. pub totp_recover: Option<String>,
  31. pub security_stamp: String,
  32. pub equivalent_domains: String,
  33. pub excluded_globals: String,
  34. pub client_kdf_type: i32,
  35. pub client_kdf_iter: i32,
  36. }
  37. #[derive(Debug, Identifiable, Queryable, Insertable)]
  38. #[table_name = "invitations"]
  39. #[primary_key(email)]
  40. pub struct Invitation {
  41. pub email: String,
  42. }
  43. }
  44. enum UserStatus {
  45. Enabled = 0,
  46. Invited = 1,
  47. _Disabled = 2,
  48. }
  49. /// Local methods
  50. impl User {
  51. pub const CLIENT_KDF_TYPE_DEFAULT: i32 = 0; // PBKDF2: 0
  52. pub const CLIENT_KDF_ITER_DEFAULT: i32 = 100_000;
  53. pub fn new(mail: String) -> Self {
  54. let now = Utc::now().naive_utc();
  55. let email = mail.to_lowercase();
  56. Self {
  57. uuid: crate::util::get_uuid(),
  58. created_at: now,
  59. updated_at: now,
  60. verified_at: None,
  61. last_verifying_at: None,
  62. login_verify_count: 0,
  63. name: email.clone(),
  64. email,
  65. akey: String::new(),
  66. email_new: None,
  67. email_new_token: None,
  68. password_hash: Vec::new(),
  69. salt: crypto::get_random_64(),
  70. password_iterations: CONFIG.password_iterations(),
  71. security_stamp: crate::util::get_uuid(),
  72. password_hint: None,
  73. private_key: None,
  74. public_key: None,
  75. _totp_secret: None,
  76. totp_recover: None,
  77. equivalent_domains: "[]".to_string(),
  78. excluded_globals: "[]".to_string(),
  79. client_kdf_type: Self::CLIENT_KDF_TYPE_DEFAULT,
  80. client_kdf_iter: Self::CLIENT_KDF_ITER_DEFAULT,
  81. }
  82. }
  83. pub fn check_valid_password(&self, password: &str) -> bool {
  84. crypto::verify_password_hash(
  85. password.as_bytes(),
  86. &self.salt,
  87. &self.password_hash,
  88. self.password_iterations as u32,
  89. )
  90. }
  91. pub fn check_valid_recovery_code(&self, recovery_code: &str) -> bool {
  92. if let Some(ref totp_recover) = self.totp_recover {
  93. crate::crypto::ct_eq(recovery_code, totp_recover.to_lowercase())
  94. } else {
  95. false
  96. }
  97. }
  98. pub fn set_password(&mut self, password: &str) {
  99. self.password_hash = crypto::hash_password(password.as_bytes(), &self.salt, self.password_iterations as u32);
  100. }
  101. pub fn reset_security_stamp(&mut self) {
  102. self.security_stamp = crate::util::get_uuid();
  103. }
  104. }
  105. use super::{Cipher, Device, Folder, TwoFactor, UserOrgType, UserOrganization};
  106. use crate::db::DbConn;
  107. use crate::api::EmptyResult;
  108. use crate::error::MapResult;
  109. /// Database methods
  110. impl User {
  111. pub fn to_json(&self, conn: &DbConn) -> Value {
  112. let orgs = UserOrganization::find_by_user(&self.uuid, conn);
  113. let orgs_json: Vec<Value> = orgs.iter().map(|c| c.to_json(&conn)).collect();
  114. let twofactor_enabled = !TwoFactor::find_by_user(&self.uuid, conn).is_empty();
  115. // TODO: Might want to save the status field in the DB
  116. let status = if self.password_hash.is_empty() {
  117. UserStatus::Invited
  118. } else {
  119. UserStatus::Enabled
  120. };
  121. json!({
  122. "_Status": status as i32,
  123. "Id": self.uuid,
  124. "Name": self.name,
  125. "Email": self.email,
  126. "EmailVerified": !CONFIG.mail_enabled() || self.verified_at.is_some(),
  127. "Premium": true,
  128. "MasterPasswordHint": self.password_hint,
  129. "Culture": "en-US",
  130. "TwoFactorEnabled": twofactor_enabled,
  131. "Key": self.akey,
  132. "PrivateKey": self.private_key,
  133. "SecurityStamp": self.security_stamp,
  134. "Organizations": orgs_json,
  135. "Object": "profile"
  136. })
  137. }
  138. pub fn save(&mut self, conn: &DbConn) -> EmptyResult {
  139. if self.email.trim().is_empty() {
  140. err!("User email can't be empty")
  141. }
  142. self.updated_at = Utc::now().naive_utc();
  143. db_run! {conn:
  144. sqlite, mysql {
  145. diesel::replace_into(users::table) // Insert or update
  146. .values(&UserDb::to_db(self))
  147. .execute(conn)
  148. .map_res("Error saving user")
  149. }
  150. postgresql {
  151. let value = UserDb::to_db(self);
  152. diesel::insert_into(users::table) // Insert or update
  153. .values(&value)
  154. .on_conflict(users::uuid)
  155. .do_update()
  156. .set(&value)
  157. .execute(conn)
  158. .map_res("Error saving user")
  159. }
  160. }
  161. }
  162. pub fn delete(self, conn: &DbConn) -> EmptyResult {
  163. for user_org in UserOrganization::find_by_user(&self.uuid, conn) {
  164. if user_org.atype == UserOrgType::Owner {
  165. let owner_type = UserOrgType::Owner as i32;
  166. if UserOrganization::find_by_org_and_type(&user_org.org_uuid, owner_type, conn).len() <= 1 {
  167. err!("Can't delete last owner")
  168. }
  169. }
  170. }
  171. UserOrganization::delete_all_by_user(&self.uuid, conn)?;
  172. Cipher::delete_all_by_user(&self.uuid, conn)?;
  173. Folder::delete_all_by_user(&self.uuid, conn)?;
  174. Device::delete_all_by_user(&self.uuid, conn)?;
  175. TwoFactor::delete_all_by_user(&self.uuid, conn)?;
  176. Invitation::take(&self.email, conn); // Delete invitation if any
  177. db_run! {conn: {
  178. diesel::delete(users::table.filter(users::uuid.eq(self.uuid)))
  179. .execute(conn)
  180. .map_res("Error deleting user")
  181. }}
  182. }
  183. pub fn update_uuid_revision(uuid: &str, conn: &DbConn) {
  184. if let Err(e) = Self::_update_revision(uuid, &Utc::now().naive_utc(), conn) {
  185. warn!("Failed to update revision for {}: {:#?}", uuid, e);
  186. }
  187. }
  188. pub fn update_all_revisions(conn: &DbConn) -> EmptyResult {
  189. let updated_at = Utc::now().naive_utc();
  190. db_run! {conn: {
  191. crate::util::retry(|| {
  192. diesel::update(users::table)
  193. .set(users::updated_at.eq(updated_at))
  194. .execute(conn)
  195. }, 10)
  196. .map_res("Error updating revision date for all users")
  197. }}
  198. }
  199. pub fn update_revision(&mut self, conn: &DbConn) -> EmptyResult {
  200. self.updated_at = Utc::now().naive_utc();
  201. Self::_update_revision(&self.uuid, &self.updated_at, conn)
  202. }
  203. fn _update_revision(uuid: &str, date: &NaiveDateTime, conn: &DbConn) -> EmptyResult {
  204. db_run! {conn: {
  205. crate::util::retry(|| {
  206. diesel::update(users::table.filter(users::uuid.eq(uuid)))
  207. .set(users::updated_at.eq(date))
  208. .execute(conn)
  209. }, 10)
  210. .map_res("Error updating user revision")
  211. }}
  212. }
  213. pub fn find_by_mail(mail: &str, conn: &DbConn) -> Option<Self> {
  214. let lower_mail = mail.to_lowercase();
  215. db_run! {conn: {
  216. users::table
  217. .filter(users::email.eq(lower_mail))
  218. .first::<UserDb>(conn)
  219. .ok()
  220. .from_db()
  221. }}
  222. }
  223. pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
  224. db_run! {conn: {
  225. users::table.filter(users::uuid.eq(uuid)).first::<UserDb>(conn).ok().from_db()
  226. }}
  227. }
  228. pub fn get_all(conn: &DbConn) -> Vec<Self> {
  229. db_run! {conn: {
  230. users::table.load::<UserDb>(conn).expect("Error loading users").from_db()
  231. }}
  232. }
  233. }
  234. impl Invitation {
  235. pub const fn new(email: String) -> Self {
  236. Self { email }
  237. }
  238. pub fn save(&self, conn: &DbConn) -> EmptyResult {
  239. if self.email.trim().is_empty() {
  240. err!("Invitation email can't be empty")
  241. }
  242. db_run! {conn:
  243. sqlite, mysql {
  244. diesel::replace_into(invitations::table)
  245. .values(InvitationDb::to_db(self))
  246. .execute(conn)
  247. .map_res("Error saving invitation")
  248. }
  249. postgresql {
  250. diesel::insert_into(invitations::table)
  251. .values(InvitationDb::to_db(self))
  252. .on_conflict(invitations::email)
  253. .do_nothing()
  254. .execute(conn)
  255. .map_res("Error saving invitation")
  256. }
  257. }
  258. }
  259. pub fn delete(self, conn: &DbConn) -> EmptyResult {
  260. db_run! {conn: {
  261. diesel::delete(invitations::table.filter(invitations::email.eq(self.email)))
  262. .execute(conn)
  263. .map_res("Error deleting invitation")
  264. }}
  265. }
  266. pub fn find_by_mail(mail: &str, conn: &DbConn) -> Option<Self> {
  267. let lower_mail = mail.to_lowercase();
  268. db_run! {conn: {
  269. invitations::table
  270. .filter(invitations::email.eq(lower_mail))
  271. .first::<InvitationDb>(conn)
  272. .ok()
  273. .from_db()
  274. }}
  275. }
  276. pub fn take(mail: &str, conn: &DbConn) -> bool {
  277. match Self::find_by_mail(mail, &conn) {
  278. Some(invitation) => invitation.delete(&conn).is_ok(),
  279. None => false,
  280. }
  281. }
  282. }