Upload and download attachments, and added License file

This commit is contained in:
Daniel García
2018-02-15 00:40:34 +01:00
parent 5cd40c63ed
commit b54684b677
20 changed files with 1147 additions and 199 deletions

150
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -17,7 +17,7 @@ rocket_contrib = "0.3.6"
reqwest = "0.8.4"
# multipart/form-data support
multipart = "0.13.6"
multipart = "0.14.1"
# A generic serialization/deserialization framework
serde = "1.0.27"
@ -26,15 +26,15 @@ serde_json = "1.0.9"
# A safe, extensible ORM and Query builder
# If tables need more than 16 columns, add feature "large-tables"
diesel = { version = "1.1.1", features = ["sqlite", "chrono"] }
diesel_migrations = {version = "1.1.0", features = ["sqlite"] }
diesel = { version = "1.1.1", features = ["sqlite", "chrono", "large-tables"] }
diesel_migrations = { version = "1.1.0", features = ["sqlite"] }
# A generic connection pool
r2d2 = "0.8.2"
r2d2-diesel = "1.0.0"
# Crypto library
ring = { version = "0.11.0", features = ["rsa_signing"]}
ring = { version = "0.11.0", features = ["rsa_signing"] }
# UUID generation
uuid = { version = "0.5.1", features = ["v4"] }

674
LICENSE.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -4,4 +4,6 @@ DROP TABLE devices;
DROP TABLE ciphers;
DROP TABLE attachments;
DROP TABLE folders;

View File

@ -1,30 +1,32 @@
CREATE TABLE users (
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
email TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
password_hash BLOB NOT NULL,
salt BLOB NOT NULL,
password_iterations INTEGER NOT NULL,
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
password_hash BLOB NOT NULL,
salt BLOB NOT NULL,
password_iterations INTEGER NOT NULL,
password_hint TEXT,
key TEXT NOT NULL,
key TEXT NOT NULL,
private_key TEXT,
public_key TEXT,
totp_secret TEXT,
totp_recover TEXT,
security_stamp TEXT NOT NULL
security_stamp TEXT NOT NULL,
equivalent_domains TEXT NOT NULL,
excluded_globals TEXT NOT NULL
);
CREATE TABLE devices (
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
user_uuid TEXT NOT NULL REFERENCES users (uuid),
name TEXT NOT NULL,
type INTEGER NOT NULL,
push_token TEXT UNIQUE,
refresh_token TEXT UNIQUE NOT NULL
uuid TEXT NOT NULL PRIMARY KEY,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
user_uuid TEXT NOT NULL REFERENCES users (uuid),
name TEXT NOT NULL,
type INTEGER NOT NULL,
push_token TEXT,
refresh_token TEXT NOT NULL
);
CREATE TABLE ciphers (
@ -36,8 +38,15 @@ CREATE TABLE ciphers (
organization_uuid TEXT,
type INTEGER NOT NULL,
data TEXT NOT NULL,
favorite BOOLEAN NOT NULL,
attachments BLOB
favorite BOOLEAN NOT NULL
);
CREATE TABLE attachments (
id TEXT NOT NULL PRIMARY KEY,
cipher_uuid TEXT NOT NULL REFERENCES ciphers (uuid),
file_name TEXT NOT NULL,
file_size INTEGER NOT NULL
);
CREATE TABLE folders (

View File

@ -31,7 +31,7 @@ struct KeysData {
#[post("/accounts/register", data = "<data>")]
fn register(data: Json<RegisterData>, conn: DbConn) -> Result<(), BadRequest<Json>> {
if CONFIG.signups_allowed {
if !CONFIG.signups_allowed {
err!(format!("Signups not allowed"))
}
println!("DEBUG - {:#?}", data);
@ -81,7 +81,7 @@ fn post_keys(data: Json<KeysData>, headers: Headers, conn: DbConn) -> Result<Jso
}
#[post("/accounts/password", data = "<data>")]
fn post_password(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn post_password(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let key = data["key"].as_str().unwrap();
let password_hash = data["masterPasswordHash"].as_str().unwrap();
let new_password_hash = data["newMasterPasswordHash"].as_str().unwrap();
@ -94,14 +94,13 @@ fn post_password(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Js
user.set_password(new_password_hash);
user.key = key.to_string();
user.save(&conn);
Ok(Json(json!({})))
Ok(())
}
#[post("/accounts/security-stamp", data = "<data>")]
fn post_sstamp(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn post_sstamp(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let password_hash = data["masterPasswordHash"].as_str().unwrap();
let mut user = headers.user;
@ -111,14 +110,15 @@ fn post_sstamp(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json
}
user.reset_security_stamp();
user.save(&conn);
Ok(Json(json!({})))
Ok(())
}
#[post("/accounts/email-token", data = "<data>")]
fn post_email(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
println!("{:#?}", data);
fn post_email(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let password_hash = data["masterPasswordHash"].as_str().unwrap();
let new_email = data["newEmail"].as_str().unwrap();
let mut user = headers.user;
@ -126,11 +126,18 @@ fn post_email(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json,
err!("Invalid password")
}
err!("Not implemented")
if User::find_by_mail(new_email, &conn).is_some() {
err!("Email already in use");
}
user.email = new_email.to_string();
user.save(&conn);
Ok(())
}
#[post("/accounts/delete", data = "<data>")]
fn delete_account(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn delete_account(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let password_hash = data["masterPasswordHash"].as_str().unwrap();
let mut user = headers.user;
@ -139,6 +146,10 @@ fn delete_account(data: Json<Value>, headers: Headers, conn: DbConn) -> Result<J
err!("Invalid password")
}
// Delete all ciphers by user_uuid
// Delete all devices by user_uuid
// Delete user
err!("Not implemented")
}

View File

@ -1,4 +1,5 @@
use std::io::{Cursor, Read};
use std::path::Path;
use rocket::{Route, Data};
use rocket::http::ContentType;
@ -6,14 +7,21 @@ use rocket::response::status::BadRequest;
use rocket_contrib::{Json, Value};
use multipart::server::Multipart;
use multipart::server::{Multipart, SaveResult};
use multipart::server::save::SavedData;
use data_encoding::HEXLOWER;
use db::DbConn;
use db::models::*;
use util;
use crypto;
use auth::Headers;
use CONFIG;
#[get("/sync")]
fn sync(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let user = headers.user;
@ -22,7 +30,7 @@ fn sync(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let folders_json: Vec<Value> = folders.iter().map(|c| c.to_json()).collect();
let ciphers = Cipher::find_by_user(&user.uuid, &conn);
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json()).collect();
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json(&conn)).collect();
Ok(Json(json!({
"Profile": user.to_json(),
@ -42,7 +50,7 @@ fn sync(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
fn get_ciphers(headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let ciphers = Cipher::find_by_user(&headers.user.uuid, &conn);
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json()).collect();
let ciphers_json: Vec<Value> = ciphers.iter().map(|c| c.to_json(&conn)).collect();
Ok(Json(json!({
"Data": ciphers_json,
@ -58,10 +66,10 @@ fn get_cipher(uuid: String, headers: Headers, conn: DbConn) -> Result<Json, BadR
};
if cipher.user_uuid != headers.user.uuid {
err!("Cipher is now owned by user")
err!("Cipher is not owned by user")
}
Ok(Json(cipher.to_json()))
Ok(Json(cipher.to_json(&conn)))
}
#[derive(Deserialize, Debug)]
@ -86,7 +94,15 @@ fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn) -> Resul
data.favorite.unwrap_or(false));
if let Some(ref folder_id) = data.folderId {
// TODO: Validate folder is owned by user
match Folder::find_by_uuid(folder_id, &conn) {
Some(folder) => {
if folder.user_uuid != headers.user.uuid {
err!("Folder is not owned by user")
}
}
None => err!("Folder doesn't exist")
}
cipher.folder_uuid = Some(folder_id.clone());
}
@ -107,7 +123,7 @@ fn post_ciphers(data: Json<CipherData>, headers: Headers, conn: DbConn) -> Resul
cipher.save(&conn);
Ok(Json(cipher.to_json()))
Ok(Json(cipher.to_json(&conn)))
}
fn value_from_data(data: &CipherData) -> Result<Value, &'static str> {
@ -180,48 +196,77 @@ fn post_ciphers_import(data: Json<Value>, headers: Headers, conn: DbConn) -> Res
#[post("/ciphers/<uuid>/attachment", format = "multipart/form-data", data = "<data>")]
fn post_attachment(uuid: String, data: Data, content_type: &ContentType, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
// TODO: Check if cipher exists
let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
Some(cipher) => cipher,
None => err!("Cipher doesn't exist")
};
let mut params = content_type.params();
let boundary_pair = params.next().expect("No boundary provided"); // ("boundary", "----WebKitFormBoundary...")
let boundary = boundary_pair.1;
use data_encoding::BASE64URL;
use crypto;
use CONFIG;
// TODO: Maybe use the same format as the official server?
let attachment_id = BASE64URL.encode(&crypto::get_random_64());
let path = format!("{}/{}/{}", CONFIG.attachments_folder,
headers.user.uuid, attachment_id);
println!("Path {:#?}", path);
let mut mp = Multipart::with_body(data.open(), boundary);
match mp.save().with_dir(path).into_entries() {
Some(entries) => {
println!("Entries {:#?}", entries);
let saved_file = &entries.files["data"][0]; // Only one file at a time
let file_name = &saved_file.filename; // This is provided by the client, don't trust it
let file_size = &saved_file.size;
}
None => err!("No data entries")
if cipher.user_uuid != headers.user.uuid {
err!("Cipher is not owned by user")
}
err!("Not implemented")
let mut params = content_type.params();
let boundary_pair = params.next().expect("No boundary provided");
let boundary = boundary_pair.1;
let base_path = Path::new(&CONFIG.attachments_folder).join(&cipher.uuid);
Multipart::with_body(data.open(), boundary).foreach_entry(|mut field| {
let name = field.headers.filename.unwrap(); // This is provided by the client, don't trust it
let file_name = HEXLOWER.encode(&crypto::get_random(vec![0; 10]));
let path = base_path.join(&file_name);
let size = match field.data.save()
.memory_threshold(0)
.size_limit(None)
.with_path(path) {
SaveResult::Full(SavedData::File(path, size)) => size as i32,
_ => return
};
let attachment = Attachment::new(file_name, cipher.uuid.clone(), name, size);
println!("Attachment: {:#?}", attachment);
attachment.save(&conn);
});
Ok(Json(cipher.to_json(&conn)))
}
#[post("/ciphers/<uuid>/attachment/<attachment_id>/delete", data = "<data>")]
fn delete_attachment_post(uuid: String, attachment_id: String, data: Json<Value>, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
// Data contains a json object with the id, but we don't need it
delete_attachment(uuid, attachment_id, headers, conn)
}
#[delete("/ciphers/<uuid>/attachment/<attachment_id>")]
fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
if uuid != headers.user.uuid {
err!("Permission denied")
fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn: DbConn) -> Result<(), BadRequest<Json>> {
let attachment = match Attachment::find_by_id(&attachment_id, &conn) {
Some(attachment) => attachment,
None => err!("Attachment doesn't exist")
};
if attachment.cipher_uuid != uuid {
err!("Attachment from other cipher")
}
let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
Some(cipher) => cipher,
None => err!("Cipher doesn't exist")
};
if cipher.user_uuid != headers.user.uuid {
err!("Cipher is not owned by user")
}
// Delete file
let file = attachment.get_file_path();
util::delete_file(&file);
// Delete entry in cipher
attachment.delete(&conn);
err!("Not implemented")
Ok(())
}
#[post("/ciphers/<uuid>")]

View File

@ -26,6 +26,7 @@ pub fn routes() -> Vec<Route> {
post_ciphers,
post_ciphers_import,
post_attachment,
delete_attachment_post,
delete_attachment,
post_cipher,
put_cipher,
@ -89,12 +90,27 @@ fn clear_device_token(uuid: String) -> Result<Json, BadRequest<Json>> { err!("No
fn put_device_token(uuid: String) -> Result<Json, BadRequest<Json>> { err!("Not implemented") }
#[derive(Deserialize, Debug)]
#[allow(non_snake_case)]
struct EquivDomainData {
ExcludedGlobalEquivalentDomains: Vec<i32>,
EquivalentDomains: Vec<Vec<String>>,
}
#[get("/settings/domains")]
fn get_eq_domains() -> Result<Json, BadRequest<Json>> {
err!("Not implemented")
}
#[post("/settings/domains")]
fn post_eq_domains() -> Result<Json, BadRequest<Json>> {
#[post("/settings/domains", data = "<data>")]
fn post_eq_domains(data: Json<EquivDomainData>, headers: Headers, conn: DbConn) -> Result<Json, BadRequest<Json>> {
let excluded_globals = &data.ExcludedGlobalEquivalentDomains;
let equivalent_domains = &data.EquivalentDomains;
let mut user = headers.user;
//BODY. "{\"ExcludedGlobalEquivalentDomains\":[2],\"EquivalentDomains\":[[\"uoc.edu\",\"uoc.es\"]]}"
err!("Not implemented")
}

View File

@ -20,10 +20,10 @@ fn get_twofactor(headers: Headers) -> Result<Json, BadRequest<Json>> {
Value::Null
} else {
json!([{
"Enabled": true,
"Type": 0,
"Object": "twoFactorProvider"
}])
"Enabled": true,
"Type": 0,
"Object": "twoFactorProvider"
}])
};
Ok(Json(json!({

View File

@ -16,21 +16,26 @@ pub fn routes() -> Vec<Route> {
// TODO: Might want to use in memory cache: https://github.com/hgzimmerman/rocket-file-cache
#[get("/")]
fn index() -> io::Result<NamedFile> {
NamedFile::open(Path::new(&CONFIG.web_vault_folder).join("index.html"))
NamedFile::open(
Path::new(&CONFIG.web_vault_folder)
.join("index.html"))
}
#[get("/<p..>")] // Only match this if the other routes don't match
#[get("/<p..>", rank = 1)] // Only match this if the other routes don't match
fn files(p: PathBuf) -> io::Result<NamedFile> {
NamedFile::open(Path::new(&CONFIG.web_vault_folder).join(p))
NamedFile::open(
Path::new(&CONFIG.web_vault_folder)
.join(p))
}
#[get("/attachments/<uuid>/<file..>")]
fn attachments(uuid: String, file: PathBuf, headers: Headers) -> io::Result<NamedFile> {
if uuid != headers.user.uuid {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "Permission denied"));
}
NamedFile::open(Path::new(&CONFIG.attachments_folder).join(file))
fn attachments(uuid: String, file: PathBuf) -> io::Result<NamedFile> {
NamedFile::open(
Path::new(&CONFIG.attachments_folder)
.join(uuid)
.join(file)
)
}

View File

@ -96,7 +96,7 @@ use db::DbConn;
use db::models::{User, Device};
pub struct Headers {
pub device_type: i32,
pub device_type: Option<i32>,
pub device: Device,
pub user: User,
}
@ -110,8 +110,8 @@ impl<'a, 'r> FromRequest<'a, 'r> for Headers {
/// Get device type
let device_type = match headers.get_one("Device-Type")
.map(|s| s.parse::<i32>()) {
Some(Ok(dt)) => dt,
_ => return err_handler!("Device-Type is invalid or missing")
Some(Ok(dt)) => Some(dt),// dt,
_ => None // return err_handler!("Device-Type is invalid or missing")
};
/// Get access_token

View File

@ -21,7 +21,6 @@ use reqwest::header::{self, Headers};
** These routes are here to avoid showing errors in the console,
** redirect the body data to the fairing and show the web vault.
**/
#[get("/")]
fn index() -> io::Result<NamedFile> {
NamedFile::open(Path::new("web-vault").join("index.html"))

View File

@ -0,0 +1,93 @@
use serde_json::Value as JsonValue;
use super::Cipher;
use CONFIG;
#[derive(Debug, Identifiable, Queryable, Insertable, Associations)]
#[table_name = "attachments"]
#[belongs_to(Cipher, foreign_key = "cipher_uuid")]
#[primary_key(id)]
pub struct Attachment {
pub id: String,
pub cipher_uuid: String,
pub file_name: String,
pub file_size: i32,
}
/// Local methods
impl Attachment {
pub fn new(id: String, cipher_uuid: String, file_name: String, file_size: i32) -> Self {
Self {
id,
cipher_uuid,
file_name,
file_size,
}
}
pub fn get_file_path(&self) -> String {
format!("{}/{}/{}", CONFIG.attachments_folder, self.cipher_uuid, self.id)
}
pub fn to_json(&self) -> JsonValue {
use util::get_display_size;
use CONFIG;
// TODO: Change all references to localhost (maybe put it in .env?)
let host = "http://localhost:8000";
let web_path = format!("{}/attachments/{}/{}", host, self.cipher_uuid, self.id);
let file_path = self.get_file_path();
let display_size = get_display_size(self.file_size);
json!({
"Id": self.id,
"Url": web_path,
"FileName": self.file_name,
"Size": self.file_size.to_string(),
"SizeName": display_size,
"Object": "attachment"
})
}
}
use diesel;
use diesel::prelude::*;
use db::DbConn;
use db::schema::attachments;
/// Database methods
impl Attachment {
pub fn save(&self, conn: &DbConn) -> bool {
// TODO: Update modified date
match diesel::replace_into(attachments::table)
.values(self)
.execute(&**conn) {
Ok(1) => true, // One row inserted
_ => false,
}
}
pub fn delete(self, conn: &DbConn) -> bool {
match diesel::delete(attachments::table.filter(
attachments::id.eq(self.id)))
.execute(&**conn) {
Ok(1) => true, // One row deleted
_ => false,
}
}
pub fn find_by_id(id: &str, conn: &DbConn) -> Option<Self> {
attachments::table
.filter(attachments::id.eq(id))
.first::<Self>(&**conn).ok()
}
pub fn find_by_cipher(cipher_uuid: &str, conn: &DbConn) -> Vec<Self> {
attachments::table
.filter(attachments::cipher_uuid.eq(cipher_uuid))
.load::<Self>(&**conn).expect("Error loading attachments")
}
}

View File

@ -4,8 +4,11 @@ use serde_json::Value as JsonValue;
use uuid::Uuid;
#[derive(Queryable, Insertable, Identifiable)]
use super::User;
#[derive(Debug, Identifiable, Queryable, Insertable, Associations)]
#[table_name = "ciphers"]
#[belongs_to(User, foreign_key = "user_uuid")]
#[primary_key(uuid)]
pub struct Cipher {
pub uuid: String,
@ -24,15 +27,14 @@ pub struct Cipher {
pub data: String,
pub favorite: bool,
pub attachments: Option<Vec<u8>>,
}
/// Local methods
impl Cipher {
pub fn new(user_uuid: String, type_: i32, favorite: bool) -> Cipher {
pub fn new(user_uuid: String, type_: i32, favorite: bool) -> Self {
let now = Utc::now().naive_utc();
Cipher {
Self {
uuid: Uuid::new_v4().to_string(),
created_at: now,
updated_at: now,
@ -45,30 +47,8 @@ impl Cipher {
favorite,
data: String::new(),
attachments: None,
}
}
pub fn to_json(&self) -> JsonValue {
use serde_json;
use util::format_date;
let data: JsonValue = serde_json::from_str(&self.data).unwrap();
json!({
"Id": self.uuid,
"Type": self.type_,
"RevisionDate": format_date(&self.updated_at),
"FolderId": self.folder_uuid,
"Favorite": self.favorite,
"OrganizationId": "",
"Attachments": self.attachments,
"OrganizationUseTotp": false,
"Data": data,
"Object": "cipher",
"Edit": true,
})
}
}
use diesel;
@ -78,6 +58,31 @@ use db::schema::ciphers;
/// Database methods
impl Cipher {
pub fn to_json(&self, conn: &DbConn) -> JsonValue {
use serde_json;
use util::format_date;
use super::Attachment;
let data_json: JsonValue = serde_json::from_str(&self.data).unwrap();
let attachments = Attachment::find_by_cipher(&self.uuid, conn);
let attachments_json: Vec<JsonValue> = attachments.iter().map(|c| c.to_json()).collect();
json!({
"Id": self.uuid,
"Type": self.type_,
"RevisionDate": format_date(&self.updated_at),
"FolderId": self.folder_uuid,
"Favorite": self.favorite,
"OrganizationId": "",
"Attachments": attachments_json,
"OrganizationUseTotp": false,
"Data": data_json,
"Object": "cipher",
"Edit": true,
})
}
pub fn save(&self, conn: &DbConn) -> bool {
// TODO: Update modified date
@ -98,15 +103,15 @@ impl Cipher {
}
}
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Cipher> {
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
ciphers::table
.filter(ciphers::uuid.eq(uuid))
.first::<Cipher>(&**conn).ok()
.first::<Self>(&**conn).ok()
}
pub fn find_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Cipher> {
pub fn find_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Self> {
ciphers::table
.filter(ciphers::user_uuid.eq(user_uuid))
.load::<Cipher>(&**conn).expect("Error loading ciphers")
.load::<Self>(&**conn).expect("Error loading ciphers")
}
}

View File

@ -4,8 +4,11 @@ use serde_json::Value as JsonValue;
use uuid::Uuid;
#[derive(Queryable, Insertable, Identifiable)]
use super::User;
#[derive(Debug, Identifiable, Queryable, Insertable, Associations)]
#[table_name = "devices"]
#[belongs_to(User, foreign_key = "user_uuid")]
#[primary_key(uuid)]
pub struct Device {
pub uuid: String,
@ -24,10 +27,10 @@ pub struct Device {
/// Local methods
impl Device {
pub fn new(uuid: String, user_uuid: String, name: String, type_: i32) -> Device {
pub fn new(uuid: String, user_uuid: String, name: String, type_: i32) -> Self {
let now = Utc::now().naive_utc();
Device {
Self {
uuid,
created_at: now,
updated_at: now,
@ -103,15 +106,15 @@ impl Device {
}
}
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Device> {
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
devices::table
.filter(devices::uuid.eq(uuid))
.first::<Device>(&**conn).ok()
.first::<Self>(&**conn).ok()
}
pub fn find_by_refresh_token(refresh_token: &str, conn: &DbConn) -> Option<Device> {
pub fn find_by_refresh_token(refresh_token: &str, conn: &DbConn) -> Option<Self> {
devices::table
.filter(devices::refresh_token.eq(refresh_token))
.first::<Device>(&**conn).ok()
.first::<Self>(&**conn).ok()
}
}

View File

@ -4,8 +4,11 @@ use serde_json::Value as JsonValue;
use uuid::Uuid;
#[derive(Queryable, Insertable, Identifiable)]
use super::User;
#[derive(Debug, Identifiable, Queryable, Insertable, Associations)]
#[table_name = "folders"]
#[belongs_to(User, foreign_key = "user_uuid")]
#[primary_key(uuid)]
pub struct Folder {
pub uuid: String,
@ -17,10 +20,10 @@ pub struct Folder {
/// Local methods
impl Folder {
pub fn new(user_uuid: String, name: String) -> Folder {
pub fn new(user_uuid: String, name: String) -> Self {
let now = Utc::now().naive_utc();
Folder {
Self {
uuid: Uuid::new_v4().to_string(),
created_at: now,
updated_at: now,
@ -69,15 +72,15 @@ impl Folder {
}
}
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Folder> {
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
folders::table
.filter(folders::uuid.eq(uuid))
.first::<Folder>(&**conn).ok()
.first::<Self>(&**conn).ok()
}
pub fn find_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Folder> {
pub fn find_by_user(user_uuid: &str, conn: &DbConn) -> Vec<Self> {
folders::table
.filter(folders::user_uuid.eq(user_uuid))
.load::<Folder>(&**conn).expect("Error loading folders")
.load::<Self>(&**conn).expect("Error loading folders")
}
}

View File

@ -1,8 +1,10 @@
mod attachment;
mod cipher;
mod device;
mod folder;
mod user;
pub use self::attachment::Attachment;
pub use self::cipher::Cipher;
pub use self::device::Device;
pub use self::folder::Folder;

View File

@ -6,7 +6,7 @@ use uuid::Uuid;
use CONFIG;
#[derive(Queryable, Insertable, Identifiable)]
#[derive(Debug, Identifiable, Queryable, Insertable)]
#[table_name = "users"]
#[primary_key(uuid)]
pub struct User {
@ -28,11 +28,14 @@ pub struct User {
pub totp_secret: Option<String>,
pub totp_recover: Option<String>,
pub security_stamp: String,
pub equivalent_domains: String,
pub excluded_globals: String,
}
/// Local methods
impl User {
pub fn new(mail: String, key: String, password: String) -> User {
pub fn new(mail: String, key: String, password: String) -> Self {
let now = Utc::now().naive_utc();
let email = mail.to_lowercase();
@ -42,7 +45,7 @@ impl User {
let salt = crypto::get_random_64();
let password_hash = crypto::hash_password(password.as_bytes(), &salt, iterations as u32);
User {
Self {
uuid: Uuid::new_v4().to_string(),
created_at: now,
updated_at: now,
@ -61,6 +64,9 @@ impl User {
public_key: None,
totp_secret: None,
totp_recover: None,
equivalent_domains: "[]".to_string(),
excluded_globals: "[]".to_string(),
}
}
@ -144,16 +150,16 @@ impl User {
}
}
pub fn find_by_mail(mail: &str, conn: &DbConn) -> Option<User> {
pub fn find_by_mail(mail: &str, conn: &DbConn) -> Option<Self> {
let lower_mail = mail.to_lowercase();
users::table
.filter(users::email.eq(lower_mail))
.first::<User>(&**conn).ok()
.first::<Self>(&**conn).ok()
}
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<User> {
pub fn find_by_uuid(uuid: &str, conn: &DbConn) -> Option<Self> {
users::table
.filter(users::uuid.eq(uuid))
.first::<User>(&**conn).ok()
.first::<Self>(&**conn).ok()
}
}

View File

@ -1,3 +1,12 @@
table! {
attachments (id) {
id -> Text,
cipher_uuid -> Text,
file_name -> Text,
file_size -> Integer,
}
}
table! {
ciphers (uuid) {
uuid -> Text,
@ -10,7 +19,6 @@ table! {
type_ -> Integer,
data -> Text,
favorite -> Bool,
attachments -> Nullable<Binary>,
}
}
@ -55,15 +63,19 @@ table! {
totp_secret -> Nullable<Text>,
totp_recover -> Nullable<Text>,
security_stamp -> Text,
equivalent_domains -> Text,
excluded_globals -> Text,
}
}
joinable!(attachments -> ciphers (cipher_uuid));
joinable!(ciphers -> folders (folder_uuid));
joinable!(ciphers -> users (user_uuid));
joinable!(devices -> users (user_uuid));
joinable!(folders -> users (user_uuid));
allow_tables_to_appear_in_same_query!(
attachments,
ciphers,
devices,
folders,

View File

@ -30,7 +30,7 @@ macro_rules! err_handler {
use std::path::Path;
use std::io::Read;
use std::fs::File;
use std::fs::{self, File};
pub fn file_exists(path: &str) -> bool {
Path::new(path).exists()
@ -48,6 +48,31 @@ pub fn read_file(path: &str) -> Result<Vec<u8>, String> {
Ok(contents)
}
pub fn delete_file(path: &str) -> bool {
fs::remove_file(path).is_ok()
}
const UNITS: [&'static str; 6] = ["bytes", "KB", "MB", "GB", "TB", "PB"];
pub fn get_display_size(size: i32) -> String {
let mut size = size as f64;
let mut unit_counter = 0;
loop {
if size > 1024. {
size /= 1024.;
unit_counter += 1;
} else {
break;
}
};
// Round to two decimals
size = (size * 100.).round() / 100.;
format!("{} {}", size, UNITS[unit_counter])
}
///
/// String util methods