|
- use diesel::prelude::*;
- use diesel::RunQueryDsl;
- use diesel::pg::PgConnection;
- use diesel::r2d2;
- use serde::Serialize;
-
- use crate::db::db::establish_connection;
- use crate::schema::users;
- use crate::schema::users::dsl::*;
-
- #[derive(Insertable)]
- #[diesel(table_name = users)]
- pub struct NewUserInsert {
- pub username: String,
- pub password_hash: String,
- pub stellar_address: String,
- pub email: Option<String>,
- }
-
- #[derive(Serialize)]
- pub struct RegisteredUser {
- pub id: i32,
- pub username: String,
- pub stellar_address: String,
- pub email: Option<String>,
- }
-
- #[derive(Queryable)]
- pub struct UserAuth {
- pub id: i32,
- pub username: String,
- pub full_name: Option<String>,
- pub password_hash: String,
- pub stellar_address: String,
- pub email: Option<String>,
- pub is_active: bool,
- }
-
- #[derive(Queryable, Serialize)]
- pub struct UserForAuth {
- pub id: i32,
- pub full_name: Option<String>,
- pub username: String,
- pub stellar_address: String,
- pub email: Option<String>,
- pub is_active: bool,
- }
-
- fn get_conn() -> Result<r2d2::PooledConnection<diesel::r2d2::ConnectionManager<PgConnection>>, diesel::result::Error> {
- let pool = establish_connection().map_err(|_| {
- diesel::result::Error::DatabaseError(
- diesel::result::DatabaseErrorKind::Unknown,
- Box::new("Failed to establish database connection".to_string()),
- )
- })?;
-
- pool.get().map_err(|_| {
- diesel::result::Error::DatabaseError(
- diesel::result::DatabaseErrorKind::Unknown,
- Box::new("Failed to get database connection from pool".to_string()),
- )
- })
- }
-
- pub(crate) fn create_user(
- new_user: NewUserInsert,
- ) -> Result<RegisteredUser, diesel::result::Error> {
- let mut conn = get_conn()?;
-
- diesel::insert_into(users::table)
- .values(&new_user)
- .returning((id, username, stellar_address, email))
- .get_result::<(i32, String, String, Option<String>)>(&mut conn)
- .map(|(uid, uname, saddr, mail)| RegisteredUser {
- id: uid,
- username: uname,
- stellar_address: saddr,
- email: mail,
- })
- }
-
- pub(crate) fn find_user_by_username(uname: &str) -> Result<UserAuth, diesel::result::Error> {
- let mut conn = get_conn()?;
-
- users
- .filter(username.eq(uname))
- .select((id, username, full_name, password_hash, stellar_address, email, is_active))
- .first::<UserAuth>(&mut conn)
- }
-
- pub(crate) fn get_user_for_auth_by_stellar(addr: &str) -> Result<UserForAuth, diesel::result::Error> {
- let mut conn = get_conn()?;
-
- users
- .filter(stellar_address.eq(addr))
- .select((id, full_name, username, stellar_address, email, is_active))
- .first::<UserForAuth>(&mut conn)
- }
-
- pub(crate) fn get_user_for_auth_by_email(mail: &str) -> Result<UserForAuth, diesel::result::Error> {
- let mut conn = get_conn()?;
-
- users
- .filter(email.eq(mail))
- .select((id, full_name, username, stellar_address, email, is_active))
- .first::<UserForAuth>(&mut conn)
- }
|