2018-08-25 22:07:59 +00:00
|
|
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
use rocket::request::LenientForm;
|
|
|
|
use rocket::Route;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-10-10 18:40:39 +00:00
|
|
|
use rocket_contrib::json::Json;
|
|
|
|
use serde_json::Value;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-07-12 19:46:50 +00:00
|
|
|
use num_traits::FromPrimitive;
|
|
|
|
|
2018-02-10 00:00:55 +00:00
|
|
|
use db::models::*;
|
2018-07-12 19:46:50 +00:00
|
|
|
use db::DbConn;
|
2018-02-17 19:47:13 +00:00
|
|
|
|
2018-07-12 19:46:50 +00:00
|
|
|
use util::{self, JsonMap};
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
use api::{ApiResult, EmptyResult, JsonResult};
|
2018-02-17 19:47:13 +00:00
|
|
|
|
2018-07-13 13:58:50 +00:00
|
|
|
use CONFIG;
|
|
|
|
|
2018-02-10 00:00:55 +00:00
|
|
|
pub fn routes() -> Vec<Route> {
|
2018-07-12 19:46:50 +00:00
|
|
|
routes![login]
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
|
|
|
|
2018-10-10 18:40:39 +00:00
|
|
|
#[post("/connect/token", data = "<data>")]
|
2018-10-17 20:25:28 +00:00
|
|
|
fn login(data: LenientForm<ConnectData>, conn: DbConn, socket: Option<SocketAddr>) -> JsonResult {
|
2018-10-10 18:40:39 +00:00
|
|
|
let data: ConnectData = data.into_inner();
|
2018-10-17 20:25:28 +00:00
|
|
|
validate_data(&data)?;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-06-01 13:08:03 +00:00
|
|
|
match data.grant_type {
|
2018-10-17 20:25:28 +00:00
|
|
|
GrantType::refresh_token => _refresh_login(data, conn),
|
|
|
|
GrantType::password => _password_login(data, conn, socket),
|
2018-06-01 13:08:03 +00:00
|
|
|
}
|
|
|
|
}
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
fn _refresh_login(data: ConnectData, conn: DbConn) -> JsonResult {
|
2018-06-01 13:08:03 +00:00
|
|
|
// Extract token
|
2018-10-17 20:25:28 +00:00
|
|
|
let token = data.refresh_token.unwrap();
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-06-01 13:08:03 +00:00
|
|
|
// Get device by refresh token
|
2018-10-17 20:25:28 +00:00
|
|
|
let mut device = match Device::find_by_refresh_token(&token, &conn) {
|
2018-06-01 13:08:03 +00:00
|
|
|
Some(device) => device,
|
2018-07-12 19:46:50 +00:00
|
|
|
None => err!("Invalid refresh token"),
|
2018-06-01 13:08:03 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// COMMON
|
|
|
|
let user = User::find_by_uuid(&device.user_uuid, &conn).unwrap();
|
|
|
|
let orgs = UserOrganization::find_by_user(&user.uuid, &conn);
|
|
|
|
|
|
|
|
let (access_token, expires_in) = device.refresh_tokens(&user, orgs);
|
2018-10-14 12:28:12 +00:00
|
|
|
match device.save(&conn) {
|
2018-10-17 20:25:28 +00:00
|
|
|
Ok(()) => Ok(Json(json!({
|
|
|
|
"access_token": access_token,
|
|
|
|
"expires_in": expires_in,
|
|
|
|
"token_type": "Bearer",
|
|
|
|
"refresh_token": device.refresh_token,
|
|
|
|
"Key": user.key,
|
|
|
|
"PrivateKey": user.private_key,
|
|
|
|
}))),
|
|
|
|
Err(_) => err!("Failed to add device to user"),
|
2018-10-14 12:28:12 +00:00
|
|
|
}
|
2018-06-01 13:08:03 +00:00
|
|
|
}
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
fn _password_login(data: ConnectData, conn: DbConn, remote: Option<SocketAddr>) -> JsonResult {
|
2018-08-25 22:07:59 +00:00
|
|
|
// Get the ip for error reporting
|
|
|
|
let ip = match remote {
|
|
|
|
Some(ip) => ip.ip(),
|
|
|
|
None => IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
|
|
|
|
};
|
|
|
|
|
2018-06-01 13:08:03 +00:00
|
|
|
// Validate scope
|
2018-10-17 20:25:28 +00:00
|
|
|
let scope = data.scope.as_ref().unwrap();
|
2018-06-01 13:08:03 +00:00
|
|
|
if scope != "api offline_access" {
|
|
|
|
err!("Scope not supported")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the user
|
2018-10-17 20:25:28 +00:00
|
|
|
let username = data.username.as_ref().unwrap();
|
2018-06-01 13:08:03 +00:00
|
|
|
let user = match User::find_by_mail(username, &conn) {
|
|
|
|
Some(user) => user,
|
2018-08-25 22:07:59 +00:00
|
|
|
None => err!(format!(
|
|
|
|
"Username or password is incorrect. Try again. IP: {}. Username: {}.",
|
|
|
|
ip, username
|
|
|
|
)),
|
2018-06-01 13:08:03 +00:00
|
|
|
};
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-06-01 13:08:03 +00:00
|
|
|
// Check password
|
2018-10-17 20:25:28 +00:00
|
|
|
let password = data.password.as_ref().unwrap();
|
2018-06-01 13:08:03 +00:00
|
|
|
if !user.check_valid_password(password) {
|
2018-08-25 22:07:59 +00:00
|
|
|
err!(format!(
|
|
|
|
"Username or password is incorrect. Try again. IP: {}. Username: {}.",
|
|
|
|
ip, username
|
|
|
|
))
|
2018-06-01 13:08:03 +00:00
|
|
|
}
|
2018-07-12 19:46:50 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
let device_type: i32 = util::try_parse_string(data.device_type.as_ref()).expect("Invalid type");
|
|
|
|
let device_id = data.device_identifier.clone().expect("Missing device id");
|
|
|
|
let device_name = data.device_name.clone().expect("Missing device name");
|
2018-06-01 13:08:03 +00:00
|
|
|
|
|
|
|
// Find device or create new
|
|
|
|
let mut device = match Device::find_by_uuid(&device_id, &conn) {
|
|
|
|
Some(device) => {
|
|
|
|
// Check if valid device
|
|
|
|
if device.user_uuid != user.uuid {
|
2018-10-12 14:20:10 +00:00
|
|
|
match device.delete(&conn) {
|
2018-10-17 20:25:28 +00:00
|
|
|
Ok(()) => Device::new(device_id, user.uuid.clone(), device_name, device_type),
|
|
|
|
Err(_) => err!("Tried to delete device not owned by user, but failed"),
|
2018-10-12 14:20:10 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
device
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
2018-06-01 13:08:03 +00:00
|
|
|
}
|
|
|
|
None => {
|
|
|
|
// Create new device
|
2018-10-17 20:25:28 +00:00
|
|
|
Device::new(device_id, user.uuid.clone(), device_name, device_type)
|
2018-06-01 13:08:03 +00:00
|
|
|
}
|
|
|
|
};
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
let twofactor_token = twofactor_auth(&user.uuid, &data.clone(), &mut device, &conn)?;
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-06-01 13:08:03 +00:00
|
|
|
// Common
|
2018-02-10 00:00:55 +00:00
|
|
|
let user = User::find_by_uuid(&device.user_uuid, &conn).unwrap();
|
2018-04-24 20:01:55 +00:00
|
|
|
let orgs = UserOrganization::find_by_user(&user.uuid, &conn);
|
|
|
|
|
|
|
|
let (access_token, expires_in) = device.refresh_tokens(&user, orgs);
|
2018-10-14 12:28:12 +00:00
|
|
|
if device.save(&conn).is_err() {
|
|
|
|
err!("Failed to add device to user")
|
|
|
|
}
|
2018-02-10 00:00:55 +00:00
|
|
|
|
2018-06-01 13:08:03 +00:00
|
|
|
let mut result = json!({
|
2018-02-10 00:00:55 +00:00
|
|
|
"access_token": access_token,
|
|
|
|
"expires_in": expires_in,
|
|
|
|
"token_type": "Bearer",
|
|
|
|
"refresh_token": device.refresh_token,
|
|
|
|
"Key": user.key,
|
2018-06-01 13:08:03 +00:00
|
|
|
"PrivateKey": user.private_key,
|
|
|
|
//"TwoFactorToken": "11122233333444555666777888999"
|
|
|
|
});
|
|
|
|
|
|
|
|
if let Some(token) = twofactor_token {
|
|
|
|
result["TwoFactorToken"] = Value::String(token);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Json(result))
|
|
|
|
}
|
|
|
|
|
2018-07-12 19:46:50 +00:00
|
|
|
fn twofactor_auth(
|
|
|
|
user_uuid: &str,
|
|
|
|
data: &ConnectData,
|
|
|
|
device: &mut Device,
|
|
|
|
conn: &DbConn,
|
|
|
|
) -> ApiResult<Option<String>> {
|
|
|
|
let twofactors_raw = TwoFactor::find_by_user(user_uuid, conn);
|
|
|
|
// Remove u2f challenge twofactors (impl detail)
|
|
|
|
let twofactors: Vec<_> = twofactors_raw.iter().filter(|tf| tf.type_ < 1000).collect();
|
|
|
|
|
|
|
|
let providers: Vec<_> = twofactors.iter().map(|tf| tf.type_).collect();
|
|
|
|
|
|
|
|
// No twofactor token if twofactor is disabled
|
2018-09-13 19:55:23 +00:00
|
|
|
if twofactors.is_empty() {
|
2018-07-12 19:46:50 +00:00
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
let provider = data.two_factor_provider.unwrap_or(providers[0]); // If we aren't given a two factor provider, asume the first one
|
2018-07-12 19:46:50 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
let twofactor_code = match data.two_factor_token {
|
|
|
|
Some(ref code) => code,
|
2018-07-12 19:46:50 +00:00
|
|
|
None => err_json!(_json_err_twofactor(&providers, user_uuid, conn)?),
|
|
|
|
};
|
|
|
|
|
|
|
|
let twofactor = twofactors.iter().filter(|tf| tf.type_ == provider).nth(0);
|
|
|
|
|
|
|
|
match TwoFactorType::from_i32(provider) {
|
|
|
|
Some(TwoFactorType::Remember) => {
|
2018-10-17 20:25:28 +00:00
|
|
|
match device.twofactor_remember {
|
|
|
|
Some(ref remember) if remember == twofactor_code => return Ok(None), // No twofactor token needed here
|
2018-07-12 19:46:50 +00:00
|
|
|
_ => err_json!(_json_err_twofactor(&providers, user_uuid, conn)?),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(TwoFactorType::Authenticator) => {
|
|
|
|
let twofactor = match twofactor {
|
|
|
|
Some(tf) => tf,
|
|
|
|
None => err!("TOTP not enabled"),
|
|
|
|
};
|
|
|
|
|
|
|
|
let totp_code: u64 = match twofactor_code.parse() {
|
|
|
|
Ok(code) => code,
|
|
|
|
_ => err!("Invalid TOTP code"),
|
|
|
|
};
|
|
|
|
|
|
|
|
if !twofactor.check_totp_code(totp_code) {
|
|
|
|
err_json!(_json_err_twofactor(&providers, user_uuid, conn)?)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(TwoFactorType::U2f) => {
|
|
|
|
use api::core::two_factor;
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
two_factor::validate_u2f_login(user_uuid, &twofactor_code, conn)?;
|
2018-07-12 19:46:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
_ => err!("Invalid two factor provider"),
|
|
|
|
}
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
if data.two_factor_remember.unwrap_or(0) == 1 {
|
2018-07-12 19:46:50 +00:00
|
|
|
Ok(Some(device.refresh_twofactor_remember()))
|
|
|
|
} else {
|
|
|
|
device.delete_twofactor_remember();
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn _json_err_twofactor(providers: &[i32], user_uuid: &str, conn: &DbConn) -> ApiResult<Value> {
|
|
|
|
use api::core::two_factor;
|
|
|
|
|
|
|
|
let mut result = json!({
|
2018-06-01 13:08:03 +00:00
|
|
|
"error" : "invalid_grant",
|
|
|
|
"error_description" : "Two factor required.",
|
2018-07-12 19:46:50 +00:00
|
|
|
"TwoFactorProviders" : providers,
|
|
|
|
"TwoFactorProviders2" : {} // { "0" : null }
|
|
|
|
});
|
|
|
|
|
|
|
|
for provider in providers {
|
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = Value::Null;
|
|
|
|
|
|
|
|
match TwoFactorType::from_i32(*provider) {
|
|
|
|
Some(TwoFactorType::Authenticator) => { /* Nothing to do for TOTP */ }
|
|
|
|
|
2018-07-13 13:58:50 +00:00
|
|
|
Some(TwoFactorType::U2f) if CONFIG.domain_set => {
|
2018-07-12 19:46:50 +00:00
|
|
|
let request = two_factor::generate_u2f_login(user_uuid, conn)?;
|
|
|
|
let mut challenge_list = Vec::new();
|
|
|
|
|
|
|
|
for key in request.registered_keys {
|
|
|
|
let mut challenge_map = JsonMap::new();
|
|
|
|
|
|
|
|
challenge_map.insert("appId".into(), Value::String(request.app_id.clone()));
|
|
|
|
challenge_map
|
|
|
|
.insert("challenge".into(), Value::String(request.challenge.clone()));
|
|
|
|
challenge_map.insert("version".into(), Value::String(key.version));
|
|
|
|
challenge_map.insert(
|
|
|
|
"keyHandle".into(),
|
|
|
|
Value::String(key.key_handle.unwrap_or_default()),
|
|
|
|
);
|
|
|
|
|
|
|
|
challenge_list.push(Value::Object(challenge_map));
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut map = JsonMap::new();
|
|
|
|
use serde_json;
|
|
|
|
let challenge_list_str = serde_json::to_string(&challenge_list).unwrap();
|
|
|
|
|
|
|
|
map.insert("Challenges".into(), Value::String(challenge_list_str));
|
|
|
|
result["TwoFactorProviders2"][provider.to_string()] = Value::Object(map);
|
|
|
|
}
|
|
|
|
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(result)
|
2018-06-01 13:08:03 +00:00
|
|
|
}
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
#[derive(FromForm, Debug, Clone)]
|
|
|
|
#[allow(non_snake_case)]
|
2018-02-10 00:00:55 +00:00
|
|
|
struct ConnectData {
|
|
|
|
grant_type: GrantType,
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
// Needed for grant_type="refresh_token"
|
|
|
|
refresh_token: Option<String>,
|
|
|
|
|
|
|
|
// Needed for grant_type="password"
|
|
|
|
client_id: Option<String>, // web, cli, desktop, browser, mobile
|
|
|
|
password: Option<String>,
|
|
|
|
scope: Option<String>,
|
|
|
|
username: Option<String>,
|
|
|
|
|
|
|
|
#[form(field = "deviceIdentifier")]
|
|
|
|
device_identifier: Option<String>,
|
|
|
|
#[form(field = "deviceName")]
|
|
|
|
device_name: Option<String>,
|
|
|
|
#[form(field = "deviceType")]
|
|
|
|
device_type: Option<String>,
|
|
|
|
|
|
|
|
// Needed for two-factor auth
|
|
|
|
#[form(field = "twoFactorProvider")]
|
|
|
|
two_factor_provider: Option<i32>,
|
|
|
|
#[form(field = "twoFactorToken")]
|
|
|
|
two_factor_token: Option<String>,
|
|
|
|
#[form(field = "twoFactorRemember")]
|
|
|
|
two_factor_remember: Option<i32>,
|
2018-07-12 19:46:50 +00:00
|
|
|
}
|
2018-02-15 18:05:57 +00:00
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
#[derive(FromFormValue, Debug, Clone, Copy)]
|
|
|
|
#[allow(non_camel_case_types)]
|
|
|
|
enum GrantType {
|
|
|
|
refresh_token,
|
|
|
|
password,
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
fn validate_data(data: &ConnectData) -> EmptyResult {
|
|
|
|
match data.grant_type {
|
|
|
|
GrantType::refresh_token => {
|
|
|
|
_check_is_some(&data.refresh_token, "refresh_token cannot be blank")
|
|
|
|
}
|
|
|
|
GrantType::password => {
|
|
|
|
_check_is_some(&data.client_id, "client_id cannot be blank")?;
|
|
|
|
_check_is_some(&data.password, "password cannot be blank")?;
|
|
|
|
_check_is_some(&data.scope, "scope cannot be blank")?;
|
|
|
|
_check_is_some(&data.username, "username cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_identifier, "device_identifier cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_name, "device_name cannot be blank")?;
|
|
|
|
_check_is_some(&data.device_type, "device_type cannot be blank")
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-17 20:25:28 +00:00
|
|
|
fn _check_is_some<T>(value: &Option<T>, msg: &str) -> EmptyResult {
|
|
|
|
if value.is_none() {
|
|
|
|
err!(msg)
|
2018-02-10 00:00:55 +00:00
|
|
|
}
|
2018-10-17 20:25:28 +00:00
|
|
|
Ok(())
|
2018-02-17 19:47:13 +00:00
|
|
|
}
|