-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
backend/db_connector: add authorization tokens model and migration
- Loading branch information
Showing
14 changed files
with
468 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
use actix_web::{post, web, HttpResponse, Responder}; | ||
use base64::Engine; | ||
use db_connector::models::authorization_tokens::AuthorizationToken; | ||
use rand::RngCore; | ||
use serde::{Deserialize, Serialize}; | ||
use utoipa::ToSchema; | ||
use diesel::prelude::*; | ||
|
||
use crate::{error::Error, utils::{get_connection, web_block_unpacked}, AppState}; | ||
|
||
#[derive(Serialize, Deserialize, ToSchema)] | ||
pub struct CreateAuthorizationTokenResponseSchema { | ||
token: String, | ||
} | ||
|
||
#[derive(Serialize, Deserialize, ToSchema)] | ||
pub struct CreateAuthorizationTokenSchema { | ||
use_once: bool, | ||
} | ||
|
||
#[utoipa::path( | ||
context_path = "/user", | ||
request_body = CreateAuthorizationTokenSchema, | ||
responses( | ||
(status = 201, body = CreateAuthorizationTokenResponseSchema), | ||
), | ||
security( | ||
("jwt" = []) | ||
) | ||
)] | ||
#[post("/create_authorization_token")] | ||
pub async fn create_authorization_token( | ||
state: web::Data<AppState>, | ||
user_id: crate::models::uuid::Uuid, | ||
schema: web::Json<CreateAuthorizationTokenSchema>, | ||
) -> actix_web::Result<impl Responder> | ||
{ | ||
let id = uuid::Uuid::new_v4(); | ||
let mut token = vec![0u8; 32]; | ||
rand::thread_rng().fill_bytes(&mut token); | ||
let token = base64::engine::general_purpose::STANDARD.encode(token); | ||
let auth_token = AuthorizationToken { | ||
id, | ||
user_id: user_id.clone().into(), | ||
token: token.clone(), | ||
use_once: schema.use_once, | ||
}; | ||
|
||
let mut conn = get_connection(&state)?; | ||
web_block_unpacked(move || { | ||
use db_connector::schema::authorization_tokens::dsl as authorization_tokens; | ||
|
||
match diesel::insert_into(authorization_tokens::authorization_tokens) | ||
.values(&auth_token) | ||
.execute(&mut conn) { | ||
Ok(_) => Ok(()), | ||
Err(_err) => Err(Error::InternalError) | ||
} | ||
}).await?; | ||
|
||
let response = CreateAuthorizationTokenResponseSchema { | ||
token, | ||
}; | ||
Ok(HttpResponse::Created().json(response)) | ||
} | ||
|
||
#[cfg(test)] | ||
pub mod tests { | ||
use actix_web::{cookie::Cookie, test::{self, TestRequest}, App}; | ||
|
||
use crate::{middleware::jwt::JwtMiddleware, routes::user::tests::TestUser, tests::configure}; | ||
|
||
use super::{create_authorization_token, CreateAuthorizationTokenResponseSchema, CreateAuthorizationTokenSchema}; | ||
|
||
pub async fn create_test_auth_token(user: &TestUser, use_once: bool) -> String { | ||
let token = user.access_token.as_ref().unwrap(); | ||
|
||
let app = App::new().configure(configure) | ||
.wrap(JwtMiddleware) | ||
.service(create_authorization_token); | ||
let app = test::init_service(app).await; | ||
|
||
println!("{}", use_once); | ||
let req = TestRequest::post() | ||
.uri("/create_authorization_token") | ||
.cookie(Cookie::new("access_token", token)) | ||
.set_json(CreateAuthorizationTokenSchema { | ||
use_once | ||
}) | ||
.to_request(); | ||
|
||
let resp: CreateAuthorizationTokenResponseSchema = test::call_and_read_body_json(&app, req).await; | ||
resp.token | ||
} | ||
|
||
#[actix_web::test] | ||
async fn test_authorization_token_creation() { | ||
let (mut user, _) = TestUser::random().await; | ||
let token = user.login().await; | ||
|
||
let app = App::new().configure(configure) | ||
.wrap(JwtMiddleware) | ||
.service(create_authorization_token); | ||
let app = test::init_service(app).await; | ||
|
||
let req = TestRequest::post() | ||
.uri("/create_authorization_token") | ||
.cookie(Cookie::new("access_token", token)) | ||
.set_json(CreateAuthorizationTokenSchema { | ||
use_once: true | ||
}) | ||
.to_request(); | ||
|
||
let resp = test::call_service(&app, req).await; | ||
assert_eq!(resp.status(), 201); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
use actix_web::{get, web, HttpResponse, Responder}; | ||
use db_connector::models::authorization_tokens::AuthorizationToken; | ||
use diesel::prelude::*; | ||
use serde::{Deserialize, Serialize}; | ||
use utoipa::ToSchema; | ||
|
||
use crate::{error::Error, utils::{get_connection, web_block_unpacked}, AppState}; | ||
|
||
#[derive(Serialize, Deserialize, ToSchema)] | ||
pub struct StrippedToken { | ||
token: String, | ||
use_once: bool, | ||
} | ||
|
||
#[derive(Serialize, Deserialize, ToSchema)] | ||
pub struct GetAuthorizationTokensResponseSchema { | ||
tokens: Vec<StrippedToken>, | ||
} | ||
|
||
#[utoipa::path( | ||
context_path = "/user", | ||
responses( | ||
(status = 200, body = GetAuthorizationTokensResponseSchema), | ||
), | ||
security( | ||
("jwt" = []) | ||
) | ||
)] | ||
#[get("/get_authorization_tokens")] | ||
pub async fn get_authorization_tokens( | ||
state: web::Data<AppState>, | ||
user_id: crate::models::uuid::Uuid, | ||
) -> actix_web::Result<impl Responder> { | ||
|
||
let mut conn = get_connection(&state)?; | ||
let user_tokens: Vec<AuthorizationToken> = web_block_unpacked(move || { | ||
use db_connector::schema::authorization_tokens::dsl as authorization_tokens; | ||
|
||
let user_id: uuid::Uuid = user_id.into(); | ||
match authorization_tokens::authorization_tokens | ||
.filter(authorization_tokens::user_id.eq(&user_id)) | ||
.select(AuthorizationToken::as_select()) | ||
.load(&mut conn) | ||
{ | ||
Ok(u) => Ok(u), | ||
Err(_err) => Err(Error::InternalError) | ||
} | ||
}).await?; | ||
|
||
let tokens: Vec<StrippedToken> = user_tokens.into_iter().map(|t| { | ||
StrippedToken { | ||
token: t.token, | ||
use_once: t.use_once, | ||
} | ||
}).collect(); | ||
|
||
Ok(HttpResponse::Ok().json(GetAuthorizationTokensResponseSchema { | ||
tokens | ||
})) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use actix_web::{cookie::Cookie, test, App}; | ||
|
||
use crate::{middleware::jwt::JwtMiddleware, routes::user::tests::TestUser, tests::configure}; | ||
|
||
use super::{get_authorization_tokens, GetAuthorizationTokensResponseSchema}; | ||
|
||
|
||
#[actix_web::test] | ||
async fn test_get_authorization_tokens() { | ||
let (mut user, _) = TestUser::random().await; | ||
let access_token = user.login().await.to_string(); | ||
|
||
let mut auth_tokens = vec![String::new(); 5]; | ||
for token in auth_tokens.iter_mut() { | ||
*token = user.create_authorization_token(true).await; | ||
} | ||
|
||
let app = App::new().configure(configure) | ||
.wrap(JwtMiddleware) | ||
.service(get_authorization_tokens); | ||
let app = test::init_service(app).await; | ||
|
||
let req = test::TestRequest::get() | ||
.uri("/get_authorization_tokens") | ||
.cookie(Cookie::new("access_token", access_token)) | ||
.to_request(); | ||
|
||
let resp = test::call_service(&app, req).await; | ||
assert_eq!(resp.status(), 200); | ||
let resp: GetAuthorizationTokensResponseSchema = test::read_body_json(resp).await; | ||
let resp_tokens: Vec<String> = resp.tokens.into_iter().map(|token| token.token).collect(); | ||
assert_eq!(auth_tokens, resp_tokens); | ||
} | ||
} |
Oops, something went wrong.