User Authentication and Other fixes #1

Merged
vinod merged 30 commits from user-auth into main 2023-02-05 09:01:08 +00:00
9 changed files with 1760 additions and 1145 deletions
Showing only changes of commit 02963caa73 - Show all commits

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1 @@
pub mod entities;

View File

@@ -10,7 +10,6 @@ impl MigrationTrait for Migration {
// Replace the sample below with your own migration scripts
//todo!();
manager
.create_table(
Table::create()
@@ -23,12 +22,17 @@ impl MigrationTrait for Migration {
.auto_increment()
.primary_key(),
)
.col(ColumnDef::new(User::UserName).string().unique_key().not_null())
.col(
ColumnDef::new(User::UserName)
.string()
.unique_key()
.not_null(),
)
.col(ColumnDef::new(User::PasswordHash).string().not_null())
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -65,7 +69,8 @@ impl MigrationTrait for Migration {
)
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -91,7 +96,8 @@ impl MigrationTrait for Migration {
)
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -117,7 +123,8 @@ impl MigrationTrait for Migration {
)
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -143,7 +150,8 @@ impl MigrationTrait for Migration {
)
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -169,7 +177,8 @@ impl MigrationTrait for Migration {
)
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -195,7 +204,8 @@ impl MigrationTrait for Migration {
)
.to_owned(),
)
.await.expect("Migration failed");
.await
.expect("Migration failed");
manager
.create_table(
@@ -230,22 +240,28 @@ impl MigrationTrait for Migration {
manager
.drop_table(Table::drop().table(Book::Table).to_owned())
.await.expect("Drop failed");
.await
.expect("Drop failed");
manager
.drop_table(Table::drop().table(BookAuthor::Table).to_owned())
.await.expect("Drop failed");
.await
.expect("Drop failed");
manager
.drop_table(Table::drop().table(BookPerson::Table).to_owned())
.await.expect("Drop failed");
.await
.expect("Drop failed");
manager
.drop_table(Table::drop().table(BookPlace::Table).to_owned())
.await.expect("Drop failed");
.await
.expect("Drop failed");
manager
.drop_table(Table::drop().table(BookSubject::Table).to_owned())
.await.expect("Drop failed");
.await
.expect("Drop failed");
manager
.drop_table(Table::drop().table(BookTime::Table).to_owned())
.await.expect("Drop failed");
.await
.expect("Drop failed");
manager
.drop_table(Table::drop().table(BookISBN::Table).to_owned())
.await
@@ -275,7 +291,7 @@ enum Book {
TimeAdded,
Rating,
Comments,
UserId
UserId,
}
#[derive(Iden)]

View File

@@ -1,9 +1,11 @@
//use ::entity::entities::prelude::Book;
//use ::entity::entities::{prelude::*, *};
use ::entity::entities::user::Entity as User;
use ::entity::entities::book::Entity as Book;
use ::entity::entities::user::Entity as User;
//, book_author::Entity as Author, book_person::Entity as Person, book_place::Entity as Place, book_subject::Entity as Subject, book_time::Entity as Time, book_isbn::Entity as ISBN};
use ::entity::entities::{book,book_author,book_person,book_place,book_subject,book_time,book_isbn,user};
use ::entity::entities::{
book, book_author, book_isbn, book_person, book_place, book_subject, book_time, user,
};
use sea_orm::*;
//use ::entity::entities::prelude::Book;
@@ -24,15 +26,15 @@ impl Mutation {
pub async fn delete_user(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
let user: user::ActiveModel = User::find_by_id(id)
.one(db)
.await?
.ok_or(DbErr::Custom("Cannot find user.".to_owned()))
.map(Into::into)?;
.one(db)
.await?
.ok_or(DbErr::Custom("Cannot find user.".to_owned()))
.map(Into::into)?;
user.delete(db).await
}
pub async fn create_book(
pub async fn create_book(
db: &DbConn,
form_data: book::Model,
) -> Result<InsertResult<book::ActiveModel>, DbErr> {
@@ -55,7 +57,7 @@ impl Mutation {
Book::insert(record).exec(db).await
}
pub async fn create_book_author(
pub async fn create_book_author(
db: &DbConn,
form_data: book_author::Model,
) -> Result<book_author::ActiveModel, DbErr> {
@@ -68,7 +70,7 @@ impl Mutation {
.await
}
pub async fn create_book_person(
pub async fn create_book_person(
db: &DbConn,
form_data: book_person::Model,
) -> Result<book_person::ActiveModel, DbErr> {
@@ -81,7 +83,7 @@ impl Mutation {
.await
}
pub async fn create_book_place(
pub async fn create_book_place(
db: &DbConn,
form_data: book_place::Model,
) -> Result<book_place::ActiveModel, DbErr> {
@@ -93,7 +95,7 @@ impl Mutation {
.save(db)
.await
}
pub async fn create_book_subject(
pub async fn create_book_subject(
db: &DbConn,
form_data: book_subject::Model,
) -> Result<book_subject::ActiveModel, DbErr> {
@@ -106,7 +108,7 @@ impl Mutation {
.await
}
pub async fn create_book_time(
pub async fn create_book_time(
db: &DbConn,
form_data: book_time::Model,
) -> Result<book_time::ActiveModel, DbErr> {
@@ -119,7 +121,7 @@ impl Mutation {
.await
}
pub async fn create_book_isbn(
pub async fn create_book_isbn(
db: &DbConn,
form_data: book_isbn::Model,
) -> Result<book_isbn::ActiveModel, DbErr> {
@@ -137,7 +139,6 @@ impl Mutation {
id: i32,
form_data: book::Model,
) -> Result<book::Model, DbErr> {
let book: book::ActiveModel = Book::find_by_id(id)
.one(db)
.await?
@@ -159,7 +160,9 @@ impl Mutation {
rating: Set(form_data.rating.to_owned()),
comments: Set(form_data.comments.to_owned()),
user_id: Set(form_data.user_id.to_owned()),
}.update(db).await
}
.update(db)
.await
}
pub async fn delete_book(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
@@ -172,54 +175,49 @@ impl Mutation {
book.delete(db).await
}
pub async fn delete_book_author(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_author::Entity::delete_many().filter(
Condition::any()
.add(book_author::Column::BookId.eq(id))
).exec(db).await
book_author::Entity::delete_many()
.filter(Condition::any().add(book_author::Column::BookId.eq(id)))
.exec(db)
.await
}
pub async fn delete_book_person(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_person::Entity::delete_many().filter(
Condition::any()
.add(book_person::Column::BookId.eq(id))
).exec(db).await
book_person::Entity::delete_many()
.filter(Condition::any().add(book_person::Column::BookId.eq(id)))
.exec(db)
.await
}
pub async fn delete_book_place(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_place::Entity::delete_many().filter(
Condition::any()
.add(book_place::Column::BookId.eq(id))
).exec(db).await
book_place::Entity::delete_many()
.filter(Condition::any().add(book_place::Column::BookId.eq(id)))
.exec(db)
.await
}
pub async fn delete_book_subject(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_subject::Entity::delete_many().filter(
Condition::any()
.add(book_subject::Column::BookId.eq(id))
).exec(db).await
book_subject::Entity::delete_many()
.filter(Condition::any().add(book_subject::Column::BookId.eq(id)))
.exec(db)
.await
}
pub async fn delete_book_time(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_time::Entity::delete_many().filter(
Condition::any()
.add(book_time::Column::BookId.eq(id))
).exec(db).await
book_time::Entity::delete_many()
.filter(Condition::any().add(book_time::Column::BookId.eq(id)))
.exec(db)
.await
}
pub async fn delete_book_isbn(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_isbn::Entity::delete_many().filter(
Condition::any()
.add(book_isbn::Column::BookId.eq(id))
).exec(db).await
book_isbn::Entity::delete_many()
.filter(Condition::any().add(book_isbn::Column::BookId.eq(id)))
.exec(db)
.await
}
pub async fn delete_all_books(db: &DbConn) -> Result<DeleteResult, DbErr> {
pub async fn delete_all_books(db: &DbConn) -> Result<DeleteResult, DbErr> {
Book::delete_many().exec(db).await
}
}

View File

@@ -2,7 +2,9 @@ use ::entity::entities::book::Entity as Book;
use ::entity::entities::user::Entity as User;
//, book_author::Entity as Author, book_person::Entity as Person, book_place::Entity as Place, book_subject::Entity as Subject, book_time::Entity as Time, book_isbn::Entity as ISBN};
use ::entity::entities::{book,book_author,book_person,book_place,book_subject,book_time,book_isbn,user};
use ::entity::entities::{
book, book_author, book_isbn, book_person, book_place, book_subject, book_time, user,
};
//use ::entity::entities::{prelude::*, *};
use sea_orm::*;
//use sea_query::Expr;
@@ -26,12 +28,16 @@ impl Query {
Book::find_by_id(id).one(db).await
}
pub async fn find_userid_by_name(db: &DbConn, name: String) -> Result<Option<user::Model>, DbErr> {
User::find().filter(user::Column::UserName.eq(name)).one(db).await
pub async fn find_userid_by_name(
db: &DbConn,
name: String,
) -> Result<Option<user::Model>, DbErr> {
User::find()
.filter(user::Column::UserName.eq(name))
.one(db)
.await
}
pub async fn find_user_by_id(db: &DbConn, id: i32) -> Result<Option<user::Model>, DbErr> {
User::find_by_id(id).one(db).await
}
@@ -39,13 +45,13 @@ impl Query {
pub async fn list_all_users(db: &DbConn) -> Result<Vec<user::Model>, DbErr> {
User::find().all(db).await
}
/* pub async fn find_bookplusmeta_by_id(db: &DbConn, id: i32) -> Result<Option<(book::Model, Vec<book_author::Model>, Vec<book_person::Model>)>, DbErr> {
let book = Book::find_by_id(id).one(db).await?.unwrap();
let authors = book.find_related(Author).all(db).await?;
let persons = book.find_related(Person).all(db).await?;
Ok(Some((book, authors, persons)))
}
*/
/* pub async fn find_bookplusmeta_by_id(db: &DbConn, id: i32) -> Result<Option<(book::Model, Vec<book_author::Model>, Vec<book_person::Model>)>, DbErr> {
let book = Book::find_by_id(id).one(db).await?.unwrap();
let authors = book.find_related(Author).all(db).await?;
let persons = book.find_related(Person).all(db).await?;
Ok(Some((book, authors, persons)))
}
*/
/// If ok, returns (post models, num pages).
pub async fn find_books_in_page(
@@ -62,20 +68,20 @@ impl Query {
.order_by_desc(book::Column::Id)
.paginate(db, posts_per_page);
let num_pages = paginator.num_pages().await?;
return paginator.fetch_page(page - 1).await.map(|p| (p, num_pages))
return paginator.fetch_page(page - 1).await.map(|p| (p, num_pages));
} else {
let paginator = Book::find()
.filter(book::Column::UserId.eq(userid))
.order_by_asc(book::Column::Id)
.paginate(db, posts_per_page);
let num_pages = paginator.num_pages().await?;
return paginator.fetch_page(page - 1).await.map(|p| (p, num_pages))
return paginator.fetch_page(page - 1).await.map(|p| (p, num_pages));
}
// Fetch paginated posts
}
pub async fn find_books_plus_meta_in_page(
pub async fn find_books_plus_meta_in_page(
db: &DbConn,
page: usize,
posts_per_page: usize,
@@ -83,33 +89,43 @@ pub async fn find_books_plus_meta_in_page(
sort: String,
) -> Result<(Vec<BookAndMetaV2>, u64), DbErr> {
// Setup paginator
let books = Self::find_books_in_page(db,page.try_into().unwrap(),posts_per_page.try_into().unwrap(),userid, sort).await?;
let books = Self::find_books_in_page(
db,
page.try_into().unwrap(),
posts_per_page.try_into().unwrap(),
userid,
sort,
)
.await?;
let book_ids: Vec<i32> = books.0.clone().into_iter().map(|b| b.id).collect();
println!("SIZE IS {} and {:?}", book_ids.len(), book_ids);
let mut resbooks: Vec<BookAndMetaV2> = Vec::with_capacity(book_ids.len());
for book in books.0.iter() {
let bauthors: Vec<book_author::Model> = book.find_related(book_author::Entity).all(db).await?;
let bpersons: Vec<book_person::Model> = book.find_related(book_person::Entity).all(db).await?;
let bplaces: Vec<book_place::Model> = book.find_related(book_place::Entity).all(db).await?;
let bsubjects: Vec<book_subject::Model> = book.find_related(book_subject::Entity).all(db).await?;
let btimes: Vec<book_time::Model> = book.find_related(book_time::Entity).all(db).await?;
let bisbns: Vec<book_isbn::Model> = book.find_related(book_isbn::Entity).all(db).await?;
let bauthors: Vec<book_author::Model> =
book.find_related(book_author::Entity).all(db).await?;
let bpersons: Vec<book_person::Model> =
book.find_related(book_person::Entity).all(db).await?;
let bplaces: Vec<book_place::Model> =
book.find_related(book_place::Entity).all(db).await?;
let bsubjects: Vec<book_subject::Model> =
book.find_related(book_subject::Entity).all(db).await?;
let btimes: Vec<book_time::Model> =
book.find_related(book_time::Entity).all(db).await?;
let bisbns: Vec<book_isbn::Model> =
book.find_related(book_isbn::Entity).all(db).await?;
let bookandmeta = BookAndMetaV2 {
book: (book.clone()),
authors: bauthors,
persons: bpersons,
places: bplaces,
subjects: bsubjects,
times: btimes,
isbns: bisbns
book: (book.clone()),
authors: bauthors,
persons: bpersons,
places: bplaces,
subjects: bsubjects,
times: btimes,
isbns: bisbns,
};
resbooks.push(bookandmeta);
}
Ok((resbooks,books.1))
Ok((resbooks, books.1))
}
}

View File

@@ -1,9 +1,8 @@
use sea_orm::*;
use crate::Query;
use axum::async_trait;
use axum_login::{secrecy::SecretVec, AuthUser, UserStore};
use crate::Query;
use serde::{Serialize, Deserialize};
use sea_orm::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AxumUser {
@@ -16,7 +15,7 @@ type Result<T = ()> = std::result::Result<T, eyre::Error>;
impl<Role> AuthUser<Role> for AxumUser
where
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
{
fn get_id(&self) -> String {
format!("{}", self.id)
@@ -41,7 +40,7 @@ impl AxumUserStore {
#[async_trait]
impl<Role> UserStore<Role> for AxumUserStore
where
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
{
type User = AxumUser;
@@ -59,4 +58,3 @@ Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
}
}
}

View File

@@ -1,6 +1,6 @@
use meilisearch_sdk::client::*;
use meilisearch_sdk::search::*;
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct BookMeili {
@@ -27,33 +27,35 @@ pub struct BookMeili {
pub async fn create_or_update_book(book: BookMeili, userid: i32, client: &Client) {
// An index is where the documents are stored.
let books = client.index(format!("books{}",userid));
let books = client.index(format!("books{}", userid));
// Add some movies in the index. If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
books.add_or_replace(&[
book
], Some("id")).await.unwrap();
books.add_or_replace(&[book], Some("id")).await.unwrap();
}
pub async fn delete_book(bookid: i32, userid: i32, client: &Client) {
// An index is where the documents are stored.
let books = client.index(format!("books{}",userid));
let books = client.index(format!("books{}", userid));
books.delete_document(bookid).await.unwrap();
}
pub async fn search_book(search: &str, page: usize, userid: i32, client: &Client) -> Result<(Vec<BookMeili>, usize), meilisearch_sdk::errors::Error> {
pub async fn search_book(
search: &str,
page: usize,
userid: i32,
client: &Client,
) -> Result<(Vec<BookMeili>, usize), meilisearch_sdk::errors::Error> {
// An index is where the documents are stored.
let books = client.index(format!("books{}",userid));
let results : SearchResults<BookMeili> = books.search().with_query(search).with_offset((page-1)*12)
.execute::<BookMeili>().await.unwrap();
let books = client.index(format!("books{}", userid));
let results: SearchResults<BookMeili> = books
.search()
.with_query(search)
.with_offset((page - 1) * 12)
.execute::<BookMeili>()
.await
.unwrap();
let formatted_results : Vec<BookMeili> = (results.hits).iter().map(|r| r.result.clone()).collect();
//.iter()s.map(|r| r.formatted_result.unwrap()).collect();
return Ok((formatted_results, results.estimated_total_hits));
let formatted_results: Vec<BookMeili> =
(results.hits).iter().map(|r| r.result.clone()).collect();
//.iter()s.map(|r| r.formatted_result.unwrap()).collect();
return Ok((formatted_results, results.estimated_total_hits));
}

View File

@@ -1,4 +1,3 @@
fn main() {
booksman_api::main();
}

File diff suppressed because it is too large Load Diff