B:BD[
2.6665] → [
2.6666:8001]
use crate::database::Database;
use rocket::State;
use sqlx::{query, query_as};
use rocket::serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct User {
pub id: i32,
pub name: String,
pub email: String,
#[serde(skip_deserializing)]
pub password: String,
}
impl User {
pub async fn create(&self, db: &State<Database>) -> Result<i32, sqlx::Error> {
let result = query!(
"INSERT INTO users (name, email, password) VALUES ($1, $2, crypt($3, gen_salt('bf'))) RETURNING id",
&self.name,
&self.email.to_lowercase(),
&self.password
)
.fetch_one(&**db)
.await?;
// TODO when I figure out Rust, update self with this id
Ok(result.id)
}
/// Validates a user and password combination, returns a User struct when
/// valid.
pub async fn authenticate(
db: &State<Database>,
name: String,
password: String,
) -> Result<Option<User>, sqlx::Error> {
let result = query_as!(
User,
"SELECT * FROM users WHERE name = $1 AND password = crypt($2, password)",
name,
password
)
.fetch_optional(&**db)
.await?;
Ok(result)
}
}
pub mod users;