Skip to content

Commit 8707461

Browse files
authored
Cors and getting a single ticket via its id (#31)
* feat: cors allow everything * feat: cors and method to get a single ticket via its id * chore: formatting
1 parent 7be2aca commit 8707461

File tree

5 files changed

+80
-19
lines changed

5 files changed

+80
-19
lines changed

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ argonautica = "0.2.0"
1717
hmac = "0.12.1"
1818
jwt = "0.16.0"
1919
sha2 = "0.10.7"
20+
actix-cors = "0.6.4"
2021

2122
[dev-dependencies]
22-
run_script = "0.10.1"
23+
run_script = "0.10.1"

src/database.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ pub fn get_all_tickets(connection: &mut SqliteConnection) -> QueryResult<Vec<Sql
7272
tickets.load::<SqliteTicket>(connection)
7373
}
7474

75+
pub fn get_single_ticket(
76+
ticket_id: i32,
77+
connection: &mut SqliteConnection,
78+
) -> QueryResult<SqliteTicket> {
79+
tickets.filter(id.eq(ticket_id)).get_result(connection)
80+
}
81+
7582
pub fn delete_ticket(
7683
connection: &mut SqliteConnection,
7784
ticked_id: i32,

src/main.rs

Lines changed: 70 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ mod test_helpers;
99

1010
use crate::database::{
1111
create_ticket, create_user, delete_ticket, edit_ticket, filter_tickets_in_database,
12-
get_all_tickets, get_user_by_email, remove_session_from_db, write_session_to_db, DataBase,
12+
get_all_tickets, get_single_ticket, get_user_by_email, remove_session_from_db,
13+
write_session_to_db, DataBase,
1314
};
1415
use crate::middleware::validator;
1516
use crate::models::{NewSession, NewUser, Ticket, TokenClaims};
@@ -18,8 +19,9 @@ use crate::status_messages::{
1819
CANNOT_LOGOUT, ERROR_COULD_NOT_CREATE_TICKET, ERROR_COULD_NOT_CREATE_USER,
1920
ERROR_COULD_NOT_DELETE, ERROR_COULD_NOT_GET, ERROR_COULD_NOT_UPDATE, ERROR_INCORRECT_PASSWORD,
2021
ERROR_INVALID_ID, ERROR_NOT_FOUND, ERROR_NOT_LOGGED_IN, ERROR_NO_USER_FOUND,
21-
ERROR_USER_ALREADY_EXISTS, SUCCESS_LOGIN, SUCCESS_LOGOUT,
22+
ERROR_USER_ALREADY_EXISTS, SUCCESS_LOGOUT,
2223
};
24+
use actix_cors::Cors;
2325
use actix_web::cookie::time::Duration;
2426
use actix_web::cookie::Cookie;
2527
use actix_web::web::{Json, Path};
@@ -39,15 +41,20 @@ async fn main() -> Result<()> {
3941
HttpServer::new(move || {
4042
let bearer_middleware = HttpAuthentication::bearer(validator);
4143

42-
App::new().service(signup).service(login).service(
43-
web::scope("")
44-
.wrap(bearer_middleware)
45-
.service(create)
46-
.service(get_tickets)
47-
.service(delete)
48-
.service(edit)
49-
.service(filter_tickets)
50-
.service(logout),
44+
let cors = Cors::permissive().allow_any_method().allow_any_origin();
45+
46+
App::new().wrap(cors).service(
47+
web::scope("/api").service(signup).service(login).service(
48+
web::scope("")
49+
.wrap(bearer_middleware)
50+
.service(create)
51+
.service(get_tickets)
52+
.service(get_ticket)
53+
.service(delete)
54+
.service(edit)
55+
.service(filter_tickets)
56+
.service(logout),
57+
),
5158
)
5259
})
5360
.bind(("localhost", 8080))?
@@ -84,6 +91,22 @@ async fn get_tickets() -> impl Responder {
8491
}
8592
}
8693

94+
#[get("/tickets/{id}")]
95+
async fn get_ticket(ticket_id: Path<i32>) -> impl Responder {
96+
let mut database = DataBase::new();
97+
let ticket_id = ticket_id.into_inner();
98+
99+
match get_single_ticket(ticket_id, &mut database.connection) {
100+
Ok(ticket) => HttpResponse::Ok().json(ticket.to_ticket()),
101+
Err(err) => match err {
102+
Error::NotFound => {
103+
HttpResponse::NotFound().json(format!("{} {}", ERROR_NOT_FOUND, ticket_id))
104+
}
105+
_ => HttpResponse::InternalServerError().json(ERROR_COULD_NOT_GET),
106+
},
107+
}
108+
}
109+
87110
#[post("/filter")]
88111
async fn filter_tickets(payload: Json<FilterPayload>) -> impl Responder {
89112
let mut database = DataBase::new();
@@ -211,10 +234,10 @@ async fn login(payload: Json<LoginPayload>) -> impl Responder {
211234
&mut database.connection,
212235
);
213236

214-
let bearer_cookie = Cookie::build("cira-bearer-token", token_str)
215-
.http_only(true)
237+
let bearer_cookie = Cookie::build("cira-bearer-token", &token_str)
238+
.http_only(false)
216239
.finish();
217-
HttpResponse::Ok().cookie(bearer_cookie).json(SUCCESS_LOGIN)
240+
HttpResponse::Ok().cookie(bearer_cookie).body(token_str)
218241
} else {
219242
HttpResponse::Unauthorized().json(ERROR_INCORRECT_PASSWORD)
220243
}
@@ -897,4 +920,37 @@ mod tests {
897920
assert_eq!(response.status().as_u16(), StatusCode::UNAUTHORIZED);
898921
}
899922
}
923+
924+
mod get_ticket {
925+
use super::*;
926+
use crate::get_ticket;
927+
use crate::models::Ticket;
928+
use actix_web::http::StatusCode;
929+
930+
#[actix_web::test]
931+
#[serial]
932+
async fn test_get_ticket() {
933+
setup_database();
934+
935+
let app = test::init_service(App::new().service(get_ticket)).await;
936+
let req = TestRequest::get().uri("/tickets/1").to_request();
937+
938+
let response: Ticket = test::call_and_read_body_json(&app, req).await;
939+
940+
assert_eq!(response.id, 1);
941+
}
942+
943+
#[actix_web::test]
944+
#[serial]
945+
async fn not_found() {
946+
setup_database();
947+
948+
let app = test::init_service(App::new().service(get_ticket)).await;
949+
let req = TestRequest::get().uri("/tickets/333").to_request();
950+
951+
let response = test::call_service(&app, req).await;
952+
953+
assert_eq!(response.status().as_u16(), StatusCode::NOT_FOUND);
954+
}
955+
}
900956
}

src/schema.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,4 @@ diesel::table! {
2929
}
3030
}
3131

32-
// gets reformatted every time running diesel migration
33-
#[rustfmt::skip]
3432
diesel::allow_tables_to_appear_in_same_query!(sessions, tickets, users,);

src/status_messages.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
pub const ERROR_NOT_FOUND: &str = "Could not find ticket with id";
33
pub const ERROR_INVALID_ID: &str = "ID must be an integer higher than 0";
44
pub const ERROR_COULD_NOT_CREATE_TICKET: &str = "Could not create ticket";
5-
pub const ERROR_COULD_NOT_GET: &str = "Could not get tickets";
5+
pub const ERROR_COULD_NOT_GET: &str = "Could not get ticket(s)";
66
pub const ERROR_COULD_NOT_UPDATE: &str = "Could not update ticket with id";
77
pub const ERROR_COULD_NOT_DELETE: &str = "Could not delete ticket with id";
88
pub const CANNOT_LOGOUT: &str = "Could not log you out";
@@ -13,5 +13,4 @@ pub const ERROR_NO_USER_FOUND: &str = "No user found";
1313
pub const ERROR_USER_ALREADY_EXISTS: &str = "User with that email already exists";
1414

1515
// success messages
16-
pub const SUCCESS_LOGIN: &str = "Successfully logged in";
1716
pub const SUCCESS_LOGOUT: &str = "Successfully logged out";

0 commit comments

Comments
 (0)