From 3224b9fdd9174e51eb3e9842ce5abccf735abdfd Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Sat, 16 Apr 2022 18:06:37 +0300 Subject: final touches for 2022 spring --- src/db.rs | 39 +++++++++++++++++++++++--------- src/handlers.rs | 36 ++++++++++++++--------------- src/student.rs | 70 +++++++++------------------------------------------------ 3 files changed, 56 insertions(+), 89 deletions(-) diff --git a/src/db.rs b/src/db.rs index fd5c1be..f2921f8 100644 --- a/src/db.rs +++ b/src/db.rs @@ -14,13 +14,14 @@ use log::debug; use parking_lot::RwLock; use std::{collections::HashMap, fs, io, path::PathBuf, sync::Arc}; +const PREAPPROVED_STU_FILENAME: &str = "students.csv"; + #[derive(Debug, Clone, Default)] pub struct Db { pub blockchain: Arc>, pub pending_transactions: Arc>>, pub users: Arc>>, - approved_users: Vec, - // TODO: metu_ids or approved_users or something, metu_id struct <11-04-22, yigit> // + preapproved_users: Vec, } impl Db { @@ -37,13 +38,13 @@ impl Db { } let users: HashMap = get_friendly_users(); - let approved_users = read_approved_users(); + let preapproved_users = read_approved_users(); Db { blockchain: Arc::new(RwLock::new(Block::default())), pending_transactions: Arc::new(RwLock::new(HashMap::new())), users: Arc::new(RwLock::new(users)), - approved_users, + preapproved_users, } } @@ -69,6 +70,16 @@ impl Db { } } } + + pub fn is_user_preapproved(&self, id: &Id, passwd: &String) -> bool { + for user in &self.preapproved_users { + if *user.get_id() == *id && *user.get_passwd() == *passwd { + return true; + } + } + + false + } } fn last_block_content() -> Option { @@ -122,7 +133,7 @@ fn get_friendly_users() -> HashMap { users.insert( "cde48537ca2c28084ff560826d0e6388b7c57a51497a6cb56f397289e52ff41b".to_owned(), User { - user_id: MetuId::new("friend_1".to_owned(), "not_used".to_owned()).unwrap(), + user_id: MetuId::new("friend_1".to_owned(), "not_used".to_owned()), public_key: "not_used".to_owned(), balance: 70, is_bot: true, @@ -132,7 +143,7 @@ fn get_friendly_users() -> HashMap { users.insert( "a1a38b5bae5866d7d998a9834229ec2f9db7a4fc8fb6f58b1115a96a446875ff".to_owned(), User { - user_id: MetuId::new("friend_2".to_owned(), "not_used".to_owned()).unwrap(), + user_id: MetuId::new("friend_2".to_owned(), "not_used".to_owned()), public_key: "not_used".to_owned(), balance: 20, is_bot: true, @@ -142,7 +153,7 @@ fn get_friendly_users() -> HashMap { users.insert( "4e048fd2a62f1307866086e803e9be43f78a702d5df10831fbf434e7663ae0e7".to_owned(), User { - user_id: MetuId::new("friend_4".to_owned(), "not_used".to_owned()).unwrap(), + user_id: MetuId::new("friend_4".to_owned(), "not_used".to_owned()), public_key: "not_used".to_owned(), balance: 120, is_bot: true, @@ -152,7 +163,7 @@ fn get_friendly_users() -> HashMap { users.insert( "60e77101e76950a9b1830fa107fd2f8fc545255b3e0f14b6a7797cf9ee005f07".to_owned(), User { - user_id: MetuId::new("friend_4".to_owned(), "not_used".to_owned()).unwrap(), + user_id: MetuId::new("friend_4".to_owned(), "not_used".to_owned()), public_key: "not_used".to_owned(), balance: 40, is_bot: true, @@ -163,11 +174,19 @@ fn get_friendly_users() -> HashMap { fn read_approved_users() -> Vec { let mut approved_students: Vec = Vec::new(); - let contents = fs::read_to_string("students.csv").unwrap(); + let contents = fs::read_to_string(PREAPPROVED_STU_FILENAME).unwrap_or_else(|_| { + panic!( + "{}", + format!( + "Expected {} to load preapproved students", + PREAPPROVED_STU_FILENAME + ) + ) + }); let mut reader = csv::Reader::from_reader(contents.as_bytes()); for student in reader.records() { let student = student.unwrap(); - approved_students.push(MetuId::_new(student[0].to_owned(), student[1].to_owned())); + approved_students.push(MetuId::new(student[0].to_owned(), student[1].to_owned())); } approved_students } diff --git a/src/handlers.rs b/src/handlers.rs index 96001ce..ca0608c 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -220,7 +220,7 @@ pub async fn authenticate_user( }; // c field was properly base64 encoded, now available in auth_packet - // decryptor was setup properly, with the correct lenght key + // decryptor was setup properly, with the correct length key let mut buf = auth_packet; let auth_plaintext = match cipher.decrypt(&mut buf) { Ok(p) => p, @@ -278,24 +278,22 @@ pub async fn authenticate_user( }; // is the student in AuthRequest privileged? - // TODO: this is the only check for 'if metuid is approved' <15-04-22, yigit> // - let privileged_student_id = - if let Some(id) = MetuId::new(request.student_id.clone(), request.passwd.clone()) { - id - } else { - debug!( - "Someone tried to auth with invalid credentials: {} {}", - &request.student_id, &request.passwd - ); - let res_json = warp::reply::json(&GradeCoinResponse { - res: ResponseType::Error, - message: - "The credentials given ('student_id', 'passwd') cannot hold a Gradecoin account" - .to_owned(), - }); + let privileged_student_id = if db.is_user_preapproved(&request.student_id, &request.passwd) { + MetuId::new(request.student_id.clone(), request.passwd.clone()) + } else { + debug!( + "Someone tried to auth with invalid credentials: {} {}", + &request.student_id, &request.passwd + ); + let res_json = warp::reply::json(&GradeCoinResponse { + res: ResponseType::Error, + message: + "The credentials given ('student_id', 'passwd') cannot hold a Gradecoin account" + .to_owned(), + }); - return Ok(warp::reply::with_status(res_json, StatusCode::BAD_REQUEST)); - }; + return Ok(warp::reply::with_status(res_json, StatusCode::BAD_REQUEST)); + }; // Students should be able to authenticate once { @@ -382,7 +380,7 @@ pub async fn list_transactions(db: Db) -> Result { /// Proposes a new block for the next round. /// Can reject the block /// -/// The proposer has to put their transaction as the first transaction of the transaction_list. +/// The proposer has to put their transaction as the first transaction of the `Block::transaction_list`. /// This is the analogue of `coinbase` in Bitcoin works /// /// The `coinbase` transaction also gets something for their efforts. diff --git a/src/student.rs b/src/student.rs index 711eeeb..2b9c5bd 100644 --- a/src/student.rs +++ b/src/student.rs @@ -1,7 +1,6 @@ -use crate::Fingerprint; -use lazy_static::lazy_static; +use crate::{Fingerprint, Id}; use serde::{Deserialize, Serialize}; -use std::{collections::HashSet, fmt}; +use std::fmt; #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct UserAtRest { @@ -25,11 +24,9 @@ pub struct User { pub is_bot: bool, } -/// The values are hard coded in [`static@OUR_STUDENTS`] so `MetuId::new`() can accept/reject values based on that -/// TODO update the statement above #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)] pub struct MetuId { - id: String, + id: Id, passwd: String, } @@ -40,62 +37,15 @@ impl fmt::Display for MetuId { } impl MetuId { - pub fn new(id: String, pwd: String) -> Option { - if OUR_STUDENTS.contains(&(&*id, &*pwd)) { - Some(MetuId { id, passwd: pwd }) - } else { - None - } + pub fn new(id: String, passwd: String) -> Self { + MetuId { id, passwd } } - // TODO: replace the function above with this <15-04-22, yigit> // - pub fn _new(id: String, passwd: String) -> Self { - MetuId { id, passwd } + pub fn get_id(&self) -> &Id { + &self.id } -} -// TODO: remove this, read from a yaml or something, then MetuId::new gets a self <11-04-22, yigit> // -// Students who are authorized to have Gradecoin accounts -lazy_static! { - static ref OUR_STUDENTS: HashSet<(&'static str, &'static str)> = { - [ - ("e254275", "DtNX1qk4YF4saRH"), - ("e223687", "cvFEs4XLjuGBD1v"), - ("e211024", "voQAcxiKJmEXYRT"), - ("e209888", "O75dli6AQtz2tUi"), - ("e223725", "xXuTD3Y4tyrv2Jz"), - ("e209362", "N7wGm5XU5zVWOWu"), - ("e209898", "aKBFfB8fZMq8pVn"), - ("e230995", "TgcHGlqeFhQGx42"), - ("e223743", "YVWVSWuIHplJk9C"), - ("e223747", "8LAeHrsjnwXh59Q"), - ("e223749", "HMFeJqVOzwCPHbc"), - ("e223751", "NjMsxmtmy2VOwMW"), - ("e188126", "QibuPdV2gXfsVJW"), - ("e209913", "kMxJvl2vHSWCy4A"), - ("e203608", "mfkkR0MWurk6Rp1"), - ("e233013", "GCqHxdOaDj2pWXx"), - ("e216982", "2Z0xmgCStnj5qg5"), - ("e217185", "BcaZNlzlhPph7A3"), - ("e223780", "2KvVxKUQaA9H4sn"), - ("e194931", "hsC0Wb8PQ5vzwdQ"), - ("e223783", "ETUJA3kt1QYvJai"), - ("e254550", "rPRjX0A4NefvKWi"), - ("e217203", "lN3IWhGyCrGfkk5"), - ("e217477", "O9xlMaa7LanC82w"), - ("e223786", "UxI6czykJfp9T9N"), - ("e231060", "VJgziofQQPCoisH"), - ("e223795", "pmcTCKox99NFsqp"), - ("e223715", "1H5QuOYI1b2r9ET"), - ("e181932", "THANKYOUHAVEFUN"), - ("bank", "P7oxDm30g1jeIId"), - ("friend_1", "not_used"), - ("friend_2", "not_used"), - ("friend_3", "not_used"), - ("friend_4", "not_used"), - ] - .iter() - .copied() - .collect() - }; + pub fn get_passwd(&self) -> &String { + &self.passwd + } } -- cgit v1.2.3-70-g09d2