2018-02-10 01:00:55 +01:00
|
|
|
use std::collections::HashMap;
|
2018-08-26 00:07:59 +02:00
|
|
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
use rocket::request::{self, Form, FormItems, FromForm, FromRequest, Request};
|
|
|
|
use rocket::{Outcome, Route};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
use rocket_contrib::{Json, Value};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
use num_traits::FromPrimitive;
|
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
use db::models::*;
|
2018-07-12 21:46:50 +02:00
|
|
|
use db::DbConn;
|
2018-02-17 20:47:13 +01:00
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
use util::{self, JsonMap};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
use api::{ApiResult, JsonResult};
|
2018-02-17 20:47:13 +01:00
|
|
|
|
2018-07-13 15:58:50 +02:00
|
|
|
use CONFIG;
|
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
pub fn routes() -> Vec<Route> {
|
2018-07-12 21:46:50 +02:00
|
|
|
routes![login]
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[post("/connect/token", data = "<connect_data>")]
|
2018-08-26 00:07:59 +02:00
|
|
|
fn login(connect_data: Form<ConnectData>, device_type: DeviceType, conn: DbConn, socket: Option<SocketAddr>) -> JsonResult {
|
2018-02-10 01:00:55 +01:00
|
|
|
let data = connect_data.get();
|
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
match data.grant_type {
|
2018-07-12 21:46:50 +02:00
|
|
|
GrantType::RefreshToken => _refresh_login(data, device_type, conn),
|
2018-08-26 00:07:59 +02:00
|
|
|
GrantType::Password => _password_login(data, device_type, conn, socket),
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
|
|
|
}
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
fn _refresh_login(data: &ConnectData, _device_type: DeviceType, conn: DbConn) -> JsonResult {
|
|
|
|
// Extract token
|
2018-06-11 15:44:37 +02:00
|
|
|
let token = data.get("refresh_token");
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
// Get device by refresh token
|
|
|
|
let mut device = match Device::find_by_refresh_token(token, &conn) {
|
|
|
|
Some(device) => device,
|
2018-07-12 21:46:50 +02:00
|
|
|
None => err!("Invalid refresh token"),
|
2018-06-01 15:08:03 +02: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);
|
|
|
|
device.save(&conn);
|
|
|
|
|
|
|
|
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,
|
|
|
|
})))
|
|
|
|
}
|
|
|
|
|
2018-08-26 00:07:59 +02:00
|
|
|
fn _password_login(data: &ConnectData, device_type: DeviceType, conn: DbConn, remote: Option<SocketAddr>) -> JsonResult {
|
|
|
|
// 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 15:08:03 +02:00
|
|
|
// Validate scope
|
2018-06-11 15:44:37 +02:00
|
|
|
let scope = data.get("scope");
|
2018-06-01 15:08:03 +02:00
|
|
|
if scope != "api offline_access" {
|
|
|
|
err!("Scope not supported")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the user
|
2018-06-11 15:44:37 +02:00
|
|
|
let username = data.get("username");
|
2018-06-01 15:08:03 +02:00
|
|
|
let user = match User::find_by_mail(username, &conn) {
|
|
|
|
Some(user) => user,
|
2018-08-26 00:07:59 +02:00
|
|
|
None => err!(format!(
|
|
|
|
"Username or password is incorrect. Try again. IP: {}. Username: {}.",
|
|
|
|
ip, username
|
|
|
|
)),
|
2018-06-01 15:08:03 +02:00
|
|
|
};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
// Check password
|
2018-06-11 15:44:37 +02:00
|
|
|
let password = data.get("password");
|
2018-06-01 15:08:03 +02:00
|
|
|
if !user.check_valid_password(password) {
|
2018-08-26 00:07:59 +02:00
|
|
|
err!(format!(
|
|
|
|
"Username or password is incorrect. Try again. IP: {}. Username: {}.",
|
|
|
|
ip, username
|
|
|
|
))
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
2018-07-12 21:46:50 +02:00
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
// Let's only use the header and ignore the 'devicetype' parameter
|
|
|
|
let device_type_num = device_type.0;
|
|
|
|
|
2018-06-11 15:44:37 +02:00
|
|
|
let (device_id, device_name) = if data.is_device {
|
|
|
|
(
|
|
|
|
data.get("deviceidentifier").clone(),
|
|
|
|
data.get("devicename").clone(),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
(format!("web-{}", user.uuid), String::from("web"))
|
2018-06-01 15:08:03 +02: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 16:20:10 +02:00
|
|
|
match device.delete(&conn) {
|
|
|
|
Ok(()) => Device::new(device_id, user.uuid.clone(), device_name, device_type_num),
|
|
|
|
Err(_) => err!("Tried to delete device not owned by user, but failed")
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
device
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
2018-06-01 15:08:03 +02:00
|
|
|
}
|
|
|
|
None => {
|
|
|
|
// Create new device
|
|
|
|
Device::new(device_id, user.uuid.clone(), device_name, device_type_num)
|
|
|
|
}
|
|
|
|
};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
let twofactor_token = twofactor_auth(&user.uuid, &data, &mut device, &conn)?;
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
// Common
|
2018-02-10 01:00:55 +01:00
|
|
|
let user = User::find_by_uuid(&device.user_uuid, &conn).unwrap();
|
2018-04-24 22:01:55 +02:00
|
|
|
let orgs = UserOrganization::find_by_user(&user.uuid, &conn);
|
|
|
|
|
|
|
|
let (access_token, expires_in) = device.refresh_tokens(&user, orgs);
|
2018-02-10 01:00:55 +01:00
|
|
|
device.save(&conn);
|
|
|
|
|
2018-06-01 15:08:03 +02:00
|
|
|
let mut result = json!({
|
2018-02-10 01:00:55 +01:00
|
|
|
"access_token": access_token,
|
|
|
|
"expires_in": expires_in,
|
|
|
|
"token_type": "Bearer",
|
|
|
|
"refresh_token": device.refresh_token,
|
|
|
|
"Key": user.key,
|
2018-06-01 15:08:03 +02:00
|
|
|
"PrivateKey": user.private_key,
|
|
|
|
//"TwoFactorToken": "11122233333444555666777888999"
|
|
|
|
});
|
|
|
|
|
|
|
|
if let Some(token) = twofactor_token {
|
|
|
|
result["TwoFactorToken"] = Value::String(token);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(Json(result))
|
|
|
|
}
|
|
|
|
|
2018-07-12 21:46:50 +02: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 21:55:23 +02:00
|
|
|
if twofactors.is_empty() {
|
2018-07-12 21:46:50 +02:00
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
|
2018-09-13 20:59:51 +02:00
|
|
|
let provider = match util::try_parse_string(data.get_opt("twoFactorProvider")) {
|
2018-07-12 21:46:50 +02:00
|
|
|
Some(provider) => provider,
|
|
|
|
None => providers[0], // If we aren't given a two factor provider, asume the first one
|
|
|
|
};
|
|
|
|
|
|
|
|
let twofactor_code = match data.get_opt("twoFactorToken") {
|
|
|
|
Some(code) => code,
|
|
|
|
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) => {
|
|
|
|
match &device.twofactor_remember {
|
|
|
|
Some(remember) if remember == twofactor_code => return Ok(None), // No twofactor token needed here
|
|
|
|
_ => 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;
|
|
|
|
|
|
|
|
two_factor::validate_u2f_login(user_uuid, twofactor_code, conn)?;
|
|
|
|
}
|
|
|
|
|
|
|
|
_ => err!("Invalid two factor provider"),
|
|
|
|
}
|
|
|
|
|
2018-09-13 20:59:51 +02:00
|
|
|
if util::try_parse_string_or(data.get_opt("twoFactorRemember"), 0) == 1 {
|
2018-07-12 21:46:50 +02: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 15:08:03 +02:00
|
|
|
"error" : "invalid_grant",
|
|
|
|
"error_description" : "Two factor required.",
|
2018-07-12 21:46:50 +02: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 15:58:50 +02:00
|
|
|
Some(TwoFactorType::U2f) if CONFIG.domain_set => {
|
2018-07-12 21:46:50 +02: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 15:08:03 +02:00
|
|
|
}
|
|
|
|
|
2018-06-11 15:44:37 +02:00
|
|
|
#[derive(Clone, Copy)]
|
2018-02-17 20:47:13 +01:00
|
|
|
struct DeviceType(i32);
|
|
|
|
|
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for DeviceType {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
|
|
|
let headers = request.headers();
|
|
|
|
let type_opt = headers.get_one("Device-Type");
|
2018-09-13 20:59:51 +02:00
|
|
|
let type_num = util::try_parse_string_or(type_opt, 0);
|
2018-02-17 20:47:13 +01:00
|
|
|
|
|
|
|
Outcome::Success(DeviceType(type_num))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct ConnectData {
|
|
|
|
grant_type: GrantType,
|
2018-02-15 19:05:57 +01:00
|
|
|
is_device: bool,
|
2018-02-10 01:00:55 +01:00
|
|
|
data: HashMap<String, String>,
|
|
|
|
}
|
|
|
|
|
2018-02-15 19:05:57 +01:00
|
|
|
#[derive(Debug, Copy, Clone)]
|
2018-07-12 21:46:50 +02:00
|
|
|
enum GrantType {
|
|
|
|
RefreshToken,
|
|
|
|
Password,
|
|
|
|
}
|
2018-02-15 19:05:57 +01:00
|
|
|
|
2018-02-10 01:00:55 +01:00
|
|
|
impl ConnectData {
|
2018-06-11 15:44:37 +02:00
|
|
|
fn get(&self, key: &str) -> &String {
|
|
|
|
&self.data[&key.to_lowercase()]
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_opt(&self, key: &str) -> Option<&String> {
|
2018-02-10 01:00:55 +01:00
|
|
|
self.data.get(&key.to_lowercase())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const VALUES_REFRESH: [&str; 1] = ["refresh_token"];
|
2018-02-15 19:05:57 +01:00
|
|
|
const VALUES_PASSWORD: [&str; 5] = ["client_id", "grant_type", "password", "scope", "username"];
|
|
|
|
const VALUES_DEVICE: [&str; 3] = ["deviceidentifier", "devicename", "devicetype"];
|
2018-02-10 01:00:55 +01:00
|
|
|
|
|
|
|
impl<'f> FromForm<'f> for ConnectData {
|
|
|
|
type Error = String;
|
|
|
|
|
2018-02-15 00:53:11 +01:00
|
|
|
fn from_form(items: &mut FormItems<'f>, _strict: bool) -> Result<Self, Self::Error> {
|
2018-02-10 01:00:55 +01:00
|
|
|
let mut data = HashMap::new();
|
|
|
|
|
|
|
|
// Insert data into map
|
|
|
|
for (key, value) in items {
|
2018-02-15 19:05:57 +01:00
|
|
|
match (key.url_decode(), value.url_decode()) {
|
|
|
|
(Ok(key), Ok(value)) => data.insert(key.to_lowercase(), value),
|
2018-06-11 15:44:37 +02:00
|
|
|
_ => return Err("Error decoding key or value".to_string()),
|
2018-02-10 01:00:55 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate needed values
|
2018-07-12 21:46:50 +02:00
|
|
|
let (grant_type, is_device) = match data.get("grant_type").map(String::as_ref) {
|
|
|
|
Some("refresh_token") => {
|
|
|
|
check_values(&data, &VALUES_REFRESH)?;
|
|
|
|
(GrantType::RefreshToken, false) // Device doesn't matter here
|
|
|
|
}
|
|
|
|
Some("password") => {
|
|
|
|
check_values(&data, &VALUES_PASSWORD)?;
|
|
|
|
|
|
|
|
let is_device = match data["client_id"].as_ref() {
|
|
|
|
"browser" | "mobile" => check_values(&data, &VALUES_DEVICE)?,
|
|
|
|
_ => false,
|
|
|
|
};
|
|
|
|
(GrantType::Password, is_device)
|
|
|
|
}
|
|
|
|
_ => return Err("Grant type not supported".to_string()),
|
|
|
|
};
|
2018-02-10 01:00:55 +01:00
|
|
|
|
2018-07-12 21:46:50 +02:00
|
|
|
Ok(ConnectData {
|
|
|
|
grant_type,
|
|
|
|
is_device,
|
|
|
|
data,
|
|
|
|
})
|
2018-02-10 01:00:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-15 19:05:57 +01:00
|
|
|
fn check_values(map: &HashMap<String, String>, values: &[&str]) -> Result<bool, String> {
|
2018-02-10 01:00:55 +01:00
|
|
|
for value in values {
|
|
|
|
if !map.contains_key(*value) {
|
|
|
|
return Err(format!("{} cannot be blank", value));
|
|
|
|
}
|
|
|
|
}
|
2018-02-15 19:05:57 +01:00
|
|
|
Ok(true)
|
2018-02-17 20:47:13 +01:00
|
|
|
}
|