aboutsummaryrefslogtreecommitdiff
path: root/src/db/models/organization.rs
blob: 4bb55912d934dff9a1732c4b42b967b91a60ec13 (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
use serde_json::Value as JsonValue;

use uuid::Uuid;

#[derive(Debug, Identifiable, Queryable, Insertable)]
#[table_name = "organizations"]
#[primary_key(uuid)]
pub struct Organization {
    pub uuid: String,
    pub name: String,
    pub billing_email: String,
}

#[derive(Debug, Identifiable, Queryable, Insertable)]
#[table_name = "users_organizations"]
#[primary_key(uuid)]
pub struct UserOrganization {
    pub uuid: String,
    pub user_uuid: String,
    pub org_uuid: String,

    pub access_all: bool,
    pub key: String,
    pub status: i32,
    pub type_: i32,
}

pub enum UserOrgStatus {
    _Invited = 0, // Unused, users are accepted automatically
    Accepted = 1,
    Confirmed = 2,
}

pub enum UserOrgType {
    Owner = 0,
    Admin = 1,
    User = 2,
}

impl UserOrgType {
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "0" | "Owner" => Some(UserOrgType::Owner),
            "1" | "Admin" => Some(UserOrgType::Admin),
            "2" | "User" => Some(UserOrgType::User),
            _ => None,
        }
    }
}

/// Local methods
impl Organization {
    pub fn new(name: String, billing_email: String) -> Self {
        Self {
            uuid: Uuid::new_v4().to_string(),

            name,
            billing_email,
        }
    }

    pub fn to_json(&self) -> JsonValue {
        json!({
            "Id": self.uuid,
            "Name": self.name,
            "Seats": 10,
            "MaxCollections": 10,

            "Use2fa": true,
            "UseDirectory": false,
            "UseEvents": false,
            "UseGroups": false,
            "UseTotp": true,

            "BusinessName": null,
            "BusinessAddress1":	null,
            "BusinessAddress2":	null,
            "BusinessAddress3":	null,
            "BusinessCountry": null,
            "BusinessTaxNumber": null,

            "BillingEmail": self.billing_email,
            "Plan": "TeamsAnnually",
            "PlanType": 5, // TeamsAnnually plan

            "Object": "organization",
        })
    }
}

impl UserOrganization {
    pub fn new(user_uuid: String, org_uuid: String) -> Self {
        Self {
            uuid: Uuid::new_v4().to_string(),

            user_uuid,
            org_uuid,

            access_all: false,
            key: String::new(),
            status: UserOrgStatus::Accepted as i32,
            type_: UserOrgType::User as i32,
        }
    }
}


use diesel;
use diesel::prelude::*;
use db::DbConn;
use db::schema::organizations;
use db::schema::users_organizations;

/// Database methods
impl Organization {
    pub fn save(&mut self, conn: &DbConn) -> bool {
        match diesel::replace_into(organizations::table)
            .values(&*self)
            .execute(&**conn) {
            Ok(1) => true, // One row inserted
            _ => false,
        }
    }

    pub fn delete(self, conn: &DbConn) -> QueryResult<()> {
        use super::{Cipher, Collection};

        Cipher::delete_all_by_organization(&self.uuid, &conn)?;
        Collection::delete_all_by_organization(&self.uuid, &conn)?;
        UserOrganization::delete_all_by_organization(&self.uuid, &conn)?;

        diesel::delete(
            organizations::table.filter(
                organizations::uuid.eq(self.uuid)
            )
        ).execute(&**conn).and(Ok(()))
    }

    pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
        organizations::table
            .filter(organizations::uuid.eq(uuid))
            .first::<Self>(&**conn).ok()
    }
}

impl UserOrganization {
    pub fn to_json(&self, conn: &DbConn) -> JsonValue {
        let org = Organization::find_by_uuid(&self.org_uuid, conn).unwrap();

        json!({
            "Id": self.org_uuid,
            "Name": org.name,
            "Seats": 10,
            "MaxCollections": 10,

            "Use2fa": true,
            "UseDirectory": false,
            "UseEvents": false,
            "UseGroups": false,
            "UseTotp": true,

            "MaxStorageGb": 10, // The value doesn't matter, we don't check server-side

            // These are per user
            "Key": self.key,
            "Status": self.status,
            "Type": self.type_,
            "Enabled": true,

            "Object": "profileOrganization",
        })
    }

    pub fn to_json_user_details(&self, conn: &DbConn) -> JsonValue {
        use super::User;
        let user = User::find_by_uuid(&self.user_uuid, conn).unwrap();

        json!({
            "Id": self.uuid,
            "UserId": self.user_uuid,
            "Name": user.name,
            "Email": user.email,

            "Status": self.status,
            "Type": self.type_,
            "AccessAll": self.access_all,

            "Object": "organizationUserUserDetails",
        })
    }

    pub fn to_json_collection_user_details(&self, read_only: &bool, conn: &DbConn) -> JsonValue {
        use super::User;
        let user = User::find_by_uuid(&self.user_uuid, conn).unwrap();

        json!({
            "OrganizationUserId": self.uuid,
            "AccessAll": self.access_all,
            "Name": user.name,
            "Email": user.email,
            "Type": self.type_,
            "Status": self.status,
            "ReadOnly": read_only,
            "Object": "collectionUser",
        })
    }

    pub fn to_json_details(&self, conn: &DbConn) -> JsonValue {        
        let coll_uuids = if self.access_all { 
            vec![] // If we have complete access, no need to fill the array
        } else {
            use super::CollectionUser;
            let collections = CollectionUser::find_by_organization_and_user_uuid(&self.org_uuid, &self.user_uuid, conn);
            collections.iter().map(|c| json!({"Id": c.collection_uuid, "ReadOnly": c.read_only})).collect()
        };

        json!({
            "Id": self.uuid,
            "UserId": self.user_uuid,

            "Status": self.status,
            "Type": self.type_,
            "AccessAll": self.access_all,
            "Collections": coll_uuids,

            "Object": "organizationUserDetails",
        })
    }

    pub fn save(&mut self, conn: &DbConn) -> bool {
        match diesel::replace_into(users_organizations::table)
            .values(&*self)
            .execute(&**conn) {
            Ok(1) => true, // One row inserted
            _ => false,
        }
    }

    pub fn delete(self, conn: &DbConn) -> QueryResult<()> {
        use super::CollectionUser;

        CollectionUser::delete_all_by_user(&self.user_uuid, &conn)?;

        diesel::delete(
            users_organizations::table.filter(
                users_organizations::uuid.eq(self.uuid)
            )
        ).execute(&**conn).and(Ok(()))
    }

    pub fn delete_all_by_organization(org_uuid: &str, conn: &DbConn) -> QueryResult<()> {
        for user_org in Self::find_by_org(&org_uuid, &conn) {
            user_org.delete(&conn)?;
        }
        Ok(())
    }

    pub fn has_full_access(self) -> bool {
        self.access_all || self.type_ < UserOrgType::User as i32
    }

    pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
        users_organizations::table
            .filter(users_organizations::uuid.eq(uuid))
            .first::<Self>(&**conn).ok()
    }

    pub fn find_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Self> {
        users_organizations::table
            .filter(users_organizations::user_uuid.eq(user_uuid))
            .filter(users_organizations::status.eq(UserOrgStatus::Confirmed as i32))
            .load::<Self>(&**conn).unwrap_or(vec![])
    }

    pub fn find_by_org(org_uuid: &str, conn: &DbConn) -> Vec<Self> {
        users_organizations::table
            .filter(users_organizations::org_uuid.eq(org_uuid))
            .load::<Self>(&**conn).expect("Error loading user organizations")
    }

    pub fn find_by_org_and_type(org_uuid: &str, type_: i32, conn: &DbConn) -> Vec<Self> {
        users_organizations::table
            .filter(users_organizations::org_uuid.eq(org_uuid))
            .filter(users_organizations::type_.eq(type_))
            .load::<Self>(&**conn).expect("Error loading user organizations")
    }

    pub fn find_by_user_and_org(user_uuid: &str, org_uuid: &str, conn: &DbConn) -> Option<Self> {
        users_organizations::table
            .filter(users_organizations::user_uuid.eq(user_uuid))
            .filter(users_organizations::org_uuid.eq(org_uuid))
            .first::<Self>(&**conn).ok()
    }
}