users.rs 7.56 KB
Newer Older
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
1 2
use uuid::Uuid;
use diesel::prelude::*;
3
use diesel::result::Error as DieselError;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
4
use diesel_derive_enum::DbEnum;
5
use rocket::{State, request::{FromRequest, Request, Outcome}};
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
6
use serde::{Serialize, Deserialize};
7
use rocket::http::Status;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
8 9 10
use chrono::serde::ts_seconds;
use chrono::prelude::{DateTime, Utc};
use chrono::Duration;
11 12
// TODO: Maybe just use argon2 crate directly
use djangohashers::{make_password_with_algorithm, check_password, HasherError, Algorithm};
13 14 15 16 17 18 19
use jsonwebtoken::{
    encode, decode,
    Header, Validation,
    Algorithm as JwtAlgorithm, EncodingKey, DecodingKey,
    errors::Result as JwtResult,
    errors::ErrorKind as JwtErrorKind
};
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
20 21

use crate::schema::*;
22
use crate::DbConn;
23 24 25 26 27
use crate::config::Config;


const BEARER: &'static str = "Bearer ";
const AUTH_HEADER: &'static str = "Authentication";
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
28

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
29

30 31
#[derive(Debug, DbEnum, Deserialize)]
#[serde(rename_all = "snake_case")]
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
32 33 34 35 36
pub enum Role {
    Admin,
    ZoneAdmin,
}

37 38 39
// TODO: Store Uuid instead of string??
// TODO: Store role as Role and not String.
#[derive(Debug, Queryable, Identifiable, Insertable)]
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
40 41 42 43 44 45
#[table_name = "user"]
pub struct User {
    pub id: String,
    pub role: String,
}

46
#[derive(Debug, Queryable, Identifiable, Insertable)]
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
47 48 49 50 51 52 53 54
#[table_name = "localuser"]
#[primary_key(user_id)]
pub struct LocalUser {
    pub user_id: String,
    pub username: String,
    pub password: String,
}

55 56 57 58 59 60 61 62
#[derive(Debug, Deserialize)]
pub struct CreateUserRequest {
    pub username: String,
    pub password: String,
    pub email: String,
    pub role: Option<Role>
}

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
63 64 65 66 67
// pub struct LdapUserAssociation {
//     user_id: Uuid,
//     ldap_id: String
// }

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
#[derive(Debug, Serialize, Deserialize)]
pub struct AuthClaims {
    pub jti: String,
    pub sub: String,
    #[serde(with = "ts_seconds")]
    pub exp: DateTime<Utc>,
    #[serde(with = "ts_seconds")]
    pub iat: DateTime<Utc>,
}

#[derive(Debug, Serialize)]
pub struct AuthTokenResponse {
    pub token: String
}

#[derive(Debug, Deserialize)]
pub struct AuthTokenRequest {
    pub username: String,
    pub password: String,
}

89
#[derive(Debug)]
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
90
pub struct UserInfo {
91 92 93
    pub id: String,
    pub role: String,
    pub username: String,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
94 95
}

96 97
#[rocket::async_trait]
impl<'r> FromRequest<'r> for UserInfo {
98 99
    type Error = UserError;

100
    async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
101 102 103 104 105 106 107 108 109 110 111 112
        let auth_header = match request.headers().get_one(AUTH_HEADER) {
            None => return Outcome::Forward(()),
            Some(auth_header) => auth_header,
        };

        let token = if auth_header.starts_with(BEARER) {
            auth_header.trim_start_matches(BEARER)
        } else {
            return Outcome::Failure((Status::BadRequest, UserError::MalformedHeader))
        };

        // TODO: Better error handling
113 114
        let config = request.guard::<State<Config>>().await.unwrap();
        let conn = request.guard::<DbConn>().await.unwrap();
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129
        let token_data = AuthClaims::decode(
            token, &config.web_app.secret
        ).map_err(|e| match e.into_kind() {
            JwtErrorKind::ExpiredSignature => (Status::Unauthorized, UserError::ExpiredToken),
            _ => (Status::BadRequest, UserError::BadToken),
        });

        let token_data = match token_data {
            Err(e) => return Outcome::Failure(e),
            Ok(data) => data
        };

        let user_id = token_data.sub;

130 131 132 133 134 135 136
        conn.run(|c| {
            match LocalUser::get_user_by_uuid(c, user_id) {
                Err(UserError::NotFound) => Outcome::Failure((Status::NotFound, UserError::NotFound)),
                Err(e) => Outcome::Failure((Status::InternalServerError, e)),
                Ok(d) => Outcome::Success(d),
            }
        }).await
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
137 138
    }
}
139 140 141 142 143

#[derive(Debug)]
pub enum UserError {
    NotFound,
    UserExists,
144 145 146 147
    BadToken,
    ExpiredToken,
    MalformedHeader,
    PermissionDenied,
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    DbError(DieselError),
    PasswordError(HasherError),
}

impl From<DieselError> for UserError {
    fn from(e: DieselError) -> Self {
        match e {
            DieselError::NotFound => UserError::NotFound,
            DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => UserError::UserExists,
            other => UserError::DbError(other)
        }
    }
}

impl From<HasherError> for UserError {
    fn from(e: HasherError) -> Self {
        match e {
            other => UserError::PasswordError(other)
        }
    }
}

impl LocalUser {
171
    pub fn create_user(conn: &diesel::SqliteConnection, user_request: CreateUserRequest) -> Result<UserInfo, UserError> {
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
        use crate::schema::localuser::dsl::*;
        use crate::schema::user::dsl::*;

        let new_user_id = Uuid::new_v4().to_simple().to_string();

        let new_user = User {
            id: new_user_id.clone(),
            // TODO: Use role from request
            role: "zoneadmin".into(),
        };

        let new_localuser = LocalUser {
            user_id: new_user_id.clone(),
            username: user_request.username.clone(),
            password: make_password_with_algorithm(&user_request.password, Algorithm::Argon2),
        };

        let res = UserInfo {
            id: new_user.id.clone(),
            role: new_user.role.clone(),
            username: new_localuser.username.clone(),
        };

        conn.immediate_transaction(|| -> diesel::QueryResult<()> {
            diesel::insert_into(user)
                .values(new_user)
198
                .execute(conn)?;
199 200 201

            diesel::insert_into(localuser)
                .values(new_localuser)
202
                .execute(conn)?;
203 204 205 206 207 208 209 210

            Ok(())
        })?;

        Ok(res)
    }

    pub fn get_user_by_creds(
211
        conn: &diesel::SqliteConnection,
212 213 214 215 216 217 218 219 220
        request_username: &str,
        request_password: &str
    ) ->  Result<UserInfo, UserError> {

        use crate::schema::localuser::dsl::*;
        use crate::schema::user::dsl::*;

        let (client_user, client_localuser): (User, LocalUser) = user.inner_join(localuser)
            .filter(username.eq(request_username))
221
            .get_result(conn)?;
222 223 224 225 226 227 228 229 230 231 232 233

        if !check_password(&request_password, &client_localuser.password)? {
            return Err(UserError::NotFound);
        }

        Ok(UserInfo {
            id: client_user.id,
            role: client_user.role,
            username: client_localuser.username,
        })
    }

234
    pub fn get_user_by_uuid(conn: &diesel::SqliteConnection, request_user_id: String) -> Result<UserInfo, UserError> {
235 236 237 238 239
        use crate::schema::localuser::dsl::*;
        use crate::schema::user::dsl::*;

        let (client_user, client_localuser): (User, LocalUser) = user.inner_join(localuser)
            .filter(id.eq(request_user_id))
240
            .get_result(conn)?;
241 242 243 244 245 246

        Ok(UserInfo {
            id: client_user.id,
            role: client_user.role,
            username: client_localuser.username,
        })
247 248 249
    }

}
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

impl AuthClaims {
    pub fn new(user_info: &UserInfo, token_duration: Duration) -> AuthClaims {
        let jti = Uuid::new_v4().to_simple().to_string();
        let iat = Utc::now();
        let exp = iat + token_duration;

        AuthClaims {
            jti: jti,
            sub: user_info.id.clone(),
            exp: exp,
            iat: iat,
        }
    }

265 266 267 268 269 270 271 272
    pub fn decode(token: &str, secret: &str) -> JwtResult<AuthClaims> {
        decode::<AuthClaims>(
            token,
            &DecodingKey::from_secret(secret.as_ref()),
            &Validation::new(JwtAlgorithm::HS256)
        ).and_then(|data| Ok(data.claims))
    }

273
    pub fn encode(self, secret: &str) -> JwtResult<String> {
274
        encode(&Header::default(), &self, &EncodingKey::from_secret(secret.as_ref()))
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
275 276
    }
}