DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

a4137f9834a85dc03723d8842524505bb499ae90 — Jonni Liljamo 1 year, 7 months ago 7b66025
feat(client, server, shared): new login/register
6 files changed, 111 insertions(+), 67 deletions(-)

M client/src/plugins/networking/systems/events.rs
M server/src/main.rs
M server/src/systems/event/mod.rs
M shared/src/api/mod.rs
R shared/src/api/{user/types.rs => types.rs}
M shared/src/api/user/mod.rs
M client/src/plugins/networking/systems/events.rs => client/src/plugins/networking/systems/events.rs +14 -2
@@ 7,18 7,30 @@
 */

use bevy::prelude::*;
use iyes_loopless::state::NextState;
use naia_bevy_client::{
    events::{ConnectEvent, DisconnectEvent, RejectEvent},
    Client,
};

use crate::plugins::menu::ui::connect::{ConnectScreenData, ConnectState};
use crate::plugins::menu::{
    ui::connect::{ConnectScreenData, ConnectState},
    MenuState,
};

pub fn connect_events(mut ev: EventReader<ConnectEvent>, client: Client) {
pub fn connect_events(
    mut commands: Commands,
    mut ev: EventReader<ConnectEvent>,
    client: Client,
    mut data: ResMut<ConnectScreenData>,
) {
    for _ in ev.iter() {
        info!("?");
        if let Ok(server_address) = client.server_address() {
            info!("Laurelin client connected to: '{}'", server_address);

            data.state = ConnectState::Login;
            commands.insert_resource(NextState(MenuState::Menu));
        }
    }
}

M server/src/main.rs => server/src/main.rs +10 -0
@@ 8,6 8,7 @@

use bevy_app::{App, ScheduleRunnerPlugin};
use bevy_core::CorePlugin;
use bevy_ecs::system::Resource;
use bevy_log::{info, LogPlugin};

use naia_bevy_server::{Plugin as ServerPlugin, ServerConfig};


@@ 16,9 17,16 @@ use laurelin_shared::server::protocol::protocol;

mod systems;

#[derive(Resource)]
pub struct Config {
    pub api_address: String,
}

fn main() {
    let mut server = App::new();

    let api_address = std::env::var("LAURELIN_API_URL").expect("LAURELIN_API_URL");

    server
        // plugins
        .add_plugin(CorePlugin::default())


@@ 29,6 37,8 @@ fn main() {
            ..Default::default()
        })
        .add_plugin(ServerPlugin::new(ServerConfig::default(), protocol()))
        // config
        .insert_resource(Config { api_address })
        // init system
        .add_startup_system(systems::init::init)
        // events

M server/src/systems/event/mod.rs => server/src/systems/event/mod.rs +23 -6
@@ 6,22 6,39 @@
 * See LICENSE for licensing information.
 */

use bevy_ecs::event::EventReader;
use laurelin_shared::server::messages::Auth;
use bevy_ecs::{event::EventReader, system::Res};
use laurelin_shared::{
    api::user::{login, register, ResponseLogin, ResponseRegister},
    server::messages::Auth,
};
use naia_bevy_server::{events::AuthEvents, Server};

pub(crate) fn auth_events(mut ev: EventReader<AuthEvents>, mut server: Server) {
use crate::Config;

pub(crate) fn auth_events(
    mut ev: EventReader<AuthEvents>,
    mut server: Server,
    config: Res<Config>,
) {
    for events in ev.iter() {
        for (user_key, auth) in events.read::<Auth>() {
            println!("TEMPORARY LOG TO CHECK IF WE GOT AN AUTH EVENT");
            match auth.username {
                Some(username) => {
                    // register
                    server.reject_connection(&user_key);
                    let wrapped =
                        register(&config.api_address, &username, &auth.email, &auth.password);
                    match wrapped.response {
                        ResponseRegister::Error(_) => server.reject_connection(&user_key),
                        ResponseRegister::Ok(_) => server.accept_connection(&user_key),
                    }
                }
                None => {
                    // login
                    server.reject_connection(&user_key);
                    let wrapped = login(&config.api_address, &auth.email, &auth.password);
                    match wrapped.response {
                        ResponseLogin::Error(_) => server.reject_connection(&user_key),
                        ResponseLogin::Ok(_) => server.accept_connection(&user_key),
                    }
                }
            }
        }

M shared/src/api/mod.rs => shared/src/api/mod.rs +2 -1
@@ 9,7 9,8 @@
use reqwest;
use serde::{Deserialize, Serialize};

pub mod game;
//pub mod game;
pub mod types;
pub mod user;

#[derive(Debug, Deserialize, Serialize)]

R shared/src/api/user/types.rs => shared/src/api/types.rs +4 -3
@@ 6,12 6,13 @@
 * See LICENSE for licensing information.
 */

use serde::{Deserialize, Serialize};
use serde::Deserialize;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserPub {
#[derive(Deserialize)]
pub struct User {
    pub id: String,
    pub created_at: String,
    pub updated_at: String,
    pub username: String,
    pub email: String,
}

M shared/src/api/user/mod.rs => shared/src/api/user/mod.rs +58 -55
@@ 9,39 9,52 @@
use reqwest;
use serde::{Deserialize, Serialize};

use super::APIErrorWrapper;
use crate::error::api::APIError;

pub mod types;
use super::types::User;

#[derive(Serialize)]
pub struct PostToken {
pub struct PostLogin {
    pub email: String,
    pub password: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ResultToken {
    pub token: String,
    pub id: String,
#[derive(Deserialize)]
#[serde(untagged)]
pub enum ResponseLogin {
    Error(APIError),
    Ok(User),
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResponseToken {
    Error(APIErrorWrapper),
    Valid(ResultToken),
#[derive(Deserialize)]
pub struct ResponseLoginWrapper {
    pub response: ResponseLogin,
    pub cookie: String,
}

pub fn token(api_address: String, email: String, password: String) -> ResponseToken {
pub fn login(api_address: &str, email: &str, password: &str) -> ResponseLoginWrapper {
    let client = reqwest::blocking::Client::new();

    let resp = client
        .post(&format!("{}/user/token", api_address))
        .json(&PostToken { email, password })
        .post(&format!("{}/user/login", api_address))
        .json(&PostLogin {
            email: email.to_string(),
            password: password.to_string(),
        })
        .send()
        .unwrap();

    resp.json().unwrap()
    let mut cookie = String::from("");
    for c in resp.cookies() {
        if c.name() == "id" {
            cookie = c.value().to_string();
        }
    }

    ResponseLoginWrapper {
        response: resp.json().unwrap(),
        cookie,
    }
}

#[derive(Serialize)]


@@ 51,56 64,46 @@ pub struct PostRegister {
    pub password: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[derive(Deserialize)]
#[serde(untagged)]
pub enum ResponseRegister {
    Error(APIErrorWrapper),
    Valid(types::UserPub),
    Error(APIError),
    Ok(User),
}

#[derive(Deserialize)]
pub struct ResponseRegisterWrapper {
    pub response: ResponseRegister,
    pub cookie: String,
}

pub fn register(
    api_address: String,
    username: String,
    email: String,
    password: String,
) -> ResponseRegister {
    api_address: &str,
    username: &str,
    email: &str,
    password: &str,
) -> ResponseRegisterWrapper {
    let client = reqwest::blocking::Client::new();

    let resp = client
        .post(&format!("{}/user/register", api_address))
        .post(&format!("{}/user", api_address))
        .json(&PostRegister {
            username,
            email,
            password,
            username: username.to_string(),
            email: email.to_string(),
            password: password.to_string(),
        })
        .send()
        .unwrap();

    resp.json().unwrap()
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ResultUserInfoP {
    pub id: String,
    pub username: String,
    pub email: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResponseUserInfoP {
    Error(APIErrorWrapper),
    Valid(ResultUserInfoP),
}

pub fn userinfop(api_address: String, token: String, user_id: String) -> ResponseUserInfoP {
    let client = reqwest::blocking::Client::new();

    let resp = client
        .get(&format!("{}/user/_/{}", api_address, user_id))
        .header("Authorization", token)
        .send()
        .unwrap();

    resp.json().unwrap()
    let mut cookie = String::from("");
    for c in resp.cookies() {
        if c.name() == "id" {
            cookie = c.value().to_string();
        }
    }

    ResponseRegisterWrapper {
        response: resp.json().unwrap(),
        cookie,
    }
}