Skip to content

Commit

Permalink
fix-warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
mpiorowski committed Apr 23, 2023
1 parent 1bca9f6 commit f3c7dea
Show file tree
Hide file tree
Showing 7 changed files with 70 additions and 91 deletions.
7 changes: 7 additions & 0 deletions .github/workflows/lint-server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ env:
RUSTFLAGS: "-Dwarnings"

jobs:
utils:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Clippy
run: cargo clippy --all-targets --all-features
working-directory: service-utils
users:
runs-on: ubuntu-latest
steps:
Expand Down
2 changes: 1 addition & 1 deletion service-notes/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ fn check_auth(mut req: Request<()>) -> Result<Request<()>, Status> {
.parse()
.map_err(|_| Status::unauthenticated("Invalid user id"))?,
);
return Ok(req);
Ok(req)
}
_ => Err(Status::unauthenticated("No valid auth token")),
}
Expand Down
2 changes: 1 addition & 1 deletion service-users/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ fn check_auth(mut req: Request<()>) -> Result<Request<()>, Status> {
.parse()
.map_err(|_| Status::unauthenticated("Invalid user id"))?,
);
return Ok(req);
Ok(req)
}
_ => Err(Status::unauthenticated("No valid auth token")),
}
Expand Down
10 changes: 5 additions & 5 deletions service-users/src/users_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ impl UsersService for MyService {
let user_id = Uuid::parse_str(&user_id).map_err(|e| Status::internal(e.to_string()))?;

let row = query("select * from users where id = $1")
.bind(&user_id)
.bind(user_id)
.fetch_optional(&pool)
.await
.map_err(sqlx::Error::into_status)?;
Expand All @@ -212,21 +212,21 @@ impl UsersService for MyService {
.ok_or_else(|| Status::unauthenticated("Missing user_id metadata"))?
.to_str()
.map_err(|e| Status::internal(e.to_string()))?;
let user_uuid = Uuid::parse_str(&user_id).map_err(|e| Status::internal(e.to_string()))?;
let user_uuid = Uuid::parse_str(user_id).map_err(|e| Status::internal(e.to_string()))?;
let request = request.into_inner();

let avatar_id = request.avatar;
let avatar_uuid = match avatar_id {
Some(avatar_id) => Some(Uuid::try_parse(&avatar_id).map_err(|e| {
Status::invalid_argument(format!("Invalid avatar_id: {}", e.to_string()))
Status::invalid_argument(format!("Invalid avatar_id: {}", e))
})?),
None => None,
};

let row = query("update users set name = $1, avatar = $2 where id = $3 returning *")
.bind(&request.name)
.bind(&avatar_uuid)
.bind(&user_uuid)
.bind(avatar_uuid)
.bind(user_uuid)
.fetch_one(&mut tx)
.await
.map_err(sqlx::Error::into_status)?;
Expand Down
40 changes: 0 additions & 40 deletions service-users/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use anyhow::Result;
use jsonwebtoken::{Validation, DecodingKey, Header, encode, EncodingKey};
use serde::{Deserialize, Serialize};
use tonic::metadata::{MetadataMap, MetadataValue};

pub fn check_env(env_str: &str) -> Result<String> {
let env = std::env::var(env_str);
Expand All @@ -13,40 +10,3 @@ pub fn check_env(env_str: &str) -> Result<String> {
)),
}
}

pub fn create_auth_metadata(user_id: &String) -> Result<MetadataMap> {
let secret = check_env("SECRET")?;
let token = encode_token(user_id, secret.as_ref())?;
let metadata_value = MetadataValue::try_from("Bearer ".to_owned() + &token)?;
let mut metadata = MetadataMap::new();
metadata.insert("authorization", metadata_value);
Ok(metadata)
}


#[derive(Debug, Deserialize, Serialize)]
struct Claims {
user_id: String,
exp: usize,
}

pub fn decode_token(token: &str, secret: &[u8]) -> Result<String, jsonwebtoken::errors::Error> {
let validation = Validation::new(jsonwebtoken::Algorithm::HS256);
let decoding_key = DecodingKey::from_secret(secret);
let token_data = jsonwebtoken::decode::<Claims>(token, &decoding_key, &validation)?;
Ok(token_data.claims.user_id)
}

pub fn encode_token(user_id: &String, secret: &[u8]) -> Result<String> {
let current_time = time::OffsetDateTime::now_utc();
let claims = Claims {
user_id: user_id.to_string(),
exp: (current_time + time::Duration::hours(1)).unix_timestamp() as usize,
};
let token = encode(
&Header::new(jsonwebtoken::Algorithm::HS256),
&claims,
&EncodingKey::from_secret(secret),
)?;
Ok(token)
}
9 changes: 3 additions & 6 deletions service-utils/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod utils_service;
mod proto;
mod utils;
mod utils_service;

use anyhow::{Context, Result};
use sqlx::{postgres::PgPoolOptions, PgPool};
Expand Down Expand Up @@ -40,10 +40,7 @@ async fn main() -> Result<()> {

let server = MyService { pool };
let svc = UtilsServiceServer::with_interceptor(server, check_auth);
Server::builder()
.add_service(svc)
.serve(addr)
.await?;
Server::builder().add_service(svc).serve(addr).await?;

Ok(())
}
Expand All @@ -65,7 +62,7 @@ fn check_auth(mut req: Request<()>) -> Result<Request<()>, Status> {
.parse()
.map_err(|_| Status::unauthenticated("Invalid user id"))?,
);
return Ok(req);
Ok(req)
}
_ => Err(Status::unauthenticated("No valid auth token")),
}
Expand Down
91 changes: 53 additions & 38 deletions service-utils/src/utils_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,36 @@ use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status};

fn map_file(row: Option<PgRow>) -> Result<File> {
match row {
Some(row) => {
let id: Uuid = row.try_get("id")?;
let created: OffsetDateTime = row.try_get("created")?;
let updated: OffsetDateTime = row.try_get("updated")?;
let deleted: Option<OffsetDateTime> = row.try_get("deleted")?;
let target_id: Uuid = row.try_get("targetId")?;
let name: String = row.try_get("name")?;
let r#type: String = row.try_get("type")?;
let file_type =
FileType::from_str_name(&r#type).ok_or(anyhow::anyhow!("Invalid file type"))?;

let file = File {
id: id.to_string(),
created: created.to_string(),
updated: updated.to_string(),
deleted: deleted.map(|d| d.to_string()),
target_id: target_id.to_string(),
name: name.to_string(),
r#type: file_type.into(),
buffer: Vec::new(),
};
return Ok(file);
impl TryFrom<Option<PgRow>> for File {
type Error = anyhow::Error;

fn try_from(row: Option<PgRow>) -> Result<Self, Self::Error> {
match row {
Some(row) => {
let id: Uuid = row.try_get("id")?;
let created: OffsetDateTime = row.try_get("created")?;
let updated: OffsetDateTime = row.try_get("updated")?;
let deleted: Option<OffsetDateTime> = row.try_get("deleted")?;
let target_id: Uuid = row.try_get("targetId")?;
let name: String = row.try_get("name")?;
let r#type: String = row.try_get("type")?;
let file_type =
FileType::from_str_name(&r#type).ok_or(anyhow::anyhow!("Invalid file type"))?;

let file = File {
id: id.to_string(),
created: created.to_string(),
updated: updated.to_string(),
deleted: deleted.map(|d| d.to_string()),
target_id: target_id.to_string(),
name,
r#type: file_type.into(),
buffer: Vec::new(),
};
Ok(file)
}
None => Err(anyhow::anyhow!("File not found")),
}
None => Err(anyhow::anyhow!("File not found")),
}
}

Expand All @@ -62,8 +66,8 @@ impl UtilsService for MyService {

tokio::spawn(async move {
let mut files_stream = query("SELECT * FROM files WHERE \"targetId\" = $1 and type = $2 and deleted is null order by created desc")
.bind(&target_uuid)
.bind(&r#type)
.bind(target_uuid)
.bind(r#type)
.fetch(&pool);

loop {
Expand All @@ -74,7 +78,7 @@ impl UtilsService for MyService {
break;
}
Ok(file) => {
let mut file = match map_file(file) {
let mut file: File = match file.try_into() {
Ok(file) => file,
Err(e) => {
tx.send(Err(Status::internal(e.to_string()))).await.unwrap();
Expand Down Expand Up @@ -115,12 +119,17 @@ impl UtilsService for MyService {
Uuid::parse_str(&request.target_id).map_err(|e| Status::internal(e.to_string()))?;
let row =
query("SELECT * FROM files WHERE id = $1 and \"targetId\" = $2 and deleted is null")
.bind(&uuid)
.bind(&target_uuid)
.bind(uuid)
.bind(target_uuid)
.fetch_one(&pool)
.await
.map_err(|e| Status::internal(e.to_string()))?;
let mut file = map_file(Some(row)).map_err(|e| Status::internal(e.to_string()))?;

let mut file: File = match Some(row).try_into() {
Ok(file) => file,
Err(e) => return Err(Status::internal(e.to_string())),
};

let file_path = format!("/app/files/{}/{}", &file.id, &file.name);
let buffer = std::fs::read(file_path).unwrap();
file.buffer = buffer;
Expand Down Expand Up @@ -154,13 +163,16 @@ impl UtilsService for MyService {
// save file to db
let row =
query("INSERT INTO files (\"targetId\", name, type) VALUES ($1, $2, $3) RETURNING *")
.bind(&uuid)
.bind(&file.name)
.bind(&r#type)
.bind(uuid)
.bind(file.name)
.bind(r#type)
.fetch_one(&mut tx)
.await
.map_err(|e| Status::internal(e.to_string()))?;
let file = map_file(Some(row)).map_err(|e| Status::internal(e.to_string()))?;
let file: File = match Some(row).try_into() {
Ok(file) => file,
Err(e) => return Err(Status::internal(e.to_string())),
};

// save file to disk
let file_path = format!("/app/files/{}/{}", file.id, file.name);
Expand Down Expand Up @@ -196,16 +208,19 @@ impl UtilsService for MyService {
let row = query(
"UPDATE files SET deleted = now() WHERE id = $1 and \"targetId\" = $2 RETURNING *",
)
.bind(&file_id)
.bind(&target_id)
.bind(file_id)
.bind(target_id)
.fetch_one(&mut tx)
.await
.map_err(|e| Status::not_found(e.to_string()))?;

// delete file from disk
tokio::fs::remove_dir_all(format!("/app/files/{}", file_id)).await?;

let file = map_file(Some(row)).map_err(|e| Status::internal(e.to_string()))?;
let file: File = match Some(row).try_into() {
Ok(file) => file,
Err(e) => return Err(Status::internal(e.to_string())),
};

// commit transaction
tx.commit()
Expand Down

0 comments on commit f3c7dea

Please sign in to comment.