feat: signup api (OS-3)

This commit is contained in:
Artemy 2022-07-26 20:27:05 +03:00
parent 70fba74aa8
commit c1124f0941
3 changed files with 68 additions and 0 deletions

View file

@ -37,6 +37,57 @@ impl Core {
self.get_collection(&self.apps).await
}
pub async fn signup(&self, user: &Json<User>) -> serde_json::Value {
let jwt_info = JwtInfo {
name: user.name.clone(),
role: "user".to_string(),
exp: Utc::now().timestamp() + 604800, //week
};
let token = encode(
&Header::default(),
&jwt_info,
&EncodingKey::from_secret(self.jwt_secret.as_ref()),
);
match token {
Ok(token) => {
let auth_info = doc! {
"name": &user.name,
"password": self.hash(user.name.clone() + &user.password),
"email": &user.email,
"role": "user".to_string(),
};
let response = self.users.insert_one(&auth_info, None).await;
match response {
Ok(_) => {
json! ({
"code":"ok",
"token":token
})
}
Err(_) => {
json! ({
"code":"err",
"msg":"User with this name already exist"
})
}
}
}
Err(_) => {
json! ({
"code":"err",
"msg":"Some problem with jwt generation"
})
}
}
}
fn hash(&self, to_hash: String) -> String {
let mut hasher = Sha3_256::new();
hasher.update(to_hash + &self.salt);
let hash = hasher.finalize();
format!("{:x}", hash)
}
async fn get_collection(&self, collection: &Collection<Document>) -> Vec<Document> {
let options = FindOptions::builder().projection(doc! {"_id" : 0}).build();
let cursor = match collection.find(None, options).await {

View file

@ -44,6 +44,7 @@ async fn main() -> std::io::Result<()> {
}))
.wrap(cors)
.service(routes::apps)
.service(routes::signup)
})
.bind(("0.0.0.0", port))
.expect("Can not bind to port")

View file

@ -1,7 +1,23 @@
use crate::types::*;
use actix_web::{get, post, web, HttpRequest, HttpResponse, Responder};
use actix_web_grants::proc_macro::{has_any_permission, has_permissions};
#[post("/signup")]
pub async fn signup(app_data: web::Data<crate::AppState>, user: web::Json<User>) -> impl Responder {
response(app_data.core.signup(&user).await)
}
#[get("/apps")]
pub async fn apps(app_data: web::Data<crate::AppState>) -> impl Responder {
HttpResponse::Ok().json(app_data.core.get_apps().await)
}
fn response(result: serde_json::Value) -> impl Responder {
if result["code"] == "ok" {
HttpResponse::Ok().json(result)
} else if result["code"] == "ok_body" {
HttpResponse::Ok().json(&result["body"])
} else if result["code"] == "denied" {
HttpResponse::Forbidden().json(result)
} else {
println!("{}", result["code"]);
HttpResponse::InternalServerError().json(result)
}
}