aboutsummaryrefslogtreecommitdiff
path: root/src/api/core/organizations.rs
blob: 00f2ef71dd28e0fed01d157a18cef4883f10b686 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
use num_traits::FromPrimitive;
use rocket::{request::Form, Route};
use rocket_contrib::json::Json;
use serde_json::Value;

use crate::{
    api::{EmptyResult, JsonResult, JsonUpcase, JsonUpcaseVec, Notify, NumberOrString, PasswordData, UpdateType},
    auth::{decode_invite, AdminHeaders, Headers, ManagerHeaders, ManagerHeadersLoose, OwnerHeaders},
    db::{models::*, DbConn},
    mail, CONFIG,
};

pub fn routes() -> Vec<Route> {
    routes![
        get_organization,
        create_organization,
        delete_organization,
        post_delete_organization,
        leave_organization,
        get_user_collections,
        get_org_collections,
        get_org_collection_detail,
        get_collection_users,
        put_collection_users,
        put_organization,
        post_organization,
        post_organization_collections,
        delete_organization_collection_user,
        post_organization_collection_delete_user,
        post_organization_collection_update,
        put_organization_collection_update,
        delete_organization_collection,
        post_organization_collection_delete,
        get_org_details,
        get_org_users,
        send_invite,
        reinvite_user,
        bulk_reinvite_user,
        confirm_invite,
        bulk_confirm_invite,
        accept_invite,
        get_user,
        edit_user,
        put_organization_user,
        delete_user,
        bulk_delete_user,
        post_delete_user,
        post_org_import,
        list_policies,
        list_policies_token,
        get_policy,
        put_policy,
        get_organization_tax,
        get_plans,
        get_plans_tax_rates,
        import,
        post_org_keys,
        bulk_public_keys,
    ]
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct OrgData {
    BillingEmail: String,
    CollectionName: String,
    Key: String,
    Name: String,
    Keys: Option<OrgKeyData>,
    #[serde(rename = "PlanType")]
    _PlanType: NumberOrString, // Ignored, always use the same plan
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct OrganizationUpdateData {
    BillingEmail: String,
    Name: String,
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct NewCollectionData {
    Name: String,
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct OrgKeyData {
    EncryptedPrivateKey: String,
    PublicKey: String,
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct OrgBulkIds {
    Ids: Vec<String>,
}

#[post("/organizations", data = "<data>")]
fn create_organization(headers: Headers, data: JsonUpcase<OrgData>, conn: DbConn) -> JsonResult {
    if !CONFIG.is_org_creation_allowed(&headers.user.email) {
        err!("User not allowed to create organizations")
    }
    if OrgPolicy::is_applicable_to_user(&headers.user.uuid, OrgPolicyType::SingleOrg, &conn) {
        err!(
            "You may not create an organization. You belong to an organization which has a policy that prohibits you from being a member of any other organization."
        )
    }

    let data: OrgData = data.into_inner().data;
    let (private_key, public_key) = if data.Keys.is_some() {
        let keys: OrgKeyData = data.Keys.unwrap();
        (Some(keys.EncryptedPrivateKey), Some(keys.PublicKey))
    } else {
        (None, None)
    };

    let org = Organization::new(data.Name, data.BillingEmail, private_key, public_key);
    let mut user_org = UserOrganization::new(headers.user.uuid, org.uuid.clone());
    let collection = Collection::new(org.uuid.clone(), data.CollectionName);

    user_org.akey = data.Key;
    user_org.access_all = true;
    user_org.atype = UserOrgType::Owner as i32;
    user_org.status = UserOrgStatus::Confirmed as i32;

    org.save(&conn)?;
    user_org.save(&conn)?;
    collection.save(&conn)?;

    Ok(Json(org.to_json()))
}

#[delete("/organizations/<org_id>", data = "<data>")]
fn delete_organization(
    org_id: String,
    data: JsonUpcase<PasswordData>,
    headers: OwnerHeaders,
    conn: DbConn,
) -> EmptyResult {
    let data: PasswordData = data.into_inner().data;
    let password_hash = data.MasterPasswordHash;

    if !headers.user.check_valid_password(&password_hash) {
        err!("Invalid password")
    }

    match Organization::find_by_uuid(&org_id, &conn) {
        None => err!("Organization not found"),
        Some(org) => org.delete(&conn),
    }
}

#[post("/organizations/<org_id>/delete", data = "<data>")]
fn post_delete_organization(
    org_id: String,
    data: JsonUpcase<PasswordData>,
    headers: OwnerHeaders,
    conn: DbConn,
) -> EmptyResult {
    delete_organization(org_id, data, headers, conn)
}

#[post("/organizations/<org_id>/leave")]
fn leave_organization(org_id: String, headers: Headers, conn: DbConn) -> EmptyResult {
    match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
        None => err!("User not part of organization"),
        Some(user_org) => {
            if user_org.atype == UserOrgType::Owner {
                let num_owners =
                    UserOrganization::find_by_org_and_type(&org_id, UserOrgType::Owner as i32, &conn).len();

                if num_owners <= 1 {
                    err!("The last owner can't leave")
                }
            }

            user_org.delete(&conn)
        }
    }
}

#[get("/organizations/<org_id>")]
fn get_organization(org_id: String, _headers: OwnerHeaders, conn: DbConn) -> JsonResult {
    match Organization::find_by_uuid(&org_id, &conn) {
        Some(organization) => Ok(Json(organization.to_json())),
        None => err!("Can't find organization details"),
    }
}

#[put("/organizations/<org_id>", data = "<data>")]
fn put_organization(
    org_id: String,
    headers: OwnerHeaders,
    data: JsonUpcase<OrganizationUpdateData>,
    conn: DbConn,
) -> JsonResult {
    post_organization(org_id, headers, data, conn)
}

#[post("/organizations/<org_id>", data = "<data>")]
fn post_organization(
    org_id: String,
    _headers: OwnerHeaders,
    data: JsonUpcase<OrganizationUpdateData>,
    conn: DbConn,
) -> JsonResult {
    let data: OrganizationUpdateData = data.into_inner().data;

    let mut org = match Organization::find_by_uuid(&org_id, &conn) {
        Some(organization) => organization,
        None => err!("Can't find organization details"),
    };

    org.name = data.Name;
    org.billing_email = data.BillingEmail;

    org.save(&conn)?;
    Ok(Json(org.to_json()))
}

// GET /api/collections?writeOnly=false
#[get("/collections")]
fn get_user_collections(headers: Headers, conn: DbConn) -> Json<Value> {
    Json(json!({
        "Data":
            Collection::find_by_user_uuid(&headers.user.uuid, &conn)
            .iter()
            .map(Collection::to_json)
            .collect::<Value>(),
        "Object": "list",
        "ContinuationToken": null,
    }))
}

#[get("/organizations/<org_id>/collections")]
fn get_org_collections(org_id: String, _headers: AdminHeaders, conn: DbConn) -> Json<Value> {
    Json(json!({
        "Data":
            Collection::find_by_organization(&org_id, &conn)
            .iter()
            .map(Collection::to_json)
            .collect::<Value>(),
        "Object": "list",
        "ContinuationToken": null,
    }))
}

#[post("/organizations/<org_id>/collections", data = "<data>")]
fn post_organization_collections(
    org_id: String,
    headers: ManagerHeadersLoose,
    data: JsonUpcase<NewCollectionData>,
    conn: DbConn,
) -> JsonResult {
    let data: NewCollectionData = data.into_inner().data;

    let org = match Organization::find_by_uuid(&org_id, &conn) {
        Some(organization) => organization,
        None => err!("Can't find organization details"),
    };

    // Get the user_organization record so that we can check if the user has access to all collections.
    let user_org = match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
        Some(u) => u,
        None => err!("User is not part of organization"),
    };

    let collection = Collection::new(org.uuid, data.Name);
    collection.save(&conn)?;

    // If the user doesn't have access to all collections, only in case of a Manger,
    // then we need to save the creating user uuid (Manager) to the users_collection table.
    // Else the user will not have access to his own created collection.
    if !user_org.access_all {
        CollectionUser::save(&headers.user.uuid, &collection.uuid, false, false, &conn)?;
    }

    Ok(Json(collection.to_json()))
}

#[put("/organizations/<org_id>/collections/<col_id>", data = "<data>")]
fn put_organization_collection_update(
    org_id: String,
    col_id: String,
    headers: ManagerHeaders,
    data: JsonUpcase<NewCollectionData>,
    conn: DbConn,
) -> JsonResult {
    post_organization_collection_update(org_id, col_id, headers, data, conn)
}

#[post("/organizations/<org_id>/collections/<col_id>", data = "<data>")]
fn post_organization_collection_update(
    org_id: String,
    col_id: String,
    _headers: ManagerHeaders,
    data: JsonUpcase<NewCollectionData>,
    conn: DbConn,
) -> JsonResult {
    let data: NewCollectionData = data.into_inner().data;

    let org = match Organization::find_by_uuid(&org_id, &conn) {
        Some(organization) => organization,
        None => err!("Can't find organization details"),
    };

    let mut collection = match Collection::find_by_uuid(&col_id, &conn) {
        Some(collection) => collection,
        None => err!("Collection not found"),
    };

    if collection.org_uuid != org.uuid {
        err!("Collection is not owned by organization");
    }

    collection.name = data.Name;
    collection.save(&conn)?;

    Ok(Json(collection.to_json()))
}

#[delete("/organizations/<org_id>/collections/<col_id>/user/<org_user_id>")]
fn delete_organization_collection_user(
    org_id: String,
    col_id: String,
    org_user_id: String,
    _headers: AdminHeaders,
    conn: DbConn,
) -> EmptyResult {
    let collection = match Collection::find_by_uuid(&col_id, &conn) {
        None => err!("Collection not found"),
        Some(collection) => {
            if collection.org_uuid == org_id {
                collection
            } else {
                err!("Collection and Organization id do not match")
            }
        }
    };

    match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
        None => err!("User not found in organization"),
        Some(user_org) => {
            match CollectionUser::find_by_collection_and_user(&collection.uuid, &user_org.user_uuid, &conn) {
                None => err!("User not assigned to collection"),
                Some(col_user) => col_user.delete(&conn),
            }
        }
    }
}

#[post("/organizations/<org_id>/collections/<col_id>/delete-user/<org_user_id>")]
fn post_organization_collection_delete_user(
    org_id: String,
    col_id: String,
    org_user_id: String,
    headers: AdminHeaders,
    conn: DbConn,
) -> EmptyResult {
    delete_organization_collection_user(org_id, col_id, org_user_id, headers, conn)
}

#[delete("/organizations/<org_id>/collections/<col_id>")]
fn delete_organization_collection(
    org_id: String,
    col_id: String,
    _headers: ManagerHeaders,
    conn: DbConn,
) -> EmptyResult {
    match Collection::find_by_uuid(&col_id, &conn) {
        None => err!("Collection not found"),
        Some(collection) => {
            if collection.org_uuid == org_id {
                collection.delete(&conn)
            } else {
                err!("Collection and Organization id do not match")
            }
        }
    }
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case, dead_code)]
struct DeleteCollectionData {
    Id: String,
    OrgId: String,
}

#[post("/organizations/<org_id>/collections/<col_id>/delete", data = "<_data>")]
fn post_organization_collection_delete(
    org_id: String,
    col_id: String,
    headers: ManagerHeaders,
    _data: JsonUpcase<DeleteCollectionData>,
    conn: DbConn,
) -> EmptyResult {
    delete_organization_collection(org_id, col_id, headers, conn)
}

#[get("/organizations/<org_id>/collections/<coll_id>/details")]
fn get_org_collection_detail(org_id: String, coll_id: String, headers: ManagerHeaders, conn: DbConn) -> JsonResult {
    match Collection::find_by_uuid_and_user(&coll_id, &headers.user.uuid, &conn) {
        None => err!("Collection not found"),
        Some(collection) => {
            if collection.org_uuid != org_id {
                err!("Collection is not owned by organization")
            }

            Ok(Json(collection.to_json()))
        }
    }
}

#[get("/organizations/<org_id>/collections/<coll_id>/users")]
fn get_collection_users(org_id: String, coll_id: String, _headers: ManagerHeaders, conn: DbConn) -> JsonResult {
    // Get org and collection, check that collection is from org
    let collection = match Collection::find_by_uuid_and_org(&coll_id, &org_id, &conn) {
        None => err!("Collection not found in Organization"),
        Some(collection) => collection,
    };

    // Get the users from collection
    let user_list: Vec<Value> = CollectionUser::find_by_collection(&collection.uuid, &conn)
        .iter()
        .map(|col_user| {
            UserOrganization::find_by_user_and_org(&col_user.user_uuid, &org_id, &conn)
                .unwrap()
                .to_json_user_access_restrictions(col_user)
        })
        .collect();

    Ok(Json(json!(user_list)))
}

#[put("/organizations/<org_id>/collections/<coll_id>/users", data = "<data>")]
fn put_collection_users(
    org_id: String,
    coll_id: String,
    data: JsonUpcaseVec<CollectionData>,
    _headers: ManagerHeaders,
    conn: DbConn,
) -> EmptyResult {
    // Get org and collection, check that collection is from org
    if Collection::find_by_uuid_and_org(&coll_id, &org_id, &conn).is_none() {
        err!("Collection not found in Organization")
    }

    // Delete all the user-collections
    CollectionUser::delete_all_by_collection(&coll_id, &conn)?;

    // And then add all the received ones (except if the user has access_all)
    for d in data.iter().map(|d| &d.data) {
        let user = match UserOrganization::find_by_uuid(&d.Id, &conn) {
            Some(u) => u,
            None => err!("User is not part of organization"),
        };

        if user.access_all {
            continue;
        }

        CollectionUser::save(&user.user_uuid, &coll_id, d.ReadOnly, d.HidePasswords, &conn)?;
    }

    Ok(())
}

#[derive(FromForm)]
struct OrgIdData {
    #[form(field = "organizationId")]
    organization_id: String,
}

#[get("/ciphers/organization-details?<data..>")]
fn get_org_details(data: Form<OrgIdData>, headers: Headers, conn: DbConn) -> Json<Value> {
    let ciphers = Cipher::find_by_org(&data.organization_id, &conn);
    let ciphers_json: Vec<Value> =
        ciphers.iter().map(|c| c.to_json(&headers.host, &headers.user.uuid, &conn)).collect();

    Json(json!({
      "Data": ciphers_json,
      "Object": "list",
      "ContinuationToken": null,
    }))
}

#[get("/organizations/<org_id>/users")]
fn get_org_users(org_id: String, _headers: ManagerHeadersLoose, conn: DbConn) -> Json<Value> {
    let users = UserOrganization::find_by_org(&org_id, &conn);
    let users_json: Vec<Value> = users.iter().map(|c| c.to_json_user_details(&conn)).collect();

    Json(json!({
        "Data": users_json,
        "Object": "list",
        "ContinuationToken": null,
    }))
}

#[post("/organizations/<org_id>/keys", data = "<data>")]
fn post_org_keys(org_id: String, data: JsonUpcase<OrgKeyData>, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
    let data: OrgKeyData = data.into_inner().data;

    let mut org = match Organization::find_by_uuid(&org_id, &conn) {
        Some(organization) => {
            if organization.private_key.is_some() && organization.public_key.is_some() {
                err!("Organization Keys already exist")
            }
            organization
        }
        None => err!("Can't find organization details"),
    };

    org.private_key = Some(data.EncryptedPrivateKey);
    org.public_key = Some(data.PublicKey);

    org.save(&conn)?;

    Ok(Json(json!({
        "Object": "organizationKeys",
        "PublicKey": org.public_key,
        "PrivateKey": org.private_key,
    })))
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct CollectionData {
    Id: String,
    ReadOnly: bool,
    HidePasswords: bool,
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct InviteData {
    Emails: Vec<String>,
    Type: NumberOrString,
    Collections: Option<Vec<CollectionData>>,
    AccessAll: Option<bool>,
}

#[post("/organizations/<org_id>/users/invite", data = "<data>")]
fn send_invite(org_id: String, data: JsonUpcase<InviteData>, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
    let data: InviteData = data.into_inner().data;

    let new_type = match UserOrgType::from_str(&data.Type.into_string()) {
        Some(new_type) => new_type as i32,
        None => err!("Invalid type"),
    };

    if new_type != UserOrgType::User && headers.org_user_type != UserOrgType::Owner {
        err!("Only Owners can invite Managers, Admins or Owners")
    }

    for email in data.Emails.iter() {
        let email = email.to_lowercase();
        let mut user_org_status = if CONFIG.mail_enabled() {
            UserOrgStatus::Invited as i32
        } else {
            UserOrgStatus::Accepted as i32 // Automatically mark user as accepted if no email invites
        };
        let user = match User::find_by_mail(&email, &conn) {
            None => {
                if !CONFIG.invitations_allowed() {
                    err!(format!("User does not exist: {}", email))
                }

                if !CONFIG.is_email_domain_allowed(&email) {
                    err!("Email domain not eligible for invitations")
                }

                if !CONFIG.mail_enabled() {
                    let invitation = Invitation::new(email.clone());
                    invitation.save(&conn)?;
                }

                let mut user = User::new(email.clone());
                user.save(&conn)?;
                user_org_status = UserOrgStatus::Invited as i32;
                user
            }
            Some(user) => {
                if UserOrganization::find_by_user_and_org(&user.uuid, &org_id, &conn).is_some() {
                    err!(format!("User already in organization: {}", email))
                } else {
                    user
                }
            }
        };

        let mut new_user = UserOrganization::new(user.uuid.clone(), org_id.clone());
        let access_all = data.AccessAll.unwrap_or(false);
        new_user.access_all = access_all;
        new_user.atype = new_type;
        new_user.status = user_org_status;

        // If no accessAll, add the collections received
        if !access_all {
            for col in data.Collections.iter().flatten() {
                match Collection::find_by_uuid_and_org(&col.Id, &org_id, &conn) {
                    None => err!("Collection not found in Organization"),
                    Some(collection) => {
                        CollectionUser::save(&user.uuid, &collection.uuid, col.ReadOnly, col.HidePasswords, &conn)?;
                    }
                }
            }
        }

        new_user.save(&conn)?;

        if CONFIG.mail_enabled() {
            let org_name = match Organization::find_by_uuid(&org_id, &conn) {
                Some(org) => org.name,
                None => err!("Error looking up organization"),
            };

            mail::send_invite(
                &email,
                &user.uuid,
                Some(org_id.clone()),
                Some(new_user.uuid),
                &org_name,
                Some(headers.user.email.clone()),
            )?;
        }
    }

    Ok(())
}

#[post("/organizations/<org_id>/users/reinvite", data = "<data>")]
fn bulk_reinvite_user(
    org_id: String,
    data: JsonUpcase<OrgBulkIds>,
    headers: AdminHeaders,
    conn: DbConn,
) -> Json<Value> {
    let data: OrgBulkIds = data.into_inner().data;

    let mut bulk_response = Vec::new();
    for org_user_id in data.Ids {
        let err_msg = match _reinvite_user(&org_id, &org_user_id, &headers.user.email, &conn) {
            Ok(_) => String::from(""),
            Err(e) => format!("{:?}", e),
        };

        bulk_response.push(json!(
            {
                "Object": "OrganizationBulkConfirmResponseModel",
                "Id": org_user_id,
                "Error": err_msg
            }
        ))
    }

    Json(json!({
        "Data": bulk_response,
        "Object": "list",
        "ContinuationToken": null
    }))
}

#[post("/organizations/<org_id>/users/<user_org>/reinvite")]
fn reinvite_user(org_id: String, user_org: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
    _reinvite_user(&org_id, &user_org, &headers.user.email, &conn)
}

fn _reinvite_user(org_id: &str, user_org: &str, invited_by_email: &str, conn: &DbConn) -> EmptyResult {
    if !CONFIG.invitations_allowed() {
        err!("Invitations are not allowed.")
    }

    if !CONFIG.mail_enabled() {
        err!("SMTP is not configured.")
    }

    let user_org = match UserOrganization::find_by_uuid(user_org, conn) {
        Some(user_org) => user_org,
        None => err!("The user hasn't been invited to the organization."),
    };

    if user_org.status != UserOrgStatus::Invited as i32 {
        err!("The user is already accepted or confirmed to the organization")
    }

    let user = match User::find_by_uuid(&user_org.user_uuid, conn) {
        Some(user) => user,
        None => err!("User not found."),
    };

    let org_name = match Organization::find_by_uuid(org_id, conn) {
        Some(org) => org.name,
        None => err!("Error looking up organization."),
    };

    if CONFIG.mail_enabled() {
        mail::send_invite(
            &user.email,
            &user.uuid,
            Some(org_id.to_string()),
            Some(user_org.uuid),
            &org_name,
            Some(invited_by_email.to_string()),
        )?;
    } else {
        let invitation = Invitation::new(user.email);
        invitation.save(conn)?;
    }

    Ok(())
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct AcceptData {
    Token: String,
}

#[post("/organizations/<_org_id>/users/<_org_user_id>/accept", data = "<data>")]
fn accept_invite(_org_id: String, _org_user_id: String, data: JsonUpcase<AcceptData>, conn: DbConn) -> EmptyResult {
    // The web-vault passes org_id and org_user_id in the URL, but we are just reading them from the JWT instead
    let data: AcceptData = data.into_inner().data;
    let token = &data.Token;
    let claims = decode_invite(token)?;

    match User::find_by_mail(&claims.email, &conn) {
        Some(_) => {
            Invitation::take(&claims.email, &conn);

            if let (Some(user_org), Some(org)) = (&claims.user_org_id, &claims.org_id) {
                let mut user_org = match UserOrganization::find_by_uuid_and_org(user_org, org, &conn) {
                    Some(user_org) => user_org,
                    None => err!("Error accepting the invitation"),
                };

                if user_org.status != UserOrgStatus::Invited as i32 {
                    err!("User already accepted the invitation")
                }

                let user_twofactor_disabled = TwoFactor::find_by_user(&user_org.user_uuid, &conn).is_empty();

                let policy = OrgPolicyType::TwoFactorAuthentication as i32;
                let org_twofactor_policy_enabled =
                    match OrgPolicy::find_by_org_and_type(&user_org.org_uuid, policy, &conn) {
                        Some(p) => p.enabled,
                        None => false,
                    };

                if org_twofactor_policy_enabled && user_twofactor_disabled {
                    err!("You cannot join this organization until you enable two-step login on your user account.")
                }

                // Enforce Single Organization Policy of organization user is trying to join
                let single_org_policy_enabled =
                    match OrgPolicy::find_by_org_and_type(&user_org.org_uuid, OrgPolicyType::SingleOrg as i32, &conn) {
                        Some(p) => p.enabled,
                        None => false,
                    };
                if single_org_policy_enabled && user_org.atype < UserOrgType::Admin {
                    let is_member_of_another_org = UserOrganization::find_any_state_by_user(&user_org.user_uuid, &conn)
                        .into_iter()
                        .filter(|uo| uo.org_uuid != user_org.org_uuid)
                        .count()
                        > 1;
                    if is_member_of_another_org {
                        err!("You may not join this organization until you leave or remove all other organizations.")
                    }
                }

                // Enforce Single Organization Policy of other organizations user is a member of
                if OrgPolicy::is_applicable_to_user(&user_org.user_uuid, OrgPolicyType::SingleOrg, &conn) {
                    err!(
                        "You cannot join this organization because you are a member of an organization which forbids it"
                    )
                }

                user_org.status = UserOrgStatus::Accepted as i32;
                user_org.save(&conn)?;
            }
        }
        None => err!("Invited user not found"),
    }

    if CONFIG.mail_enabled() {
        let mut org_name = CONFIG.invitation_org_name();
        if let Some(org_id) = &claims.org_id {
            org_name = match Organization::find_by_uuid(org_id, &conn) {
                Some(org) => org.name,
                None => err!("Organization not found."),
            };
        };
        if let Some(invited_by_email) = &claims.invited_by_email {
            // User was invited to an organization, so they must be confirmed manually after acceptance
            mail::send_invite_accepted(&claims.email, invited_by_email, &org_name)?;
        } else {
            // User was invited from /admin, so they are automatically confirmed
            mail::send_invite_confirmed(&claims.email, &org_name)?;
        }
    }

    Ok(())
}

#[post("/organizations/<org_id>/users/confirm", data = "<data>")]
fn bulk_confirm_invite(org_id: String, data: JsonUpcase<Value>, headers: AdminHeaders, conn: DbConn) -> Json<Value> {
    let data = data.into_inner().data;

    let mut bulk_response = Vec::new();
    match data["Keys"].as_array() {
        Some(keys) => {
            for invite in keys {
                let org_user_id = invite["Id"].as_str().unwrap_or_default();
                let user_key = invite["Key"].as_str().unwrap_or_default();
                let err_msg = match _confirm_invite(&org_id, org_user_id, user_key, &headers, &conn) {
                    Ok(_) => String::from(""),
                    Err(e) => format!("{:?}", e),
                };

                bulk_response.push(json!(
                    {
                        "Object": "OrganizationBulkConfirmResponseModel",
                        "Id": org_user_id,
                        "Error": err_msg
                    }
                ));
            }
        }
        None => error!("No keys to confirm"),
    }

    Json(json!({
        "Data": bulk_response,
        "Object": "list",
        "ContinuationToken": null
    }))
}

#[post("/organizations/<org_id>/users/<org_user_id>/confirm", data = "<data>")]
fn confirm_invite(
    org_id: String,
    org_user_id: String,
    data: JsonUpcase<Value>,
    headers: AdminHeaders,
    conn: DbConn,
) -> EmptyResult {
    let data = data.into_inner().data;
    let user_key = data["Key"].as_str().unwrap_or_default();
    _confirm_invite(&org_id, &org_user_id, user_key, &headers, &conn)
}

fn _confirm_invite(org_id: &str, org_user_id: &str, key: &str, headers: &AdminHeaders, conn: &DbConn) -> EmptyResult {
    if key.is_empty() || org_user_id.is_empty() {
        err!("Key or UserId is not set, unable to process request");
    }

    let mut user_to_confirm = match UserOrganization::find_by_uuid_and_org(org_user_id, org_id, conn) {
        Some(user) => user,
        None => err!("The specified user isn't a member of the organization"),
    };

    if user_to_confirm.atype != UserOrgType::User && headers.org_user_type != UserOrgType::Owner {
        err!("Only Owners can confirm Managers, Admins or Owners")
    }

    if user_to_confirm.status != UserOrgStatus::Accepted as i32 {
        err!("User in invalid state")
    }

    user_to_confirm.status = UserOrgStatus::Confirmed as i32;
    user_to_confirm.akey = key.to_string();

    if CONFIG.mail_enabled() {
        let org_name = match Organization::find_by_uuid(org_id, conn) {
            Some(org) => org.name,
            None => err!("Error looking up organization."),
        };
        let address = match User::find_by_uuid(&user_to_confirm.user_uuid, conn) {
            Some(user) => user.email,
            None => err!("Error looking up user."),
        };
        mail::send_invite_confirmed(&address, &org_name)?;
    }

    user_to_confirm.save(conn)
}

#[get("/organizations/<org_id>/users/<org_user_id>")]
fn get_user(org_id: String, org_user_id: String, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
    let user = match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
        Some(user) => user,
        None => err!("The specified user isn't a member of the organization"),
    };

    Ok(Json(user.to_json_details(&conn)))
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct EditUserData {
    Type: NumberOrString,
    Collections: Option<Vec<CollectionData>>,
    AccessAll: bool,
}

#[put("/organizations/<org_id>/users/<org_user_id>", data = "<data>", rank = 1)]
fn put_organization_user(
    org_id: String,
    org_user_id: String,
    data: JsonUpcase<EditUserData>,
    headers: AdminHeaders,
    conn: DbConn,
) -> EmptyResult {
    edit_user(org_id, org_user_id, data, headers, conn)
}

#[post("/organizations/<org_id>/users/<org_user_id>", data = "<data>", rank = 1)]
fn edit_user(
    org_id: String,
    org_user_id: String,
    data: JsonUpcase<EditUserData>,
    headers: AdminHeaders,
    conn: DbConn,
) -> EmptyResult {
    let data: EditUserData = data.into_inner().data;

    let new_type = match UserOrgType::from_str(&data.Type.into_string()) {
        Some(new_type) => new_type,
        None => err!("Invalid type"),
    };

    let mut user_to_edit = match UserOrganization::find_by_uuid_and_org(&org_user_id, &org_id, &conn) {
        Some(user) => user,
        None => err!("The specified user isn't member of the organization"),
    };

    if new_type != user_to_edit.atype
        && (user_to_edit.atype >= UserOrgType::Admin || new_type >= UserOrgType::Admin)
        && headers.org_user_type != UserOrgType::Owner
    {
        err!("Only Owners can grant and remove Admin or Owner privileges")
    }

    if user_to_edit.atype == UserOrgType::Owner && headers.org_user_type != UserOrgType::Owner {
        err!("Only Owners can edit Owner users")
    }

    if user_to_edit.atype == UserOrgType::Owner && new_type != UserOrgType::Owner {
        // Removing owner permmission, check that there are at least another owner
        let num_owners = UserOrganization::find_by_org_and_type(&org_id, UserOrgType::Owner as i32, &conn).len();

        if num_owners <= 1 {
            err!("Can't delete the last owner")
        }
    }

    user_to_edit.access_all = data.AccessAll;
    user_to_edit.atype = new_type as i32;

    // Delete all the odd collections
    for c in CollectionUser::find_by_organization_and_user_uuid(&org_id, &user_to_edit.user_uuid, &conn) {
        c.delete(&conn)?;
    }

    // If no accessAll, add the collections received
    if !data.AccessAll {
        for col in data.Collections.iter().flatten() {
            match Collection::find_by_uuid_and_org(&col.Id, &org_id, &conn) {
                None => err!("Collection not found in Organization"),
                Some(collection) => {
                    CollectionUser::save(
                        &user_to_edit.user_uuid,
                        &collection.uuid,
                        col.ReadOnly,
                        col.HidePasswords,
                        &conn,
                    )?;
                }
            }
        }
    }

    user_to_edit.save(&conn)
}

#[delete("/organizations/<org_id>/users", data = "<data>")]
fn bulk_delete_user(org_id: String, data: JsonUpcase<OrgBulkIds>, headers: AdminHeaders, conn: DbConn) -> Json<Value> {
    let data: OrgBulkIds = data.into_inner().data;

    let mut bulk_response = Vec::new();
    for org_user_id in data.Ids {
        let err_msg = match _delete_user(&org_id, &org_user_id, &headers, &conn) {
            Ok(_) => String::from(""),
            Err(e) => format!("{:?}", e),
        };

        bulk_response.push(json!(
            {
                "Object": "OrganizationBulkConfirmResponseModel",
                "Id": org_user_id,
                "Error": err_msg
            }
        ))
    }

    Json(json!({
        "Data": bulk_response,
        "Object": "list",
        "ContinuationToken": null
    }))
}

#[delete("/organizations/<org_id>/users/<org_user_id>")]
fn delete_user(org_id: String, org_user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
    _delete_user(&org_id, &org_user_id, &headers, &conn)
}

fn _delete_user(org_id: &str, org_user_id: &str, headers: &AdminHeaders, conn: &DbConn) -> EmptyResult {
    let user_to_delete = match UserOrganization::find_by_uuid_and_org(org_user_id, org_id, conn) {
        Some(user) => user,
        None => err!("User to delete isn't member of the organization"),
    };

    if user_to_delete.atype != UserOrgType::User && headers.org_user_type != UserOrgType::Owner {
        err!("Only Owners can delete Admins or Owners")
    }

    if user_to_delete.atype == UserOrgType::Owner {
        // Removing owner, check that there are at least another owner
        let num_owners = UserOrganization::find_by_org_and_type(org_id, UserOrgType::Owner as i32, conn).len();

        if num_owners <= 1 {
            err!("Can't delete the last owner")
        }
    }

    user_to_delete.delete(conn)
}

#[post("/organizations/<org_id>/users/<org_user_id>/delete")]
fn post_delete_user(org_id: String, org_user_id: String, headers: AdminHeaders, conn: DbConn) -> EmptyResult {
    delete_user(org_id, org_user_id, headers, conn)
}

#[post("/organizations/<org_id>/users/public-keys", data = "<data>")]
fn bulk_public_keys(org_id: String, data: JsonUpcase<OrgBulkIds>, _headers: AdminHeaders, conn: DbConn) -> Json<Value> {
    let data: OrgBulkIds = data.into_inner().data;

    let mut bulk_response = Vec::new();
    // Check all received UserOrg UUID's and find the matching User to retreive the public-key.
    // If the user does not exists, just ignore it, and do not return any information regarding that UserOrg UUID.
    // The web-vault will then ignore that user for the folowing steps.
    for user_org_id in data.Ids {
        match UserOrganization::find_by_uuid_and_org(&user_org_id, &org_id, &conn) {
            Some(user_org) => match User::find_by_uuid(&user_org.user_uuid, &conn) {
                Some(user) => bulk_response.push(json!(
                    {
                        "Object": "organizationUserPublicKeyResponseModel",
                        "Id": user_org_id,
                        "UserId": user.uuid,
                        "Key": user.public_key
                    }
                )),
                None => debug!("User doesn't exist"),
            },
            None => debug!("UserOrg doesn't exist"),
        }
    }

    Json(json!({
        "Data": bulk_response,
        "Object": "list",
        "ContinuationToken": null
    }))
}

use super::ciphers::update_cipher_from_data;
use super::ciphers::CipherData;

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct ImportData {
    Ciphers: Vec<CipherData>,
    Collections: Vec<NewCollectionData>,
    CollectionRelationships: Vec<RelationsData>,
}

#[derive(Deserialize)]
#[allow(non_snake_case)]
struct RelationsData {
    // Cipher index
    Key: usize,
    // Collection index
    Value: usize,
}

#[post("/ciphers/import-organization?<query..>", data = "<data>")]
fn post_org_import(
    query: Form<OrgIdData>,
    data: JsonUpcase<ImportData>,
    headers: AdminHeaders,
    conn: DbConn,
    nt: Notify,
) -> EmptyResult {
    let data: ImportData = data.into_inner().data;
    let org_id = query.into_inner().organization_id;

    // Read and create the collections
    let collections: Vec<_> = data
        .Collections
        .into_iter()
        .map(|coll| {
            let collection = Collection::new(org_id.clone(), coll.Name);
            if collection.save(&conn).is_err() {
                err!("Failed to create Collection");
            }

            Ok(collection)
        })
        .collect();

    // Read the relations between collections and ciphers
    let mut relations = Vec::new();
    for relation in data.CollectionRelationships {
        relations.push((relation.Key, relation.Value));
    }

    let headers: Headers = headers.into();

    // Read and create the ciphers
    let ciphers: Vec<_> = data
        .Ciphers
        .into_iter()
        .map(|cipher_data| {
            let mut cipher = Cipher::new(cipher_data.Type, cipher_data.Name.clone());
            update_cipher_from_data(&mut cipher, cipher_data, &headers, false, &conn, &nt, UpdateType::CipherCreate)
                .ok();
            cipher
        })
        .collect();

    // Assign the collections
    for (cipher_index, coll_index) in relations {
        let cipher_id = &ciphers[cipher_index].uuid;
        let coll = &collections[coll_index];
        let coll_id = match coll {
            Ok(coll) => coll.uuid.as_str(),
            Err(_) => err!("Failed to assign to collection"),
        };

        CollectionCipher::save(cipher_id, coll_id, &conn)?;
    }

    let mut user = headers.user;
    user.update_revision(&conn)
}

#[get("/organizations/<org_id>/policies")]
fn list_policies(org_id: String, _headers: AdminHeaders, conn: DbConn) -> Json<Value> {
    let policies = OrgPolicy::find_by_org(&org_id, &conn);
    let policies_json: Vec<Value> = policies.iter().map(OrgPolicy::to_json).collect();

    Json(json!({
        "Data": policies_json,
        "Object": "list",
        "ContinuationToken": null
    }))
}

#[get("/organizations/<org_id>/policies/token?<token>")]
fn list_policies_token(org_id: String, token: String, conn: DbConn) -> JsonResult {
    let invite = crate::auth::decode_invite(&token)?;

    let invite_org_id = match invite.org_id {
        Some(invite_org_id) => invite_org_id,
        None => err!("Invalid token"),
    };

    if invite_org_id != org_id {
        err!("Token doesn't match request organization");
    }

    // TODO: We receive the invite token as ?token=<>, validate it contains the org id
    let policies = OrgPolicy::find_by_org(&org_id, &conn);
    let policies_json: Vec<Value> = policies.iter().map(OrgPolicy::to_json).collect();

    Ok(Json(json!({
        "Data": policies_json,
        "Object": "list",
        "ContinuationToken": null
    })))
}

#[get("/organizations/<org_id>/policies/<pol_type>")]
fn get_policy(org_id: String, pol_type: i32, _headers: AdminHeaders, conn: DbConn) -> JsonResult {
    let pol_type_enum = match OrgPolicyType::from_i32(pol_type) {
        Some(pt) => pt,
        None => err!("Invalid or unsupported policy type"),
    };

    let policy = match OrgPolicy::find_by_org_and_type(&org_id, pol_type, &conn) {
        Some(p) => p,
        None => OrgPolicy::new(org_id, pol_type_enum, "{}".to_string()),
    };

    Ok(Json(policy.to_json()))
}

#[derive(Deserialize)]
struct PolicyData {
    enabled: bool,
    #[serde(rename = "type")]
    _type: i32,
    data: Option<Value>,
}

#[put("/organizations/<org_id>/policies/<pol_type>", data = "<data>")]
fn put_policy(
    org_id: String,
    pol_type: i32,
    data: Json<PolicyData>,
    _headers: AdminHeaders,
    conn: DbConn,
) -> JsonResult {
    let data: PolicyData = data.into_inner();

    let pol_type_enum = match OrgPolicyType::from_i32(pol_type) {
        Some(pt) => pt,
        None => err!("Invalid policy type"),
    };

    // If enabling the TwoFactorAuthentication policy, remove this org's members that do have 2FA
    if pol_type_enum == OrgPolicyType::TwoFactorAuthentication && data.enabled {
        let org_members = UserOrganization::find_by_org(&org_id, &conn);

        for member in org_members.into_iter() {
            let user_twofactor_disabled = TwoFactor::find_by_user(&member.user_uuid, &conn).is_empty();

            // Policy only applies to non-Owner/non-Admin members who have accepted joining the org
            if user_twofactor_disabled
                && member.atype < UserOrgType::Admin
                && member.status != UserOrgStatus::Invited as i32
            {
                if CONFIG.mail_enabled() {
                    let org = Organization::find_by_uuid(&member.org_uuid, &conn).unwrap();
                    let user = User::find_by_uuid(&member.user_uuid, &conn).unwrap();

                    mail::send_2fa_removed_from_org(&user.email, &org.name)?;
                }
                member.delete(&conn)?;
            }
        }
    }

    // If enabling the SingleOrg policy, remove this org's members that are members of other orgs
    if pol_type_enum == OrgPolicyType::SingleOrg && data.enabled {
        let org_members = UserOrganization::find_by_org(&org_id, &conn);

        for member in org_members.into_iter() {
            // Policy only applies to non-Owner/non-Admin members who have accepted joining the org
            if member.atype < UserOrgType::Admin && member.status != UserOrgStatus::Invited as i32 {
                let is_member_of_another_org = UserOrganization::find_any_state_by_user(&member.user_uuid, &conn)
                    .into_iter()
                    // Other UserOrganization's where they have accepted being a member of
                    .filter(|uo| uo.uuid != member.uuid && uo.status != UserOrgStatus::Invited as i32)
                    .count()
                    > 1;

                if is_member_of_another_org {
                    if CONFIG.mail_enabled() {
                        let org = Organization::find_by_uuid(&member.org_uuid, &conn).unwrap();
                        let user = User::find_by_uuid(&member.user_uuid, &conn).unwrap();

                        mail::send_single_org_removed_from_org(&user.email, &org.name)?;
                    }
                    member.delete(&conn)?;
                }
            }
        }
    }

    let mut policy = match OrgPolicy::find_by_org_and_type(&org_id, pol_type, &conn) {
        Some(p) => p,
        None => OrgPolicy::new(org_id, pol_type_enum, "{}".to_string()),
    };

    policy.enabled = data.enabled;
    policy.data = serde_json::to_string(&data.data)?;
    policy.save(&conn)?;

    Ok(Json(policy.to_json()))
}

#[allow(unused_variables)]
#[get("/organizations/<org_id>/tax")]
fn get_organization_tax(org_id: String, _headers: Headers, _conn: DbConn) -> EmptyResult {
    // Prevent a 404 error, which also causes Javascript errors.
    err!("Only allowed when not self hosted.")
}

#[get("/plans")]
fn get_plans(_headers: Headers, _conn: DbConn) -> Json<Value> {
    Json(json!({
        "Object": "list",
        "Data": [
        {
            "Object": "plan",
            "Type": 0,
            "Product": 0,
            "Name": "Free",
            "IsAnnual": false,
            "NameLocalizationKey": "planNameFree",
            "DescriptionLocalizationKey": "planDescFree",
            "CanBeUsedByBusiness": false,
            "BaseSeats": 2,
            "BaseStorageGb": null,
            "MaxCollections": 2,
            "MaxUsers": 2,
            "HasAdditionalSeatsOption": false,
            "MaxAdditionalSeats": null,
            "HasAdditionalStorageOption": false,
            "MaxAdditionalStorage": null,
            "HasPremiumAccessOption": false,
            "TrialPeriodDays": null,
            "HasSelfHost": false,
            "HasPolicies": false,
            "HasGroups": false,
            "HasDirectory": false,
            "HasEvents": false,
            "HasTotp": false,
            "Has2fa": false,
            "HasApi": false,
            "HasSso": false,
            "UsersGetPremium": false,
            "UpgradeSortOrder": -1,
            "DisplaySortOrder": -1,
            "LegacyYear": null,
            "Disabled": false,
            "StripePlanId": null,
            "StripeSeatPlanId": null,
            "StripeStoragePlanId": null,
            "StripePremiumAccessPlanId": null,
            "BasePrice": 0.0,
            "SeatPrice": 0.0,
            "AdditionalStoragePricePerGb": 0.0,
            "PremiumAccessOptionPrice": 0.0
            }
        ],
        "ContinuationToken": null
    }))
}

#[get("/plans/sales-tax-rates")]
fn get_plans_tax_rates(_headers: Headers, _conn: DbConn) -> Json<Value> {
    // Prevent a 404 error, which also causes Javascript errors.
    Json(json!({
        "Object": "list",
        "Data": [],
        "ContinuationToken": null
    }))
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case, dead_code)]
struct OrgImportGroupData {
    Name: String,       // "GroupName"
    ExternalId: String, // "cn=GroupName,ou=Groups,dc=example,dc=com"
    Users: Vec<String>, // ["uid=user,ou=People,dc=example,dc=com"]
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct OrgImportUserData {
    Email: String, // "user@maildomain.net"
    #[allow(dead_code)]
    ExternalId: String, // "uid=user,ou=People,dc=example,dc=com"
    Deleted: bool,
}

#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct OrgImportData {
    #[allow(dead_code)]
    Groups: Vec<OrgImportGroupData>,
    OverwriteExisting: bool,
    Users: Vec<OrgImportUserData>,
}

#[post("/organizations/<org_id>/import", data = "<data>")]
fn import(org_id: String, data: JsonUpcase<OrgImportData>, headers: Headers, conn: DbConn) -> EmptyResult {
    let data = data.into_inner().data;

    // TODO: Currently we aren't storing the externalId's anywhere, so we also don't have a way
    // to differentiate between auto-imported users and manually added ones.
    // This means that this endpoint can end up removing users that were added manually by an admin,
    // as opposed to upstream which only removes auto-imported users.

    // User needs to be admin or owner to use the Directry Connector
    match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
        Some(user_org) if user_org.atype >= UserOrgType::Admin => { /* Okay, nothing to do */ }
        Some(_) => err!("User has insufficient permissions to use Directory Connector"),
        None => err!("User not part of organization"),
    };

    for user_data in &data.Users {
        if user_data.Deleted {
            // If user is marked for deletion and it exists, delete it
            if let Some(user_org) = UserOrganization::find_by_email_and_org(&user_data.Email, &org_id, &conn) {
                user_org.delete(&conn)?;
            }

        // If user is not part of the organization, but it exists
        } else if UserOrganization::find_by_email_and_org(&user_data.Email, &org_id, &conn).is_none() {
            if let Some(user) = User::find_by_mail(&user_data.Email, &conn) {
                let user_org_status = if CONFIG.mail_enabled() {
                    UserOrgStatus::Invited as i32
                } else {
                    UserOrgStatus::Accepted as i32 // Automatically mark user as accepted if no email invites
                };

                let mut new_org_user = UserOrganization::new(user.uuid.clone(), org_id.clone());
                new_org_user.access_all = false;
                new_org_user.atype = UserOrgType::User as i32;
                new_org_user.status = user_org_status;

                new_org_user.save(&conn)?;

                if CONFIG.mail_enabled() {
                    let org_name = match Organization::find_by_uuid(&org_id, &conn) {
                        Some(org) => org.name,
                        None => err!("Error looking up organization"),
                    };

                    mail::send_invite(
                        &user_data.Email,
                        &user.uuid,
                        Some(org_id.clone()),
                        Some(new_org_user.uuid),
                        &org_name,
                        Some(headers.user.email.clone()),
                    )?;
                }
            }
        }
    }

    // If this flag is enabled, any user that isn't provided in the Users list will be removed (by default they will be kept unless they have Deleted == true)
    if data.OverwriteExisting {
        for user_org in UserOrganization::find_by_org_and_type(&org_id, UserOrgType::User as i32, &conn) {
            if let Some(user_email) = User::find_by_uuid(&user_org.user_uuid, &conn).map(|u| u.email) {
                if !data.Users.iter().any(|u| u.Email == user_email) {
                    user_org.delete(&conn)?;
                }
            }
        }
    }

    Ok(())
}