This commit is contained in:
@@ -10,7 +10,14 @@ use axum::{
|
||||
use rand_core::OsRng;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::{responses::{registration::RegistrationResponse, authentication::{AuthenticationResponse, AuthenticationSuccess}}, api::client_server::errors::authentication_error::AuthenticationError};
|
||||
use crate::{
|
||||
api::client_server::errors::authentication_error::AuthenticationError,
|
||||
models::sessions::Session,
|
||||
responses::{
|
||||
authentication::{AuthenticationResponse, AuthenticationSuccess},
|
||||
registration::RegistrationResponse,
|
||||
},
|
||||
};
|
||||
use crate::{
|
||||
models::devices::Device,
|
||||
responses::{flow::Flows, registration::RegistrationSuccess},
|
||||
@@ -41,10 +48,11 @@ async fn get_login() -> Result<Json<Flows>, ApiError> {
|
||||
async fn post_login(
|
||||
Extension(config): Extension<Arc<Config>>,
|
||||
Extension(db): Extension<SqlitePool>,
|
||||
Json(body): Json<AuthenticationData>
|
||||
Json(body): Json<AuthenticationData>,
|
||||
) -> Result<Json<AuthenticationResponse>, ApiError> {
|
||||
let user = UserId::new("name", "server_name").ok().ok_or(AuthenticationError::InvalidUserId)?;
|
||||
todo!("Flesh this out more");
|
||||
let user = UserId::new("name", "server_name")
|
||||
.ok()
|
||||
.ok_or(AuthenticationError::InvalidUserId)?;
|
||||
let resp = AuthenticationSuccess::new("", "", &user);
|
||||
|
||||
Ok(Json(AuthenticationResponse::Success(resp)))
|
||||
@@ -92,22 +100,29 @@ async fn post_register(
|
||||
None => "Random displayname",
|
||||
};
|
||||
|
||||
let user =
|
||||
User::create(&db, &user_id, &user_id.to_string(), auth_data.password()).await?;
|
||||
let device = Device::create(&db, &user, "test", display_name).await?;
|
||||
let user = User::new(&user_id, &user_id.to_string(), auth_data.password())?
|
||||
.create(&db)
|
||||
.await?;
|
||||
|
||||
let device = Device::new(&user, "test", display_name)?
|
||||
.create(&db)
|
||||
.await?;
|
||||
|
||||
(user, device)
|
||||
}
|
||||
};
|
||||
|
||||
if body.inhibit_login().unwrap_or(false) {
|
||||
let resp = RegistrationSuccess::new(None, device.device_id(), user.user_id());
|
||||
let resp = RegistrationSuccess::new(None, device.device_id(), &user.user_id().to_string());
|
||||
|
||||
Ok(Json(RegistrationResponse::Success(resp)))
|
||||
} else {
|
||||
let session = device.create_session(&db).await?;
|
||||
let resp =
|
||||
RegistrationSuccess::new(Some(session.value()), device.device_id(), user.user_id());
|
||||
let session = Session::new(&device)?.create(&db).await?;
|
||||
let resp = RegistrationSuccess::new(
|
||||
Some(session.key()),
|
||||
device.device_id(),
|
||||
&user.user_id().to_string(),
|
||||
);
|
||||
|
||||
Ok(Json(RegistrationResponse::Success(resp)))
|
||||
}
|
||||
|
@@ -38,8 +38,9 @@ pub enum ApiError {
|
||||
impl From<anyhow::Error> for ApiError {
|
||||
fn from(err: anyhow::Error) -> Self {
|
||||
map_err!(err,
|
||||
sqlx::Error => ApiError::DBError,
|
||||
RegistrationError => ApiError::RegistrationError
|
||||
sqlx::Error => ApiError::DBError,
|
||||
RegistrationError => ApiError::RegistrationError,
|
||||
AuthenticationError => ApiError::AuthenticationError
|
||||
);
|
||||
|
||||
ApiError::Generic(err)
|
||||
|
@@ -30,12 +30,22 @@ impl IntoResponse for AuthenticationError {
|
||||
.into_response(),
|
||||
Self::Forbidden => (
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(ErrorResponse::new(ErrorCode::Forbidden, &self.to_string(), None)),
|
||||
).into_response(),
|
||||
Json(ErrorResponse::new(
|
||||
ErrorCode::Forbidden,
|
||||
&self.to_string(),
|
||||
None,
|
||||
)),
|
||||
)
|
||||
.into_response(),
|
||||
Self::UserDeactivated => (
|
||||
StatusCode::FORBIDDEN,
|
||||
Json(ErrorResponse::new(ErrorCode::UserDeactivated, &self.to_string(), None)),
|
||||
).into_response(),
|
||||
Json(ErrorResponse::new(
|
||||
ErrorCode::UserDeactivated,
|
||||
&self.to_string(),
|
||||
None,
|
||||
)),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -20,4 +20,4 @@ impl ErrorResponse {
|
||||
retry_after_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,50 +1,50 @@
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::types::uuid::Uuid;
|
||||
|
||||
use super::{sessions::Session, users::User};
|
||||
|
||||
pub struct Device {
|
||||
id: i64,
|
||||
user_id: i64,
|
||||
uuid: Uuid,
|
||||
user_uuid: Uuid,
|
||||
device_id: String,
|
||||
display_name: String,
|
||||
}
|
||||
|
||||
impl Device {
|
||||
pub async fn create(
|
||||
conn: &SqlitePool,
|
||||
user: &User,
|
||||
device_id: &str,
|
||||
display_name: &str,
|
||||
) -> anyhow::Result<Self> {
|
||||
let user_id = user.id();
|
||||
Ok(sqlx::query_as!(Self, "insert into devices(user_id, device_id, display_name) values(?, ?, ?) returning id, user_id, device_id, display_name", user_id, device_id, display_name).fetch_one(conn).await?)
|
||||
pub fn new(user: &User, device_id: &str, display_name: &str) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
uuid: uuid::Uuid::new_v4().into(),
|
||||
user_uuid: user.uuid().clone(),
|
||||
device_id: device_id.to_owned(),
|
||||
display_name: display_name.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn by_user(conn: &SqlitePool, user: &User) -> anyhow::Result<Self> {
|
||||
let user_id = user.id();
|
||||
pub async fn create(&self, conn: &SqlitePool) -> anyhow::Result<Self> {
|
||||
Ok(sqlx::query_as!(
|
||||
Self,
|
||||
"select id, user_id, device_id, display_name from devices where user_id = ?",
|
||||
user_id
|
||||
"insert into devices(uuid, user_uuid, device_id, display_name)
|
||||
values(?, ?, ?, ?)
|
||||
returning uuid as 'uuid: Uuid', user_uuid as 'user_uuid: Uuid', device_id, display_name",
|
||||
self.uuid,
|
||||
self.user_uuid,
|
||||
self.device_id,
|
||||
self.display_name)
|
||||
.fetch_one(conn).await?
|
||||
)
|
||||
.fetch_one(conn)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn create_session(&self, conn: &SqlitePool) -> anyhow::Result<Session> {
|
||||
Ok(Session::create(conn, self, "random_session_id").await?)
|
||||
}
|
||||
|
||||
/// Get the device's id.
|
||||
#[must_use]
|
||||
pub fn id(&self) -> i64 {
|
||||
self.id
|
||||
pub fn uuid(&self) -> &Uuid {
|
||||
&self.uuid
|
||||
}
|
||||
|
||||
/// Get the device's user id.
|
||||
#[must_use]
|
||||
pub fn user_id(&self) -> i64 {
|
||||
self.user_id
|
||||
pub fn user_uuid(&self) -> &Uuid {
|
||||
&self.user_uuid
|
||||
}
|
||||
|
||||
/// Get a reference to the device's device id.
|
||||
|
@@ -1,21 +1,33 @@
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::types::uuid::Uuid;
|
||||
|
||||
use super::devices::Device;
|
||||
|
||||
pub struct Session {
|
||||
id: i64,
|
||||
device_id: i64,
|
||||
value: String,
|
||||
uuid: Uuid,
|
||||
device_uuid: Uuid,
|
||||
key: String,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub async fn create(conn: &SqlitePool, device: &Device, value: &str) -> anyhow::Result<Self> {
|
||||
let device_id = device.id();
|
||||
pub fn new(device: &Device) -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
uuid: uuid::Uuid::new_v4().into(),
|
||||
device_uuid: device.uuid().clone(),
|
||||
key: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn create(&self, conn: &SqlitePool) -> anyhow::Result<Self> {
|
||||
Ok(sqlx::query_as!(
|
||||
Self,
|
||||
"insert into sessions(device_id, value) values(?, ?) returning id, device_id, value",
|
||||
device_id,
|
||||
value
|
||||
"insert into sessions(uuid, device_uuid, key)
|
||||
values(?, ?, ?)
|
||||
returning uuid as 'uuid: Uuid', device_uuid as 'device_uuid: Uuid', key",
|
||||
self.uuid,
|
||||
self.device_uuid,
|
||||
self.key
|
||||
)
|
||||
.fetch_one(conn)
|
||||
.await?)
|
||||
@@ -23,19 +35,19 @@ impl Session {
|
||||
|
||||
/// Get the session's id.
|
||||
#[must_use]
|
||||
pub fn id(&self) -> i64 {
|
||||
self.id
|
||||
pub fn uuid(&self) -> &Uuid {
|
||||
&self.uuid
|
||||
}
|
||||
|
||||
/// Get the session's device id.
|
||||
#[must_use]
|
||||
pub fn device_id(&self) -> i64 {
|
||||
self.device_id
|
||||
pub fn device_uuid(&self) -> &Uuid {
|
||||
&self.device_uuid
|
||||
}
|
||||
|
||||
/// Get a reference to the session's value.
|
||||
#[must_use]
|
||||
pub fn value(&self) -> &str {
|
||||
self.value.as_ref()
|
||||
pub fn key(&self) -> &str {
|
||||
self.key.as_ref()
|
||||
}
|
||||
}
|
||||
|
@@ -1,17 +1,33 @@
|
||||
use crate::types::uuid::Uuid;
|
||||
use argon2::{password_hash::SaltString, Argon2, PasswordHasher};
|
||||
use rand_core::OsRng;
|
||||
use sqlx::SqlitePool;
|
||||
use sqlx::{encode::IsNull, sqlite::SqliteTypeInfo, FromRow, Sqlite, SqlitePool};
|
||||
|
||||
use crate::types::user_id::UserId;
|
||||
|
||||
pub struct User {
|
||||
id: i64,
|
||||
user_id: String,
|
||||
uuid: Uuid,
|
||||
user_id: UserId,
|
||||
display_name: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn new(user_id: &UserId, display_name: &str, password: &str) -> anyhow::Result<Self> {
|
||||
let argon2 = Argon2::default();
|
||||
let salt = SaltString::generate(OsRng);
|
||||
let password = argon2
|
||||
.hash_password(password.as_bytes(), &salt)?
|
||||
.to_string();
|
||||
|
||||
Ok(Self {
|
||||
uuid: uuid::Uuid::new_v4().into(),
|
||||
user_id: user_id.clone(),
|
||||
display_name: display_name.to_owned(),
|
||||
password,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn exists(conn: &SqlitePool, user_id: &UserId) -> anyhow::Result<bool> {
|
||||
Ok(
|
||||
sqlx::query!("select user_id from users where user_id = ?", user_id)
|
||||
@@ -21,25 +37,42 @@ impl User {
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
conn: &SqlitePool,
|
||||
user_id: &UserId,
|
||||
display_name: &str,
|
||||
password: &str,
|
||||
) -> anyhow::Result<Self> {
|
||||
let salt = SaltString::generate(OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
let pw_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)?
|
||||
.to_string();
|
||||
|
||||
Ok(sqlx::query_as!(Self, "insert into users(user_id, display_name, password) values (?, ?, ?) returning id, user_id, display_name, password", user_id, display_name, pw_hash).fetch_one(conn).await?)
|
||||
pub async fn create(&self, conn: &SqlitePool) -> anyhow::Result<Self> {
|
||||
Ok(sqlx::query_as!(
|
||||
Self,
|
||||
"insert into users(uuid, user_id, display_name, password)
|
||||
values (?, ?, ?, ?)
|
||||
returning uuid as 'uuid: Uuid', user_id as 'user_id: UserId', display_name, password",
|
||||
self.uuid,
|
||||
self.user_id,
|
||||
self.display_name,
|
||||
self.password
|
||||
)
|
||||
.fetch_one(conn)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn update(&self, conn: &SqlitePool) -> anyhow::Result<Self> {
|
||||
Ok(sqlx::query_as!(
|
||||
Self,
|
||||
"update users set uuid = ?, user_id = ?, display_name = ?, password = ?
|
||||
where uuid = ?
|
||||
returning uuid as 'uuid: Uuid', user_id as 'user_id: UserId', display_name, password",
|
||||
self.uuid,
|
||||
self.user_id,
|
||||
self.display_name,
|
||||
self.password,
|
||||
self.uuid
|
||||
)
|
||||
.fetch_one(conn)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn by_user_id(conn: &SqlitePool, user_id: &UserId) -> anyhow::Result<Self> {
|
||||
Ok(sqlx::query_as!(
|
||||
Self,
|
||||
"select id, user_id, display_name, password from users where user_id = ?",
|
||||
"select uuid as 'uuid: Uuid', user_id as 'user_id: UserId', display_name, password
|
||||
from users where user_id = ?",
|
||||
user_id
|
||||
)
|
||||
.fetch_one(conn)
|
||||
@@ -48,14 +81,14 @@ impl User {
|
||||
|
||||
/// Get the user's id.
|
||||
#[must_use]
|
||||
pub fn id(&self) -> i64 {
|
||||
self.id
|
||||
pub fn uuid(&self) -> &Uuid {
|
||||
&self.uuid
|
||||
}
|
||||
|
||||
/// Get a reference to the user's user id.
|
||||
#[must_use]
|
||||
pub fn user_id(&self) -> &str {
|
||||
self.user_id.as_ref()
|
||||
pub fn user_id(&self) -> &UserId {
|
||||
&self.user_id
|
||||
}
|
||||
|
||||
/// Get a reference to the user's password.
|
||||
|
@@ -1 +1 @@
|
||||
pub mod registration;
|
||||
pub mod registration;
|
||||
|
@@ -5,7 +5,7 @@ use crate::types::user_id::UserId;
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum AuthenticationResponse {
|
||||
Success(AuthenticationSuccess)
|
||||
Success(AuthenticationSuccess),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
@@ -23,4 +23,4 @@ impl AuthenticationSuccess {
|
||||
user_id: user_id.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,5 @@
|
||||
pub mod authentication;
|
||||
pub mod flow;
|
||||
pub mod registration;
|
||||
pub mod username_available;
|
||||
pub mod versions;
|
||||
pub mod authentication;
|
@@ -12,7 +12,7 @@ pub enum ErrorCode {
|
||||
UserInUse,
|
||||
InvalidUsername,
|
||||
Exclusive,
|
||||
UserDeactivated
|
||||
UserDeactivated,
|
||||
}
|
||||
|
||||
impl serde::Serialize for ErrorCode {
|
||||
|
@@ -5,3 +5,4 @@ pub mod identifier;
|
||||
pub mod identifier_type;
|
||||
pub mod user_id;
|
||||
pub mod user_interactive_authorization;
|
||||
pub mod uuid;
|
||||
|
@@ -1,10 +1,40 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
#[derive(sqlx::Type)]
|
||||
#[sqlx(transparent)]
|
||||
use sqlx::{encode::IsNull, Sqlite};
|
||||
|
||||
#[derive(Clone)]
|
||||
#[repr(transparent)]
|
||||
pub struct UserId(String);
|
||||
|
||||
impl sqlx::Type<Sqlite> for UserId {
|
||||
fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo {
|
||||
<&str as sqlx::Type<Sqlite>>::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e> sqlx::Encode<'e, Sqlite> for UserId {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Sqlite as sqlx::database::HasArguments<'e>>::ArgumentBuffer,
|
||||
) -> sqlx::encode::IsNull {
|
||||
buf.push(sqlx::sqlite::SqliteArgumentValue::Text(
|
||||
self.0.to_string().into(),
|
||||
));
|
||||
|
||||
IsNull::No
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d> sqlx::Decode<'d, Sqlite> for UserId {
|
||||
fn decode(
|
||||
value: <Sqlite as sqlx::database::HasValueRef<'d>>::ValueRef,
|
||||
) -> Result<Self, sqlx::error::BoxDynError> {
|
||||
let value = <String as sqlx::Decode<Sqlite>>::decode(value)?;
|
||||
|
||||
Ok(UserId(value))
|
||||
}
|
||||
}
|
||||
|
||||
impl UserId {
|
||||
pub fn new(name: &str, server_name: &str) -> anyhow::Result<Self> {
|
||||
let user_id = Self(format!("@{name}:{server_name}"));
|
||||
|
45
src/types/uuid.rs
Normal file
45
src/types/uuid.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use sqlx::{encode::IsNull, Sqlite, Type};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Uuid(pub uuid::Uuid);
|
||||
|
||||
impl Uuid {
|
||||
pub fn new_v4() -> Self {
|
||||
Uuid(uuid::Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Sqlite> for Uuid {
|
||||
fn type_info() -> <Sqlite as sqlx::Database>::TypeInfo {
|
||||
<&str as Type<Sqlite>>::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e> sqlx::Encode<'e, Sqlite> for Uuid {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Sqlite as sqlx::database::HasArguments<'e>>::ArgumentBuffer,
|
||||
) -> sqlx::encode::IsNull {
|
||||
buf.push(sqlx::sqlite::SqliteArgumentValue::Text(
|
||||
self.0.to_string().into(),
|
||||
));
|
||||
|
||||
IsNull::No
|
||||
}
|
||||
}
|
||||
|
||||
impl<'d> sqlx::Decode<'d, Sqlite> for Uuid {
|
||||
fn decode(
|
||||
value: <Sqlite as sqlx::database::HasValueRef<'d>>::ValueRef,
|
||||
) -> Result<Self, sqlx::error::BoxDynError> {
|
||||
let value = <&str as sqlx::Decode<Sqlite>>::decode(value)?;
|
||||
|
||||
Ok(Uuid(uuid::Uuid::parse_str(value)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<uuid::Uuid> for Uuid {
|
||||
fn from(uuid: uuid::Uuid) -> Self {
|
||||
Uuid(uuid)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user