organizations.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. #![allow(unused_imports)]
  2. use rocket_contrib::{Json, Value};
  3. use db::DbConn;
  4. use db::models::*;
  5. use api::{PasswordData, JsonResult, EmptyResult, NumberOrString, JsonUpcase};
  6. use auth::{Headers, AdminHeaders, OwnerHeaders};
  7. #[derive(Deserialize)]
  8. #[allow(non_snake_case)]
  9. struct OrgData {
  10. BillingEmail: String,
  11. CollectionName: String,
  12. Key: String,
  13. Name: String,
  14. #[serde(rename = "PlanType")]
  15. _PlanType: String, // Ignored, always use the same plan
  16. }
  17. #[derive(Deserialize, Debug)]
  18. #[allow(non_snake_case)]
  19. struct OrganizationUpdateData {
  20. BillingEmail: String,
  21. Name: String,
  22. }
  23. #[derive(Deserialize, Debug)]
  24. #[allow(non_snake_case)]
  25. struct NewCollectionData {
  26. Name: String,
  27. }
  28. #[post("/organizations", data = "<data>")]
  29. fn create_organization(headers: Headers, data: JsonUpcase<OrgData>, conn: DbConn) -> JsonResult {
  30. let data: OrgData = data.into_inner().data;
  31. let mut org = Organization::new(data.Name, data.BillingEmail);
  32. let mut user_org = UserOrganization::new(
  33. headers.user.uuid.clone(), org.uuid.clone());
  34. let mut collection = Collection::new(
  35. org.uuid.clone(), data.CollectionName);
  36. user_org.key = data.Key;
  37. user_org.access_all = true;
  38. user_org.type_ = UserOrgType::Owner as i32;
  39. user_org.status = UserOrgStatus::Confirmed as i32;
  40. org.save(&conn);
  41. user_org.save(&conn);
  42. collection.save(&conn);
  43. Ok(Json(org.to_json()))
  44. }
  45. #[post("/organizations/<org_id>/delete", data = "<data>")]
  46. fn delete_organization(org_id: String, data: JsonUpcase<PasswordData>, headers: OwnerHeaders, conn: DbConn) -> EmptyResult {
  47. let data: PasswordData = data.into_inner().data;
  48. let password_hash = data.MasterPasswordHash;
  49. if !headers.user.check_valid_password(&password_hash) {
  50. err!("Invalid password")
  51. }
  52. match Organization::find_by_uuid(&org_id, &conn) {
  53. None => err!("Organization not found"),
  54. Some(org) => match org.delete(&conn) {
  55. Ok(()) => Ok(()),
  56. Err(_) => err!("Failed deleting the organization")
  57. }
  58. }
  59. }
  60. #[get("/organizations/<org_id>")]
  61. fn get_organization(org_id: String, _headers: OwnerHeaders, conn: DbConn) -> JsonResult {
  62. match Organization::find_by_uuid(&org_id, &conn) {
  63. Some(organization) => Ok(Json(organization.to_json())),
  64. None => err!("Can't find organization details")
  65. }
  66. }
  67. #[post("/organizations/<org_id>", data = "<data>")]
  68. fn post_organization(org_id: String, _headers: OwnerHeaders, data: JsonUpcase<OrganizationUpdateData>, conn: DbConn) -> JsonResult {
  69. let data: OrganizationUpdateData = data.into_inner().data;
  70. let mut org = match Organization::find_by_uuid(&org_id, &conn) {
  71. Some(organization) => organization,
  72. None => err!("Can't find organization details")
  73. };
  74. org.name = data.Name;
  75. org.billing_email = data.BillingEmail;
  76. org.save(&conn);
  77. Ok(Json(org.to_json()))
  78. }
  79. // GET /api/collections?writeOnly=false
  80. #[get("/collections")]
  81. fn get_user_collections(headers: Headers, conn: DbConn) -> JsonResult {
  82. Ok(Json(json!({
  83. "Data":
  84. Collection::find_by_user_uuid(&headers.user.uuid, &conn)
  85. .iter()
  86. .map(|collection| {
  87. collection.to_json()
  88. }).collect::<Value>(),
  89. "Object": "list"
  90. })))
  91. }
  92. #[get("/organizations/<org_id>/collections")]
  93. fn get_org_collections(org_id: String, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
  94. Ok(Json(json!({
  95. "Data":
  96. Collection::find_by_organization(&org_id, &conn)
  97. .iter()
  98. .map(|collection| {
  99. collection.to_json()
  100. }).collect::<Value>(),
  101. "Object": "list"
  102. })))
  103. }
  104. #[post("/organizations/<org_id>/collections", data = "<data>")]
  105. fn post_organization_collections(org_id: String, _headers: AdminHeaders, data: JsonUpcase<NewCollectionData>, conn: DbConn) -> JsonResult {
  106. let data: NewCollectionData = data.into_inner().data;
  107. let org = match Organization::find_by_uuid(&org_id, &conn) {
  108. Some(organization) => organization,
  109. None => err!("Can't find organization details")
  110. };
  111. let mut collection = Collection::new(org.uuid.clone(), data.Name);
  112. collection.save(&conn);
  113. Ok(Json(collection.to_json()))
  114. }
  115. #[post("/organizations/<org_id>/collections/<col_id>", data = "<data>")]
  116. fn post_organization_collection_update(org_id: String, col_id: String, _headers: AdminHeaders, data: JsonUpcase<NewCollectionData>, conn: DbConn) -> JsonResult {
  117. let data: NewCollectionData = data.into_inner().data;
  118. let org = match Organization::find_by_uuid(&org_id, &conn) {
  119. Some(organization) => organization,
  120. None => err!("Can't find organization details")
  121. };
  122. let mut collection = match Collection::find_by_uuid(&col_id, &conn) {
  123. Some(collection) => collection,
  124. None => err!("Collection not found")
  125. };
  126. if collection.org_uuid != org.uuid {
  127. err!("Collection is not owned by organization");
  128. }
  129. collection.name = data.Name.clone();
  130. collection.save(&conn);
  131. Ok(Json(collection.to_json()))
  132. }
  133. #[post("/organizations/<org_id>/collections/<col_id>/delete-user/<org_user_id>")]
  134. fn post_organization_collection_delete_user(org_id: String, col_id: String, org_user_id: String, _headers: AdminHeaders, conn: DbConn) -> EmptyResult {
  135. let collection = match Collection::find_by_uuid(&col_id, &conn) {
  136. None => err!("Collection not found"),
  137. Some(collection) => if collection.org_uuid == org_id {
  138. collection
  139. } else {
  140. err!("Collection and Organization id do not match")
  141. }
  142. };
  143. match UserOrganization::find_by_uuid(&org_user_id, &conn) {
  144. None => err!("User not found in organization"),
  145. Some(user_org) => {
  146. match CollectionUser::find_by_collection_and_user(&collection.uuid, &user_org.user_uuid, &conn) {
  147. None => err!("User not assigned to collection"),
  148. Some(col_user) => {
  149. match col_user.delete(&conn) {
  150. Ok(()) => Ok(()),
  151. Err(_) => err!("Failed removing user from collection")
  152. }
  153. }
  154. }
  155. }
  156. }
  157. }
  158. #[derive(Deserialize, Debug)]
  159. #[allow(non_snake_case)]
  160. struct DeleteCollectionData {
  161. Id: String,
  162. OrgId: String,
  163. }
  164. #[post("/organizations/<org_id>/collections/<col_id>/delete", data = "<data>")]
  165. fn post_organization_collection_delete(org_id: String, col_id: String, _headers: AdminHeaders, data: JsonUpcase<DeleteCollectionData>, conn: DbConn) -> EmptyResult {
  166. let _data: DeleteCollectionData = data.into_inner().data;
  167. match Collection::find_by_uuid(&col_id, &conn) {
  168. None => err!("Collection not found"),
  169. Some(collection) => if collection.org_uuid == org_id {
  170. match collection.delete(&conn) {
  171. Ok(()) => Ok(()),
  172. Err(_) => err!("Failed deleting collection")
  173. }
  174. } else {
  175. err!("Collection and Organization id do not match")
  176. }
  177. }
  178. }
  179. #[get("/organizations/<org_id>/collections/<coll_id>/details")]
  180. fn get_org_collection_detail(org_id: String, coll_id: String, headers: AdminHeaders, conn: DbConn) -> JsonResult {
  181. match Collection::find_by_uuid_and_user(&coll_id, &headers.user.uuid, &conn) {
  182. None => err!("Collection not found"),
  183. Some(collection) => {
  184. if collection.org_uuid != org_id {
  185. err!("Collection is not owned by organization")
  186. }
  187. Ok(Json(collection.to_json()))
  188. }
  189. }
  190. }
  191. #[get("/organizations/<org_id>/collections/<coll_id>/users")]
  192. fn get_collection_users(org_id: String, coll_id: String, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
  193. // Get org and collection, check that collection is from org
  194. let collection = match Collection::find_by_uuid_and_org(&coll_id, &org_id, &conn) {
  195. None => err!("Collection not found in Organization"),
  196. Some(collection) => collection
  197. };
  198. // Get the users from collection
  199. let user_list: Vec<Value> = CollectionUser::find_by_collection(&collection.uuid, &conn)
  200. .iter().map(|col_user| {
  201. UserOrganization::find_by_user_and_org(&col_user.user_uuid, &org_id, &conn)
  202. .unwrap()
  203. .to_json_collection_user_details(&col_user.read_only, &conn)
  204. }).collect();
  205. Ok(Json(json!({
  206. "Data": user_list,
  207. "Object": "list"
  208. })))
  209. }
  210. #[derive(FromForm)]
  211. #[allow(non_snake_case)]
  212. struct OrgIdData {
  213. organizationId: String
  214. }
  215. #[get("/ciphers/organization-details?<data>")]
  216. fn get_org_details(data: OrgIdData, headers: Headers, conn: DbConn) -> JsonResult {
  217. let ciphers = Cipher::find_by_org(&data.organizationId, &conn);
  218. let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json(&headers.host, &headers.user.uuid, &conn)).collect();
  219. Ok(Json(json!({
  220. "Data": ciphers_json,
  221. "Object": "list",
  222. })))
  223. }
  224. #[get("/organizations/<org_id>/users")]
  225. fn get_org_users(org_id: String, headers: AdminHeaders, conn: DbConn) -> JsonResult {
  226. match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
  227. Some(_) => (),
  228. None => err!("User isn't member of organization")
  229. }
  230. let users = UserOrganization::find_by_org(&org_id, &conn);
  231. let users_json: Vec<Value> = users.iter().map(|c| c.to_json_user_details(&conn)).collect();
  232. Ok(Json(json!({
  233. "Data": users_json,
  234. "Object": "list"
  235. })))
  236. }
  237. #[derive(Deserialize)]
  238. #[allow(non_snake_case)]
  239. struct CollectionData {
  240. id: String,
  241. readOnly: bool,
  242. }
  243. #[derive(Deserialize)]
  244. #[allow(non_snake_case)]
  245. struct InviteData {
  246. Emails: Vec<String>,
  247. Type: NumberOrString,
  248. Collections: Vec<CollectionData>,
  249. AccessAll: Option<bool>,
  250. }
  251. #[post("/organizations/<org_id>/users/invite", data = "<data>")]
  252. fn send_invite(org_id: String, data: JsonUpcase<InviteData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
  253. let data: InviteData = data.into_inner().data;
  254. let new_type = match UserOrgType::from_str(&data.Type.into_string()) {
  255. Some(new_type) => new_type as i32,
  256. None => err!("Invalid type")
  257. };
  258. if new_type != UserOrgType::User as i32 &&
  259. headers.org_user_type != UserOrgType::Owner as i32 {
  260. err!("Only Owners can invite Admins or Owners")
  261. }
  262. for user_opt in data.Emails.iter().map(|email| User::find_by_mail(email, &conn)) {
  263. match user_opt {
  264. None => err!("User email does not exist"),
  265. Some(user) => {
  266. if UserOrganization::find_by_user_and_org(&user.uuid, &org_id, &conn).is_some() {
  267. err!("User already in organization")
  268. }
  269. let mut new_user = UserOrganization::new(user.uuid.clone(), org_id.clone());
  270. let access_all = data.AccessAll.unwrap_or(false);
  271. new_user.access_all = access_all;
  272. new_user.type_ = new_type;
  273. // If no accessAll, add the collections received
  274. if !access_all {
  275. for col in &data.Collections {
  276. match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn) {
  277. None => err!("Collection not found in Organization"),
  278. Some(collection) => {
  279. if CollectionUser::save(&user.uuid, &collection.uuid, col.readOnly, &conn).is_err() {
  280. err!("Failed saving collection access for user")
  281. }
  282. }
  283. }
  284. }
  285. }
  286. new_user.save(&conn);
  287. }
  288. }
  289. }
  290. Ok(())
  291. }
  292. #[post("/organizations/<org_id>/users/<user_id>/confirm", data = "<data>")]
  293. fn confirm_invite(org_id: String, user_id: String, data: JsonUpcase<Value>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
  294. let data = data.into_inner().data;
  295. let mut user_to_confirm = match UserOrganization::find_by_uuid(&user_id, &conn) {
  296. Some(user) => user,
  297. None => err!("Failed to find user membership")
  298. };
  299. if user_to_confirm.org_uuid != org_id {
  300. err!("The specified user isn't a member of the organization")
  301. }
  302. if user_to_confirm.type_ != UserOrgType::User as i32 &&
  303. headers.org_user_type != UserOrgType::Owner as i32 {
  304. err!("Only Owners can confirm Admins or Owners")
  305. }
  306. if user_to_confirm.status != UserOrgStatus::Accepted as i32 {
  307. err!("User in invalid state")
  308. }
  309. user_to_confirm.status = UserOrgStatus::Confirmed as i32;
  310. user_to_confirm.key = match data["key"].as_str() {
  311. Some(key) => key.to_string(),
  312. None => err!("Invalid key provided")
  313. };
  314. user_to_confirm.save(&conn);
  315. Ok(())
  316. }
  317. #[get("/organizations/<org_id>/users/<user_id>")]
  318. fn get_user(org_id: String, user_id: String, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
  319. let user = match UserOrganization::find_by_uuid(&user_id, &conn) {
  320. Some(user) => user,
  321. None => err!("Failed to find user membership")
  322. };
  323. if user.org_uuid != org_id {
  324. err!("The specified user isn't a member of the organization")
  325. }
  326. Ok(Json(user.to_json_details(&conn)))
  327. }
  328. #[derive(Deserialize)]
  329. #[allow(non_snake_case)]
  330. struct EditUserData {
  331. Type: NumberOrString,
  332. Collections: Vec<CollectionData>,
  333. AccessAll: bool,
  334. }
  335. #[post("/organizations/<org_id>/users/<user_id>", data = "<data>", rank = 1)]
  336. fn edit_user(org_id: String, user_id: String, data: JsonUpcase<EditUserData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
  337. let data: EditUserData = data.into_inner().data;
  338. let new_type = match UserOrgType::from_str(&data.Type.into_string()) {
  339. Some(new_type) => new_type as i32,
  340. None => err!("Invalid type")
  341. };
  342. let mut user_to_edit = match UserOrganization::find_by_uuid(&user_id, &conn) {
  343. Some(user) => user,
  344. None => err!("The specified user isn't member of the organization")
  345. };
  346. if new_type != UserOrgType::User as i32 &&
  347. headers.org_user_type != UserOrgType::Owner as i32 {
  348. err!("Only Owners can grant Admin or Owner type")
  349. }
  350. if user_to_edit.type_ != UserOrgType::User as i32 &&
  351. headers.org_user_type != UserOrgType::Owner as i32 {
  352. err!("Only Owners can edit Admin or Owner")
  353. }
  354. if user_to_edit.type_ == UserOrgType::Owner as i32 &&
  355. new_type != UserOrgType::Owner as i32 {
  356. // Removing owner permmission, check that there are at least another owner
  357. let num_owners = UserOrganization::find_by_org_and_type(
  358. &org_id, UserOrgType::Owner as i32, &conn)
  359. .len();
  360. if num_owners <= 1 {
  361. err!("Can't delete the last owner")
  362. }
  363. }
  364. user_to_edit.access_all = data.AccessAll;
  365. user_to_edit.type_ = new_type;
  366. // Delete all the odd collections
  367. for c in CollectionUser::find_by_organization_and_user_uuid(&org_id, &user_to_edit.user_uuid, &conn) {
  368. if c.delete(&conn).is_err() {
  369. err!("Failed deleting old collection assignment")
  370. }
  371. }
  372. // If no accessAll, add the collections received
  373. if !data.AccessAll {
  374. for col in &data.Collections {
  375. match Collection::find_by_uuid_and_org(&col.id, &org_id, &conn) {
  376. None => err!("Collection not found in Organization"),
  377. Some(collection) => {
  378. if CollectionUser::save(&user_to_edit.user_uuid, &collection.uuid, col.readOnly, &conn).is_err() {
  379. err!("Failed saving collection access for user")
  380. }
  381. }
  382. }
  383. }
  384. }
  385. user_to_edit.save(&conn);
  386. Ok(())
  387. }
  388. #[post("/organizations/<org_id>/users/<user_id>/delete")]
  389. fn delete_user(org_id: String, user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
  390. let user_to_delete = match UserOrganization::find_by_uuid(&user_id, &conn) {
  391. Some(user) => user,
  392. None => err!("User to delete isn't member of the organization")
  393. };
  394. if user_to_delete.type_ != UserOrgType::User as i32 &&
  395. headers.org_user_type != UserOrgType::Owner as i32 {
  396. err!("Only Owners can delete Admins or Owners")
  397. }
  398. if user_to_delete.type_ == UserOrgType::Owner as i32 {
  399. // Removing owner, check that there are at least another owner
  400. let num_owners = UserOrganization::find_by_org_and_type(
  401. &org_id, UserOrgType::Owner as i32, &conn)
  402. .len();
  403. if num_owners <= 1 {
  404. err!("Can't delete the last owner")
  405. }
  406. }
  407. match user_to_delete.delete(&conn) {
  408. Ok(()) => Ok(()),
  409. Err(_) => err!("Failed deleting user from organization")
  410. }
  411. }