Merge pull request #8 from EETagent/create_candidate

Create candidate
This commit is contained in:
Sebastian Pravda 2022-10-24 22:21:46 +02:00 committed by GitHub
commit 93512c0d34
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 109 additions and 38 deletions

View file

@ -1,15 +1,12 @@
#[macro_use]
extern crate rocket;
use rocket::{Rocket, Build};
use rocket::serde::json::Json;
use rocket::fairing::{self, AdHoc};
use rocket::form::{ Form};
use rocket::fs::{relative, FileServer};
use rocket::response::{Flash, Redirect};
use rocket::{Build, Rocket};
use portfolio_core::{Mutation, Query};
use rocket::response::status::Custom;
use portfolio_core::{Mutation};
use migration::MigratorTrait;
use migration::{MigratorTrait};
use sea_orm_rocket::{Connection, Database};
mod pool;
@ -18,18 +15,21 @@ use pool::Db;
pub use entity::candidate;
pub use entity::candidate::Entity as Candidate;
use portfolio_core::crypto::random_8_char_string;
#[post("/", data = "<post_form>")]
async fn create(conn: Connection<'_, Db>, post_form: Json<candidate::Model>) -> Flash<Redirect> {
async fn create(conn: Connection<'_, Db>, post_form: Json<candidate::Model>) -> Result<String, Custom<String>> {
let db = conn.into_inner();
let form = post_form.into_inner();
Mutation::create_candidate(db, form)
.await
.expect("could not insert post");
let plain_text_password = random_8_char_string();
Flash::success(Redirect::to("/"), "Post successfully added.")
Mutation::create_candidate(db, form, &plain_text_password)
.await
.expect("Could not insert candidate");
Ok(plain_text_password)
}
#[get("/hello")]

View file

@ -5,6 +5,9 @@ edition = "2021"
[dependencies]
portfolio-entity = { path = "../entity" }
rand = "0.8.5"
argon2 = "0.4.1"
chrono = "0.4.22"
[dependencies.sea-orm]
version = "^0.10.0"

53
core/src/crypto.rs Normal file
View file

@ -0,0 +1,53 @@
use argon2::{
Argon2, PasswordHasher as ArgonPasswordHasher, PasswordVerifier as ArgonPasswordVerifier,
};
use rand::Rng;
/// Foolproof random 8 char string
/// only uppercase letters (except for 0 and O) and numbers
/// TODO tests
pub fn random_8_char_string() -> String {
let iterator = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.map(char::from);
let mut s = String::new();
for c in iterator { // add all characters except for: lowercase chars, 0 and O
if ('1'..='9').contains(&c) ||
('A'..='N').contains(&c) ||
('P'..'Z').contains(&c)
{
s.push(c);
if s.len() == 8 {
break;
}
}
}
s
}
pub fn hash_password(password_plaint_text: &str) -> Result<String, argon2::password_hash::Error> {
let password = password_plaint_text.as_bytes();
let salt = "c2VjcmV0bHl0ZXN0aW5nZXZlcnl0aGluZw";
let argon_config = Argon2::default();
let hash = argon_config.hash_password(password, salt)?;
return Ok(hash.to_string());
}
pub fn verify_password(
password_plaint_text: &str,
hash: &str,
) -> Result<bool, argon2::password_hash::Error> {
let argon_config = Argon2::default();
let parsed_hash = argon2::PasswordHash::new(&hash)?;
return Ok(argon_config
.verify_password(password_plaint_text.as_bytes(), &parsed_hash)
.is_ok());
}

View file

@ -1,5 +1,6 @@
mod mutation;
mod query;
pub mod crypto;
pub use mutation::*;
pub use query::*;

View file

@ -1,5 +1,6 @@
use ::entity::{candidate, candidate::Entity as Candidate};
use ::entity::{candidate};
use sea_orm::*;
use crate::crypto::hash_password;
pub struct Mutation;
@ -7,7 +8,20 @@ impl Mutation {
pub async fn create_candidate(
db: &DbConn,
form_data: candidate::Model,
) -> Result<candidate::ActiveModel, DbErr> {
todo!()
plain_text_password: &String,
) -> Result<candidate::Model, DbErr> {
// TODO: unwrap pro testing..
let hashed_password = hash_password(plain_text_password).unwrap();
candidate::ActiveModel {
application: Set(form_data.application),
code: Set(hashed_password),
public_key: Set("lorem ipsum pub key".to_string()),
private_key: Set("lorem ipsum priv key".to_string()),
created_at: Set(chrono::offset::Local::now().naive_local()),
updated_at: Set(chrono::offset::Local::now().naive_local()),
..Default::default()
}
.insert(db)
.await
}
}

View file

@ -1,10 +1,8 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.3
use sea_orm::entity::prelude::*;
use rocket::serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "admin")]
pub struct Model {
#[sea_orm(primary_key)]

View file

@ -1,7 +1,8 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.10.0
use chrono::{DateTime, NaiveDate, Local};
use rocket::serde::{Deserialize, Serialize};
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.3
use sea_orm::entity::prelude::*;
use rocket::serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
@ -9,26 +10,30 @@ use sea_orm::entity::prelude::*;
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
pub application: i32,
#[serde(skip_deserializing, skip_serializing)]
pub code: String,
pub name: Option<String>,
pub surname: Option<String>,
pub birth_surname: Option<String>,
pub birthplace: Option<String>,
pub birthdate: Option<NaiveDate>,
pub birthdate: Option<Date>,
pub address: Option<String>,
pub telephone: Option<String>,
#[sea_orm(default_value="Česká republika")]
pub citizenship: Option<String>,
pub email: Option<String>,
pub sex: Option<String>,
pub study: Option<String>,
pub personal_identification_number: Option<String>,
#[sea_orm(column_type = "Text")]
#[sea_orm(column_type = "Text", nullable)]
pub personal_identification_number_hash: Option<String>,
#[serde(skip_deserializing, skip_serializing)]
pub public_key: String,
#[serde(skip_deserializing, skip_serializing)]
pub private_key: String,
pub created_at: DateTime<Local>,
pub updated_at: DateTime<Local>,
#[serde(skip_deserializing, skip_serializing)]
pub created_at: DateTime,
#[serde(skip_deserializing, skip_serializing)]
pub updated_at: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]

View file

@ -1,6 +1,3 @@
#[macro_use]
extern crate rocket;
pub mod prelude;
pub mod admin;

View file

@ -1,10 +1,8 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.10.0
use sea_orm::entity::prelude::*;
use chrono::{DateTime, Local};
use rocket::serde::{Deserialize, Serialize};
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.3
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "parent")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false)]
@ -13,8 +11,8 @@ pub struct Model {
pub surname: Option<String>,
pub telephone: Option<String>,
pub email: Option<String>,
pub created_at: DateTime<Local>,
pub updated_at: DateTime<Local>,
pub created_at: DateTime,
pub updated_at: DateTime,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]

View file

@ -1,3 +1,5 @@
//! SeaORM Entity. Generated by sea-orm-codegen 0.9.3
pub use super::admin::Entity as Admin;
pub use super::candidate::Entity as Candidate;
pub use super::parent::Entity as Parent;