Browse Source

update: Add pseudo check for authentication with api key.

Alexandre Leblanc 5 years atrás
parent
commit
048ef6f361
2 changed files with 31 additions and 7 deletions
  1. 0 0
      doc/api_insomnia.json
  2. 31 7
      src/main.rs

api_insomnia.json → doc/api_insomnia.json


+ 31 - 7
src/main.rs

@@ -5,6 +5,12 @@ mod broadsign;
 use actix_web::{middleware, web, App, HttpResponse, HttpServer};
 use broadsign::real_time_pop_request::RealTimePopRequest;
 
+// We keep authentication at its simplest form, but you could
+// return the api user informations through a Result<UserIdentity> mechanism.
+pub fn authenticate(api_key: &String) -> bool {
+    api_key == "some_secure_api_key"
+}
+
 pub async fn status_get() -> HttpResponse {
     HttpResponse::Ok().finish()
 }
@@ -12,7 +18,12 @@ pub async fn status_get() -> HttpResponse {
 pub async fn pop_post(pop_data: web::Json<RealTimePopRequest>) -> HttpResponse {
     let pop_data: RealTimePopRequest = pop_data.into_inner();
 
-    debug!("{:?}", pop_data);
+    debug!("Received pop submission:\n{:?}", pop_data);
+
+    if !authenticate(&pop_data.api_key) {
+        error!("Pop submission refused for api key '{}'", &pop_data.api_key);
+        return HttpResponse::Unauthorized().finish();
+    }
 
     HttpResponse::Ok().finish()
 }
@@ -41,7 +52,7 @@ async fn main() -> std::io::Result<()> {
 #[cfg(test)]
 mod tests_endpoint_status {
     use super::*;
-    use actix_web::{http, web};
+    use actix_web::http;
 
     #[actix_rt::test]
     async fn given_everything_is_running_status_returns_200_ok() {
@@ -58,9 +69,8 @@ mod tests_endpoint_pop {
     use broadsign::real_time_pop_request::{RealTimePopEntry, RealTimePopRequest};
     use serde_json::json;
 
-    #[actix_rt::test]
-    async fn given_a_valid_pop_and_healthy_server_respond_ok() {
-        let resp = pop_post(web::Json(RealTimePopRequest {
+    fn make_valid_pop_request() -> RealTimePopRequest {
+        RealTimePopRequest {
             api_key: "some_secure_api_key".to_owned(),
             player_id: 123456,
             pops: vec![RealTimePopEntry {
@@ -78,9 +88,23 @@ mod tests_endpoint_pop {
                 service_value: "701".to_owned(),
                 extra_data: json!(""),
             }],
-        }))
-        .await;
+        }
+    }
+
+    #[actix_rt::test]
+    async fn given_a_valid_pop_and_healthy_server_respond_ok() {
+        let resp = pop_post(web::Json(make_valid_pop_request())).await;
 
         assert_eq!(resp.status(), http::StatusCode::OK);
     }
+
+    #[actix_rt::test]
+    async fn given_an_invalid_api_key_server_responds_401_unauthorized() {
+        let mut request = make_valid_pop_request();
+        request.api_key = "some_invalid_api_key".to_owned();
+
+        let resp = pop_post(web::Json(request)).await;
+
+        assert_eq!(resp.status(), http::StatusCode::UNAUTHORIZED);
+    }
 }