Files
vote-rs/src/api.rs

119 lines
2.7 KiB
Rust

#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive;
use rocket::http::Status;
use rocket_contrib::json::{Json, JsonValue};
use crate::auth::login;
// Define data models
#[derive(Serialize, Deserialize)]
struct User {
id: String,
username: String,
password: String,
}
#[derive(Serialize, Deserialize)]
struct Authorization {
to_date: String,
from_date: String,
user: String,
}
#[derive(Serialize, Deserialize)]
struct Election {
id: String,
username: String,
name: String,
description: String,
start_date: String,
end_date: String,
items: Vec<ElectionItem>,
}
#[derive(Serialize, Deserialize)]
struct ElectionItem {
id: String,
name: String,
}
#[derive(Serialize, Deserialize)]
struct VoteItem {
item: ElectionItem,
value: f64,
}
#[derive(Serialize, Deserialize)]
struct Vote {
authorization: Authorization,
userid: String,
data: Vec<VoteItem>,
}
#[post("/auth/login", format = "application/json", data = "<credentials>")]
async fn handle_login(credentials: Json<User>, db: Db) -> JsonValue {
match login(credentials.email, credentials.password, db).await {
Ok(token) => json!({
"token": token
}),
Err(error) => json!({
"error": error
}),
}
}
#[post("/auth/token", format = "application/json", data = "<token>")]
fn generate_token(token: Json<Authorization>) -> JsonValue {
// Token generation logic here
json!({
"token": "generated_token"
})
}
#[post("/elections/create", format = "application/json", data = "<election>")]
fn create_election(election: Json<Election>) -> Result<JsonValue, Status> {
// Election creation logic here
Ok(json!(election))
}
#[get("/elections/all")]
fn get_all_elections() -> JsonValue {
// Retrieve all elections logic here
json!([
// List of all existing elections
])
}
#[get("/elections/<id>")]
fn get_election(id: String) -> JsonValue {
// Retrieve single election logic here
json!({
"id": id,
// Other election details
})
}
#[post("/elections/<id>", format = "application/json", data = "<vote>")]
fn vote_in_election(id: String, vote: Json<Vote>) -> Result<JsonValue, Status> {
// Voting logic here
Ok(json!(vote))
}
// Rocket fairings to set up CORS and other middlewares can be added here
fn main() {
rocket::ignite()
.mount("/api", routes![
login,
generate_token,
create_election,
get_all_elections,
get_election,
vote_in_election,
])
.launch();
}