aboutsummaryrefslogtreecommitdiff
path: root/src/api/admin.rs
blob: 72c9d584dd27a43ab238c71110585faa9b0b57b5 (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
use rocket_contrib::json::Json;
use serde_json::Value;

use crate::api::{JsonResult, JsonUpcase};
use crate::CONFIG;

use crate::auth::{encode_jwt, generate_invite_claims};
use crate::mail;
use crate::db::models::*;
use crate::db::DbConn;

use rocket::request::{self, FromRequest, Request};
use rocket::{Outcome, Route};

pub fn routes() -> Vec<Route> {
    routes![get_users, invite_user, delete_user]
}

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

#[get("/users")]
fn get_users(_token: AdminToken, conn: DbConn) -> JsonResult {
    let users = User::get_all(&conn);
    let users_json: Vec<Value> = users.iter().map(|u| u.to_json(&conn)).collect();

    Ok(Json(Value::Array(users_json)))
}

#[post("/invite", data = "<data>")]
fn invite_user(data: JsonUpcase<InviteData>, _token: AdminToken, conn: DbConn) -> JsonResult {
    let data: InviteData = data.into_inner().data;
    let email = data.Email.clone();
    if User::find_by_mail(&data.Email, &conn).is_some() {
        err!("User already exists")
    }

    if !CONFIG.invitations_allowed {
        err!("Invitations are not allowed")
    }

    let mut invitation = Invitation::new(data.Email);
    invitation.save(&conn)?;

    if let Some(ref mail_config) = CONFIG.mail {
        let mut user = User::new(email);
        user.save(&conn)?;
        let org_id = String::from("00000000-0000-0000-0000-000000000000");
        let claims = generate_invite_claims(
            user.uuid.to_string(),
            user.email.clone(),
            org_id.clone(),
            None,
            None,
        );
        let org_name = "bitwarden_rs";
        let invite_token = encode_jwt(&claims);
        mail::send_invite(&user.email, &org_id, &user.uuid, &invite_token, &org_name, mail_config)?;
    }

    Ok(Json(json!({})))
}

#[post("/users/<uuid>/delete")]
fn delete_user(uuid: String, _token: AdminToken, conn: DbConn) -> JsonResult {
    let user = match User::find_by_uuid(&uuid, &conn) {
        Some(user) => user,
        None => err!("User doesn't exist"),
    };

    user.delete(&conn)?;
    Ok(Json(json!({})))
}

pub struct AdminToken {}

impl<'a, 'r> FromRequest<'a, 'r> for AdminToken {
    type Error = &'static str;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        let config_token = match CONFIG.admin_token.as_ref() {
            Some(token) => token,
            None => err_handler!("Admin panel is disabled"),
        };

        // Get access_token
        let access_token: &str = match request.headers().get_one("Authorization") {
            Some(a) => match a.rsplit("Bearer ").next() {
                Some(split) => split,
                None => err_handler!("No access token provided"),
            },
            None => err_handler!("No access token provided"),
        };

        // TODO: What authentication to use?
        // Option 1: Make it a config option
        // Option 2: Generate random token, and
        // Option 2a: Send it to admin email, like upstream
        // Option 2b: Print in console or save to data dir, so admin can check

        if access_token != config_token {
            err_handler!("Invalid admin token")
        }

        Outcome::Success(AdminToken {})
    }
}