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; pub mod entities;

View File

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

View File

@@ -1,9 +1,11 @@
//use ::entity::entities::prelude::Book; //use ::entity::entities::prelude::Book;
//use ::entity::entities::{prelude::*, *}; //use ::entity::entities::{prelude::*, *};
use ::entity::entities::user::Entity as User;
use ::entity::entities::book::Entity as Book; 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}; //, 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 sea_orm::*;
//use ::entity::entities::prelude::Book; //use ::entity::entities::prelude::Book;
@@ -137,7 +139,6 @@ impl Mutation {
id: i32, id: i32,
form_data: book::Model, form_data: book::Model,
) -> Result<book::Model, DbErr> { ) -> Result<book::Model, DbErr> {
let book: book::ActiveModel = Book::find_by_id(id) let book: book::ActiveModel = Book::find_by_id(id)
.one(db) .one(db)
.await? .await?
@@ -159,7 +160,9 @@ impl Mutation {
rating: Set(form_data.rating.to_owned()), rating: Set(form_data.rating.to_owned()),
comments: Set(form_data.comments.to_owned()), comments: Set(form_data.comments.to_owned()),
user_id: Set(form_data.user_id.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> { pub async fn delete_book(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
@@ -172,53 +175,48 @@ impl Mutation {
book.delete(db).await book.delete(db).await
} }
pub async fn delete_book_author(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> { pub async fn delete_book_author(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_author::Entity::delete_many().filter( book_author::Entity::delete_many()
Condition::any() .filter(Condition::any().add(book_author::Column::BookId.eq(id)))
.add(book_author::Column::BookId.eq(id)) .exec(db)
).exec(db).await .await
} }
pub async fn delete_book_person(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> { pub async fn delete_book_person(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_person::Entity::delete_many().filter( book_person::Entity::delete_many()
Condition::any() .filter(Condition::any().add(book_person::Column::BookId.eq(id)))
.add(book_person::Column::BookId.eq(id)) .exec(db)
).exec(db).await .await
} }
pub async fn delete_book_place(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> { pub async fn delete_book_place(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_place::Entity::delete_many().filter( book_place::Entity::delete_many()
Condition::any() .filter(Condition::any().add(book_place::Column::BookId.eq(id)))
.add(book_place::Column::BookId.eq(id)) .exec(db)
).exec(db).await .await
} }
pub async fn delete_book_subject(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> { pub async fn delete_book_subject(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_subject::Entity::delete_many().filter( book_subject::Entity::delete_many()
Condition::any() .filter(Condition::any().add(book_subject::Column::BookId.eq(id)))
.add(book_subject::Column::BookId.eq(id)) .exec(db)
).exec(db).await .await
} }
pub async fn delete_book_time(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> { pub async fn delete_book_time(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_time::Entity::delete_many().filter( book_time::Entity::delete_many()
Condition::any() .filter(Condition::any().add(book_time::Column::BookId.eq(id)))
.add(book_time::Column::BookId.eq(id)) .exec(db)
).exec(db).await .await
} }
pub async fn delete_book_isbn(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> { pub async fn delete_book_isbn(db: &DbConn, id: i32) -> Result<DeleteResult, DbErr> {
book_isbn::Entity::delete_many().filter( book_isbn::Entity::delete_many()
Condition::any() .filter(Condition::any().add(book_isbn::Column::BookId.eq(id)))
.add(book_isbn::Column::BookId.eq(id)) .exec(db)
).exec(db).await .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 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; 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}; //, 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 ::entity::entities::{prelude::*, *};
use sea_orm::*; use sea_orm::*;
//use sea_query::Expr; //use sea_query::Expr;
@@ -26,12 +28,16 @@ impl Query {
Book::find_by_id(id).one(db).await Book::find_by_id(id).one(db).await
} }
pub async fn find_userid_by_name(
pub async fn find_userid_by_name(db: &DbConn, name: String) -> Result<Option<user::Model>, DbErr> { db: &DbConn,
User::find().filter(user::Column::UserName.eq(name)).one(db).await 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> { pub async fn find_user_by_id(db: &DbConn, id: i32) -> Result<Option<user::Model>, DbErr> {
User::find_by_id(id).one(db).await User::find_by_id(id).one(db).await
} }
@@ -39,7 +45,7 @@ impl Query {
pub async fn list_all_users(db: &DbConn) -> Result<Vec<user::Model>, DbErr> { pub async fn list_all_users(db: &DbConn) -> Result<Vec<user::Model>, DbErr> {
User::find().all(db).await 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> { /* 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 book = Book::find_by_id(id).one(db).await?.unwrap();
let authors = book.find_related(Author).all(db).await?; let authors = book.find_related(Author).all(db).await?;
let persons = book.find_related(Person).all(db).await?; let persons = book.find_related(Person).all(db).await?;
@@ -62,20 +68,20 @@ impl Query {
.order_by_desc(book::Column::Id) .order_by_desc(book::Column::Id)
.paginate(db, posts_per_page); .paginate(db, posts_per_page);
let num_pages = paginator.num_pages().await?; 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 { } else {
let paginator = Book::find() let paginator = Book::find()
.filter(book::Column::UserId.eq(userid)) .filter(book::Column::UserId.eq(userid))
.order_by_asc(book::Column::Id) .order_by_asc(book::Column::Id)
.paginate(db, posts_per_page); .paginate(db, posts_per_page);
let num_pages = paginator.num_pages().await?; 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 // Fetch paginated posts
} }
pub async fn find_books_plus_meta_in_page( pub async fn find_books_plus_meta_in_page(
db: &DbConn, db: &DbConn,
page: usize, page: usize,
posts_per_page: usize, posts_per_page: usize,
@@ -83,17 +89,30 @@ pub async fn find_books_plus_meta_in_page(
sort: String, sort: String,
) -> Result<(Vec<BookAndMetaV2>, u64), DbErr> { ) -> Result<(Vec<BookAndMetaV2>, u64), DbErr> {
// Setup paginator // 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(); let book_ids: Vec<i32> = books.0.clone().into_iter().map(|b| b.id).collect();
println!("SIZE IS {} and {:?}", book_ids.len(), book_ids); println!("SIZE IS {} and {:?}", book_ids.len(), book_ids);
let mut resbooks: Vec<BookAndMetaV2> = Vec::with_capacity(book_ids.len()); let mut resbooks: Vec<BookAndMetaV2> = Vec::with_capacity(book_ids.len());
for book in books.0.iter() { for book in books.0.iter() {
let bauthors: Vec<book_author::Model> = book.find_related(book_author::Entity).all(db).await?; let bauthors: Vec<book_author::Model> =
let bpersons: Vec<book_person::Model> = book.find_related(book_person::Entity).all(db).await?; book.find_related(book_author::Entity).all(db).await?;
let bplaces: Vec<book_place::Model> = book.find_related(book_place::Entity).all(db).await?; let bpersons: Vec<book_person::Model> =
let bsubjects: Vec<book_subject::Model> = book.find_related(book_subject::Entity).all(db).await?; book.find_related(book_person::Entity).all(db).await?;
let btimes: Vec<book_time::Model> = book.find_related(book_time::Entity).all(db).await?; let bplaces: Vec<book_place::Model> =
let bisbns: Vec<book_isbn::Model> = book.find_related(book_isbn::Entity).all(db).await?; 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 { let bookandmeta = BookAndMetaV2 {
book: (book.clone()), book: (book.clone()),
@@ -102,14 +121,11 @@ pub async fn find_books_plus_meta_in_page(
places: bplaces, places: bplaces,
subjects: bsubjects, subjects: bsubjects,
times: btimes, times: btimes,
isbns: bisbns isbns: bisbns,
}; };
resbooks.push(bookandmeta); 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::async_trait;
use axum_login::{secrecy::SecretVec, AuthUser, UserStore}; use axum_login::{secrecy::SecretVec, AuthUser, UserStore};
use crate::Query; use sea_orm::*;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AxumUser { pub struct AxumUser {
@@ -16,7 +15,7 @@ type Result<T = ()> = std::result::Result<T, eyre::Error>;
impl<Role> AuthUser<Role> for AxumUser impl<Role> AuthUser<Role> for AxumUser
where where
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static, Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
{ {
fn get_id(&self) -> String { fn get_id(&self) -> String {
format!("{}", self.id) format!("{}", self.id)
@@ -41,7 +40,7 @@ impl AxumUserStore {
#[async_trait] #[async_trait]
impl<Role> UserStore<Role> for AxumUserStore impl<Role> UserStore<Role> for AxumUserStore
where where
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static, Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
{ {
type User = AxumUser; 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::client::*;
use meilisearch_sdk::search::*; use meilisearch_sdk::search::*;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Debug, Clone)] #[derive(Deserialize, Serialize, Debug, Clone)]
pub struct BookMeili { pub struct BookMeili {
@@ -27,33 +27,35 @@ pub struct BookMeili {
pub async fn create_or_update_book(book: BookMeili, userid: i32, client: &Client) { pub async fn create_or_update_book(book: BookMeili, userid: i32, client: &Client) {
// An index is where the documents are stored. // 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. // 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(&[ books.add_or_replace(&[book], Some("id")).await.unwrap();
book
], Some("id")).await.unwrap();
} }
pub async fn delete_book(bookid: i32, userid: i32, client: &Client) { pub async fn delete_book(bookid: i32, userid: i32, client: &Client) {
// An index is where the documents are stored. // 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(); books.delete_document(bookid).await.unwrap();
} }
pub async fn search_book(
pub async fn search_book(search: &str, page: usize, userid: i32, client: &Client) -> Result<(Vec<BookMeili>, usize), meilisearch_sdk::errors::Error> { search: &str,
page: usize,
userid: i32,
client: &Client,
) -> Result<(Vec<BookMeili>, usize), meilisearch_sdk::errors::Error> {
// An index is where the documents are stored. // An index is where the documents are stored.
let books = client.index(format!("books{}",userid)); let books = client.index(format!("books{}", userid));
let results : SearchResults<BookMeili> = books.search().with_query(search).with_offset((page-1)*12) let results: SearchResults<BookMeili> = books
.execute::<BookMeili>().await.unwrap(); .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(); let formatted_results: Vec<BookMeili> =
(results.hits).iter().map(|r| r.result.clone()).collect();
//.iter()s.map(|r| r.formatted_result.unwrap()).collect(); //.iter()s.map(|r| r.formatted_result.unwrap()).collect();
return Ok((formatted_results, results.estimated_total_hits)); return Ok((formatted_results, results.estimated_total_hits));
} }

View File

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

File diff suppressed because it is too large Load Diff