Make working api auth

This commit is contained in:
BitHeaven 2024-03-25 22:33:03 +05:00
parent c877b02286
commit e3229f41a4
2 changed files with 89 additions and 27 deletions

View File

@ -9,7 +9,10 @@ use {
Value as Json,
json,
},
skytable::pool::ConnectionMgrTcp,
skytable::{
pool::ConnectionMgrTcp,
query,
},
bb8::Pool,
std::sync::Arc,
crate::{
@ -45,9 +48,32 @@ async fn auth(req: Request<Incoming>, _pool: DBPool) -> Json {
}
}
async fn auth_get(req: Request<Incoming>, _pool: DBPool) -> Json {
async fn auth_get(req: Request<Incoming>, pool: DBPool) -> Json {
let mut con = pool.get().await.unwrap();
let query = req.uri().query().or(Some("")).unwrap();
let query = double_split(query.to_string(), "&", "=");
println!("{:?}", query);
json!({"error": false, "msg": "test auth_get endpoint v0"})
let session = match query.get("session").is_none() {
false => query.get("session").unwrap(),
_ => ""
};
let res = con.query_parse::<(String, String)>(&query!(
"SELECT login, uuid FROM bitauth.v0 WHERE session = ?",
session
)).await;
let _ = con.query_parse::<()>(&query!(
"DELETE FROM bitauth.v0 WHERE session = ?",
session
)).await;
let (login, uuid) = match res.is_ok() {
false => ("".to_owned(), "".to_owned()),
_ => res.unwrap()
};
match login {
"" => json!({"error": true, "msg": "Not auth yet"}),
_ => json!({"error": false, "login": login, "uuid": uuid})
}
}

View File

@ -58,6 +58,7 @@ use {
},
serde_json::{
Value as Json,
Map as JsonMap,
json,
},
skytable::{
@ -164,10 +165,9 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
let mut headers = parts.headers.clone();
let cookies = get_cookies(req.headers().clone());
let token = cookies.get("token");
let token = match token.is_none() {
false => token.unwrap(),
_ => ""
let mut token = match cookies.get("token") {
x if x.is_none() => "".to_owned(),
x => x.unwrap().to_owned()
};
let mut logged = false;
@ -183,7 +183,7 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
return Ok(Response::from_parts(parts, Full::new(Bytes::new())));
}*/
let is_live = jwt_verify(pool.clone(), token)
let is_live = jwt_verify(pool.clone(), &token)
.await?
.claims
.as_object()
@ -214,9 +214,10 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
let mut con = pool.get().await.unwrap();
let tokenid = ref_data.get("uuid").unwrap().as_str().unwrap();
let newtok = format!("{}", uuid_v4().as_hyphenated());
let newref = format!("{}", uuid_v4().as_hyphenated());
let time = time();
// TODO: FIX ERROR IF TOKEN INVALID
let (uuid,) = con.query_parse::<(String,)>(&query!(
r#"
SELECT uid
@ -225,6 +226,7 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
"#,
tokenid
)).await?;
let (login,) = con.query_parse::<(String,)>(&query!(
r#"
SELECT login
@ -236,23 +238,23 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
let _ = con.query_parse::<()>(&query!(
r#"
UPDATE bitauth.tokens
SET uuid = ?, ref = ?, refend = ?
SET ref = ?, refend = ?
WHERE uuid = ?
"#,
newtok.clone(), newref.clone(), time + REFRESH_LIFETIME, tokenid
newref.clone(), time + REFRESH_LIFETIME, tokenid
)).await;
set_cookie(&mut headers, "token",
&jwt_sign(pool.clone(), json!({
"login": login.clone(),
"uuid": uuid.clone(),
"iat": time,
"exp": time + TOKEN_LIFETIME
})).await.unwrap()
);
token = jwt_sign(pool.clone(), json!({
"login": login.clone(),
"uuid": uuid.clone(),
"iat": time,
"exp": time + TOKEN_LIFETIME
})).await.unwrap();
set_cookie(&mut headers, "token", &token);
set_cookie(&mut headers, "refresh",
&jwt_sign(pool.clone(), json!({
"uuid": newtok.clone(),
"uuid": tokenid,
"iat": time,
"ref": newref.clone(),
"exp": time + REFRESH_LIFETIME
@ -273,8 +275,8 @@ async fn handle_connection(req: Request<Incoming>, pool: DBPool, ip: String) ->
"/" => uri_index(),
"/cabinet" => uri_login(req, pool.clone(), &mut headers).await?,
"/login" => uri_login(req, pool.clone(), &mut headers).await?,
x if x == "/authorize" && logged => uri_authorize(req, pool.clone()).await?,
"/authorize" => uri_authorize(req, pool.clone()).await?,
x if x == "/authorize" && logged => uri_authorize(req, pool.clone(), token).await?,
// "/authorize" => uri_authorize(req, pool.clone()).await?,
"/register" => uri_register(req, pool.clone(), &mut headers).await?,
"/recover" => uri_recover(),
x if x.starts_with("/@") => uri_user(req, pool.clone()).await?,
@ -334,17 +336,51 @@ async fn uri_login(req: Request<Incoming>, pool: DBPool, headers: &mut HeaderMap
Ok((build_html(LOGIN_HTML), StatusCode::OK, restype))
}
async fn uri_authorize(req: Request<Incoming>, _pool: DBPool) -> Result<(String, StatusCode, HeaderValue)> {
async fn uri_authorize(req: Request<Incoming>, pool: DBPool, token: String) -> Result<(String, StatusCode, HeaderValue)> {
if *req.method() == Method::POST {
let body = get_body_from_request(req).await?;
let body = String::from_utf8(body).unwrap();
let _body = double_split(body, "&", "=");
let r = double_split(req.uri().query().or(Some("")).unwrap().to_owned(), "&", "=");
let session = r.get("session");
let session = match session.is_none() {
false => session.unwrap().to_owned(),
_ => "".to_owned()
};
if session != "" {
authorize_user(pool.clone(), token, session).await;
}
}
let restype: HeaderValue = "text/html".parse().unwrap();
Ok((build_html(AUTHORIZE_HTML), StatusCode::OK, restype))
}
async fn authorize_user(pool: DBPool, token: String, session: String) {
let mut con = pool.get().await.unwrap();
let data: JsonMap<String, Json> = jwt_verify(pool.clone(), &token)
.await
.unwrap()
.claims
.as_object()
.unwrap()
.clone();
let login = data.get("login").unwrap().as_str();
let uuid = data.get("uuid").unwrap().as_str();
let _ = con.query_parse::<()>(&query!(
r#"INSERT INTO bitauth.v0 {
session: ?,
login: ?,
uuid: ?
}"#,
session,
login,
uuid
)).await;
}
fn uri_index() -> (String, StatusCode, HeaderValue) {
let restype: HeaderValue = "text/html".parse().unwrap();
(build_html(INDEX_HTML), StatusCode::OK, restype)