Compare commits

..

No commits in common. "d01ee9ae7378cbdf17cef99c4c420327d63ab613" and "16c1fd028a04e499244e6a5eeaf945339bdc8f14" have entirely different histories.

3 changed files with 43 additions and 149 deletions

View File

@ -1 +0,0 @@
pub mod tables;

View File

@ -3,14 +3,14 @@ use rocket::http::Status;
use rocket::response::content::{self, RawHtml}; use rocket::response::content::{self, RawHtml};
use rocket::{Build, Request, Rocket}; use rocket::{Build, Request, Rocket};
use rocket_db_pools::sqlx::pool::PoolConnection; use rocket_db_pools::sqlx::pool::PoolConnection;
use rocket_db_pools::sqlx::Postgres; use rocket_db_pools::sqlx::{Executor, Postgres, Row};
use rocket_db_pools::Connection; use rocket_db_pools::Connection;
use std::fs; use std::fs;
#[macro_use] #[macro_use]
extern crate rocket; extern crate rocket;
use rocket_db_pools::{ use rocket_db_pools::{
sqlx::{self, Executor}, sqlx::{self, FromRow, PgPool},
Database, Database,
}; };
@ -21,8 +21,6 @@ use rocket::{
tokio::time::{sleep, Duration}, tokio::time::{sleep, Duration},
}; };
use fossil::tables::{Db, Post, User};
#[get("/")] #[get("/")]
fn hello() -> RawHtml<String> { fn hello() -> RawHtml<String> {
content::RawHtml(fs::read_to_string("/srv/web/index.html").unwrap()) content::RawHtml(fs::read_to_string("/srv/web/index.html").unwrap())
@ -47,22 +45,6 @@ struct LoginInfo {
password: String, password: String,
} }
#[post("/createuser", data = "<info>")]
async fn createuser(
db: Connection<Db>,
info: Json<LoginInfo>,
cookies: &CookieJar<'_>,
) -> &'static str {
let token = cookies.get_private("token");
match token.is_some() {
true => "You're already logged in. Log out before trying to create a new account.",
false => {
User::create(db, &info.username, &info.password).await;
"Account created."
}
}
}
#[post("/login", data = "<info>")] #[post("/login", data = "<info>")]
async fn login(info: Json<LoginInfo>, cookies: &CookieJar<'_>) -> &'static str { async fn login(info: Json<LoginInfo>, cookies: &CookieJar<'_>) -> &'static str {
let token = cookies.get_private("token"); let token = cookies.get_private("token");
@ -95,24 +77,56 @@ async fn logout(cookies: &CookieJar<'_>) -> &'static str {
} }
} }
#[derive(Database)]
#[database("diesel_postgres")]
struct Db(PgPool);
#[derive(FromRow)]
struct Post {
id: i64,
title: String,
body: String,
published: bool,
}
#[get("/dbtest/<id>")] #[get("/dbtest/<id>")]
async fn dbtest(db: Connection<Db>, id: i32) -> Option<String> { async fn dbtest(mut db: Connection<Db>, id: i64) -> Option<String> {
let post = Post::get(db, id).await; let res = db
.fetch_one(sqlx::query_as::<_, Post>(
&format!("SELECT * FROM posts WHERE id = {id};")[..],
))
.await
.unwrap();
Some(format!( Some(format!(
"ID: {}\nTitle: {}\nBody: {}\nPublished: {}", "{}\n{}\n{}\n{}",
post.id, post.title, post.body, post.published res.get::<i32, _>("id"),
res.get::<String, _>("title"),
res.get::<String, _>("body"),
res.get::<bool, _>("published")
)) ))
} }
#[get("/dbcreate/<title>/<body>/<published>")] #[get("/dbcreate/<title>/<body>/<published>")]
async fn dbcreate( async fn dbcreate(
db: Connection<Db>, mut db: Connection<Db>,
title: String, title: String,
body: String, body: String,
published: bool, published: bool,
) -> &'static str { ) -> &'static str {
Post::create(db, title, body, published).await; db.fetch_all(
"created!" sqlx::query(
r#"
INSERT INTO posts (title, body, published)
VALUES ($1, $2, $3);
"#,
)
.bind(title)
.bind(body)
.bind(published),
)
.await
.unwrap();
"created maybe"
} }
#[catch(default)] #[catch(default)]
@ -128,7 +142,7 @@ async fn migrate(rocket: Rocket<Build>) -> Rocket<Build> {
let db = Db::fetch(&rocket).unwrap(); let db = Db::fetch(&rocket).unwrap();
let mut conn: PoolConnection<Postgres> = db.acquire().await.unwrap(); let mut conn: PoolConnection<Postgres> = db.acquire().await.unwrap();
let _ = conn let row = conn
.fetch_one(sqlx::query_as::<_, Post>( .fetch_one(sqlx::query_as::<_, Post>(
"CREATE TABLE IF NOT EXISTS posts ( "CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
@ -138,18 +152,8 @@ async fn migrate(rocket: Rocket<Build>) -> Rocket<Build> {
)", )",
)) ))
.await; .await;
let _2 = conn
.fetch_one(sqlx::query(
"CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR NOT NULL,
password TEXT NOT NULL,
token TEXT
)",
))
.await;
rocket rocket.manage(row)
} }
#[rocket::main] #[rocket::main]

View File

@ -1,109 +0,0 @@
use rocket_db_pools::sqlx::Executor;
use rocket_db_pools::Connection;
use sqlx::FromRow;
use rocket_db_pools::{
sqlx::{self, PgPool, Row},
Database,
};
#[derive(Database)]
#[database("diesel_postgres")]
pub struct Db(PgPool);
#[derive(FromRow)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
impl Post {
pub async fn create(mut db: Connection<Db>, title: String, body: String, published: bool) {
match db
.fetch_all(
sqlx::query(
r#"
INSERT INTO posts (title, body, published)
VALUES ($1, $2, $3);
"#,
)
.bind(title)
.bind(body)
.bind(published),
)
.await
{
Ok(_) => (),
Err(why) => {
eprintln!("Couldn't create database entry: {why:?}");
}
}
}
pub async fn get(mut db: Connection<Db>, id: i32) -> Post {
let res = db
.fetch_one(sqlx::query("SELECT * FROM posts WHERE id = $1;").bind(id))
.await
.unwrap();
Post {
id: res.get::<i32, _>("id"),
title: res.get::<String, _>("title"),
body: res.get::<String, _>("body"),
published: res.get::<bool, _>("published"),
}
}
}
#[derive(FromRow)]
pub struct User {
pub id: i32,
pub username: String,
pub password: String,
pub token: Option<String>,
}
impl User {
pub async fn create(mut db: Connection<Db>, username: &String, password: &String) {
match db
.fetch_all(
sqlx::query(
r#"
INSERT INTO users (username, password)
VALUES ($1, $2);
"#,
)
.bind(username)
.bind(password),
)
.await
{
Ok(_) => (),
Err(why) => {
eprintln!("Couldn't create database entry: {why:?}");
}
}
}
pub async fn get_by_id(mut db: Connection<Db>, id: i32) -> User {
let res = db
.fetch_one(sqlx::query("SELECT * FROM users WHERE id = $1;").bind(id))
.await
.unwrap();
User {
id: res.get::<i32, _>("id"),
username: res.get::<String, _>("username"),
password: res.get::<String, _>("password"),
token: res.get::<Option<String>, _>("token"),
}
}
pub async fn get_by_token(mut db: Connection<Db>, token: String) -> User {
let res = db
.fetch_one(sqlx::query("SELECT * FROM users WHERE token = $1;").bind(token))
.await
.unwrap();
User {
id: res.get::<i32, _>("id"),
username: res.get::<String, _>("username"),
password: res.get::<String, _>("password"),
token: res.get::<Option<String>, _>("token"),
}
}
}