users.rs 7.48 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::request::{FromRequest, Request, Outcome, State};
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
}

impl<'a, 'r> FromRequest<'a, 'r> for UserInfo {
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    type Error = UserError;

    fn from_request(request: &'a Request<'r>) -> Outcome<UserInfo, UserError> {
        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
        let config = request.guard::<State<Config>>().unwrap();
        let conn = request.guard::<DbConn>().unwrap();
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
114

115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
        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;
        let user_info = match LocalUser::get_user_by_uuid(&conn, user_id) {
            Err(UserError::NotFound) => return Outcome::Failure((Status::NotFound, UserError::NotFound)),
            Err(e) => return Outcome::Failure((Status::InternalServerError, e)),
            Ok(d) => d,
        };

        return Outcome::Success(user_info)
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
135 136
    }
}
137 138 139 140 141

#[derive(Debug)]
pub enum UserError {
    NotFound,
    UserExists,
142 143 144 145
    BadToken,
    ExpiredToken,
    MalformedHeader,
    PermissionDenied,
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
    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 {
    pub fn create_user(conn: &DbConn, user_request: CreateUserRequest) -> Result<UserInfo, UserError> {
        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)
                .execute(&**conn)?;

            diesel::insert_into(localuser)
                .values(new_localuser)
                .execute(&**conn)?;

            Ok(())
        })?;

        Ok(res)
    }

    pub fn get_user_by_creds(
        conn: &DbConn,
        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))
            .get_result(&**conn)?;

        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,
        })
    }

232 233 234 235 236 237 238 239 240 241 242 243 244
    pub fn get_user_by_uuid(conn: &DbConn, request_user_id: String) -> 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(id.eq(request_user_id))
            .get_result(&**conn)?;

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

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

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,
        }
    }

263 264 265 266 267 268 269 270
    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))
    }

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