Compare commits

..

13 Commits

Author SHA1 Message Date
e53e19cc3e Friend List Styling 2024-12-07 02:56:16 +00:00
49cfbff578 Organization and Friend Requests Page 2024-12-07 01:34:12 +00:00
2391016709 API Endpoints for managing friend requests, and a LOT of trait bound debugging... 2024-12-01 22:56:50 +00:00
0ad9383a08 Friend Page & Components 2024-11-29 23:37:16 +00:00
aa9001e7d1 UserRow and deliberately structuring API query output 2024-11-29 22:40:50 +00:00
25391863f6 Database Query and API Endpoint for User Friends 2024-11-29 21:08:50 +00:00
aaa9db93fb Merge pull request 'Require login to fetch audio and image assets' (#160) from 110-require-login-to-fetch-audio-and into main
Reviewed-on: LibreTunes/LibreTunes#160
2024-11-24 21:35:41 +00:00
fac33bb1f1 Merge pull request 'Add environment variable to disable signup' (#159) from 157-add-environment-variable-to-disable-signup into main
Reviewed-on: LibreTunes/LibreTunes#159
2024-11-24 21:34:32 +00:00
97f50b38c5 Add example usage of LIBRETUNES_DISABLE_SIGNUP env var 2024-11-24 14:37:10 -05:00
5ecb71ce9d Return error on /api/signup if signup disabled 2024-11-24 14:36:56 -05:00
d1c8615105 Add router layer to require authentication 2024-11-24 14:28:06 -05:00
6592d66f87 Merge pull request 'Fixed casing warning' (#158) from 155-fix-dockerfile-fromas-casing-warning into main
Reviewed-on: LibreTunes/LibreTunes#158
2024-11-24 19:04:06 +00:00
51a9e8c4b3 Fixed casing warning 2024-11-24 04:29:53 +00:00
19 changed files with 554 additions and 17 deletions

View File

@ -18,3 +18,4 @@ DATABASE_URL=postgresql://libretunes:password@localhost:5432/libretunes
LIBRETUNES_AUDIO_PATH=assets/audio LIBRETUNES_AUDIO_PATH=assets/audio
LIBRETUNES_IMAGE_PATH=assets/images LIBRETUNES_IMAGE_PATH=assets/images
LIBRETUNES_DISABLE_SIGNUP=true

View File

@ -1,4 +1,4 @@
FROM rust:slim as builder FROM rust:slim AS builder
WORKDIR /app WORKDIR /app

View File

@ -15,6 +15,7 @@ services:
POSTGRES_DB: ${POSTGRES_DB} POSTGRES_DB: ${POSTGRES_DB}
LIBRETUNES_AUDIO_PATH: /assets/audio LIBRETUNES_AUDIO_PATH: /assets/audio
LIBRETUNES_IMAGE_PATH: /assets/images LIBRETUNES_IMAGE_PATH: /assets/images
LIBRETUNES_DISABLE_SIGNUP: "true"
volumes: volumes:
- libretunes-audio:/assets/audio - libretunes-audio:/assets/audio
- libretunes-images:/assets/images - libretunes-images:/assets/images

227
src/api/friends.rs Normal file
View File

@ -0,0 +1,227 @@
use leptos::*;
use cfg_if::cfg_if;
use crate::frienddata::FriendData;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::auth::get_user;
use server_fn::error::NoCustomError;
use crate::database::get_db_conn;
use diesel::prelude::*;
use diesel::dsl::exists;
use crate::models::*;
use crate::schema::*;
use chrono::prelude::*;
}
}
/// Get a user's list of friends from the database
#[server(endpoint = "/profile/friends")]
pub async fn friends(for_user_id: i32)
-> Result<Vec<FriendData>, ServerFnError>
{
let mut db_con = get_db_conn();
let friends = friendships::table
.filter(friendships::friend_1_id.eq(for_user_id))
.filter(friendships::friend_1_id.ne(friendships::friend_2_id))
.inner_join(users::table.on(users::id.eq(friendships::friend_2_id)))
.select((users::all_columns, friendships::created_at))
.order(friendships::created_at.desc())
.order(users::username.asc())
.union(
friendships::table
.filter(friendships::friend_2_id.eq(for_user_id))
.filter(friendships::friend_1_id.ne(friendships::friend_2_id))
.inner_join(users::table.on(users::id.eq(friendships::friend_1_id)))
.select((users::all_columns, friendships::created_at))
.order(friendships::created_at.desc())
.order(users::username.asc())
)
.load(&mut db_con)?;
let friend_list: Vec<FriendData> = friends.into_iter().map(|(user, created_at): (User, NaiveDateTime)| {
FriendData {
username: user.username,
created_at: created_at.into(),
user_id: user.id.unwrap()
}
}).collect();
Ok(friend_list)
}
/// Get a user's list of friend requests (outgoing) from the database
#[server(endpoint = "/profile/friend-requests-outgoing")]
pub async fn friend_requests_outgoing(for_user_id: i32)
-> Result<Vec<FriendData>, ServerFnError>
{
let mut db_con = get_db_conn();
let friends = friend_requests::table
.filter(friend_requests::from_id.eq(for_user_id))
.filter(friend_requests::from_id.ne(friend_requests::to_id))
.inner_join(users::table.on(users::id.eq(friend_requests::to_id)))
.select((users::all_columns, friend_requests::created_at))
.order(friend_requests::created_at.desc())
.order(users::username.asc())
.load(&mut db_con)?;
let friend_list: Vec<FriendData> = friends.into_iter().map(|(user, created_at): (User, NaiveDateTime)| {
FriendData {
username: user.username,
created_at: created_at.into(),
user_id: user.id.unwrap()
}
}).collect();
Ok(friend_list)
}
/// Get a user's list of friend requests (incoming) from the database
#[server(endpoint = "/profile/friend-requests-incoming")]
pub async fn friend_requests_incoming(for_user_id: i32)
-> Result<Vec<FriendData>, ServerFnError>
{
let mut db_con = get_db_conn();
let friends = friend_requests::table
.filter(friend_requests::to_id.eq(for_user_id))
.filter(friend_requests::from_id.ne(friend_requests::to_id))
.inner_join(users::table.on(users::id.eq(friend_requests::from_id)))
.select((users::all_columns, friend_requests::created_at))
.order(friend_requests::created_at.desc())
.order(users::username.asc())
.load(&mut db_con)?;
let friend_list: Vec<FriendData> = friends.into_iter().map(|(user, created_at): (User, NaiveDateTime)| {
FriendData {
username: user.username,
created_at: created_at.into(),
user_id: user.id.unwrap()
}
}).collect();
Ok(friend_list)
}
/// Send a friend request
#[server(endpoint = "/profile/send-friend-request")]
pub async fn send_friend_request(to_user_id: i32)
-> Result<(), ServerFnError>
{
let mut db_con = get_db_conn();
// Get user id from session
let user = get_user().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user: {}", e)))?;
// Get current time for request
let timestamp: NaiveDateTime = Utc::now().naive_utc();
// Insert into database (if already exists, won't succeed due to primary key)
diesel::insert_into(crate::schema::friend_requests::table)
.values((friend_requests::created_at.eq(timestamp),friend_requests::from_id.eq(user.id.unwrap()),friend_requests::to_id.eq(to_user_id)))
.execute(&mut db_con)
.map_err(|e| {
let msg = format!("Error saving friend request to database: {}", e);
ServerFnError::<NoCustomError>::ServerError(msg)
})?;
Ok(())
}
/// Remove an outgoing friend request
#[server(endpoint = "/profile/friend-requests-incoming")]
pub async fn delete_friend_request(to_user_id: i32)
-> Result<(), ServerFnError>
{
let mut db_con = get_db_conn();
// Get user id from session
let user = get_user().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user: {}", e)))?;
// Delete the friend request
diesel::delete(friend_requests::table
.filter(friend_requests::from_id.eq(user.id.unwrap()))
.filter(friend_requests::to_id.eq(to_user_id))
).execute(&mut db_con)?;
Ok(())
}
/// Remove an existing friendship
#[server(endpoint = "/profile/delete-friend")]
pub async fn delete_friend(for_user_id: i32)
-> Result<(), ServerFnError>
{
let mut db_con = get_db_conn();
// Get user id from session
let user = get_user().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user: {}", e)))?;
// Delete the friend request
diesel::delete(friendships::table
.filter(friendships::friend_1_id.eq(user.id.unwrap()))
.filter(friendships::friend_2_id.eq(for_user_id))
).execute(&mut db_con)?;
diesel::delete(friendships::table
.filter(friendships::friend_2_id.eq(user.id.unwrap()))
.filter(friendships::friend_1_id.eq(for_user_id))
).execute(&mut db_con)?;
Ok(())
}
/// Accept a friend request
#[server(endpoint = "/profile/accept-friend-request")]
pub async fn accept_friend_request(to_user_id: i32)
-> Result<(), ServerFnError>
{
let mut db_con = get_db_conn();
// Get user id from session
let user = get_user().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user: {}", e)))?;
// Get current time for request
let timestamp: NaiveDateTime = Utc::now().naive_utc();
// Make sure the person has received a friend request from the other person
let req = diesel::select(exists(
friend_requests::table
.filter(friend_requests::from_id.eq(user.id.unwrap()))
.filter(friend_requests::to_id.eq(to_user_id))
)).get_result::<bool>(&mut db_con)?;
if req == false {
Err(ServerFnError::<NoCustomError>::ServerError(format!("Error, the friend request does not exist!")))?;
}
// Delete the friend requests
diesel::delete(friend_requests::table
.filter(friend_requests::from_id.eq(user.id.unwrap()))
.filter(friend_requests::to_id.eq(to_user_id))
).execute(&mut db_con)?;
diesel::delete(friend_requests::table
.filter(friend_requests::to_id.eq(user.id.unwrap()))
.filter(friend_requests::from_id.eq(to_user_id))
).execute(&mut db_con)?;
// Add the new friend request either direction
diesel::insert_into(crate::schema::friendships::table)
.values((friendships::created_at.eq(timestamp),friendships::friend_1_id.eq(user.id.unwrap()),friendships::friend_2_id.eq(to_user_id)))
.execute(&mut db_con)
.map_err(|e| {
let msg = format!("Error saving friendship to database: {}", e);
ServerFnError::<NoCustomError>::ServerError(msg)
})?;
Ok(())
}

View File

@ -2,3 +2,4 @@ pub mod history;
pub mod profile; pub mod profile;
pub mod songs; pub mod songs;
pub mod album; pub mod album;
pub mod friends;

View File

@ -8,6 +8,7 @@ use crate::pages::login::*;
use crate::pages::signup::*; use crate::pages::signup::*;
use crate::pages::profile::*; use crate::pages::profile::*;
use crate::pages::albumpage::*; use crate::pages::albumpage::*;
use crate::pages::friends::*;
use crate::error_template::{AppError, ErrorTemplate}; use crate::error_template::{AppError, ErrorTemplate};
use crate::util::state::GlobalState; use crate::util::state::GlobalState;
@ -45,6 +46,8 @@ pub fn App() -> impl IntoView {
<Route path="search" view=Search /> <Route path="search" view=Search />
<Route path="user/:id" view=Profile /> <Route path="user/:id" view=Profile />
<Route path="user" view=Profile /> <Route path="user" view=Profile />
<Route path="user/:id/friends" view=Friends />
<Route path="user/:id/friendrequests" view=FriendRequests />
<Route path="album/:id" view=AlbumPage /> <Route path="album/:id" view=AlbumPage />
</Route> </Route>
<Route path="/login" view=Login /> <Route path="/login" view=Login />

View File

@ -19,6 +19,11 @@ use crate::users::UserCredentials;
/// Returns a Result with the error message if the user could not be created /// Returns a Result with the error message if the user could not be created
#[server(endpoint = "signup")] #[server(endpoint = "signup")]
pub async fn signup(new_user: User) -> Result<(), ServerFnError> { pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
// Check LIBRETUNES_DISABLE_SIGNUP env var
if std::env::var("LIBRETUNES_DISABLE_SIGNUP").is_ok_and(|v| v == "true") {
return Err(ServerFnError::<NoCustomError>::ServerError("Signup is disabled".to_string()));
}
use crate::users::create_user; use crate::users::create_user;
// Ensure the user has no id, and is not a self-proclaimed admin // Ensure the user has no id, and is not a self-proclaimed admin

View File

@ -9,3 +9,4 @@ pub mod song_list;
pub mod loading; pub mod loading;
pub mod error; pub mod error;
pub mod album_info; pub mod album_info;
pub mod friend_list;

View File

@ -0,0 +1,37 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::frienddata::FriendData;
#[component]
pub fn FriendRow(user: FriendData) -> impl IntoView {
view! {
<div class="friend-row">
<div class="friend-info">
<div class="friend-item">
<Suspense fallback=|| view! { <Icon class="friend-image" icon=icondata::CgProfile/> }>
<img class="friend-image" src={format!("/assets/images/profile/{}.webp", user.user_id)} alt="Profile Photo" />
</Suspense>
</div>
<a class="friend-item" href={format!("../../user/{}",user.user_id)}>{user.username}</a>
</div>
<p class="friend-created-date">{user.created_at.format("%m/%d/%Y").to_string()}</p>
</div>
}.into_view()
}
#[component]
pub fn FriendList(friends: Vec<FriendData>) -> impl IntoView {
view! {
<div class="friend-container">
{
friends.iter().map(|friend| {
view! {
<FriendRow user={friend.clone()} />
}
}).collect::<Vec<_>>()
}
</div>
}.into_view()
}

17
src/frienddata.rs Normal file
View File

@ -0,0 +1,17 @@
use serde::{Serialize, Deserialize};
use chrono::NaiveDate;
/// Holds information about a user (friend)
///
/// Intended to be used in the front-end
#[derive(Serialize, Deserialize, Clone)]
pub struct FriendData {
/// Username
pub username: String,
/// Date which the user/friend was added
pub created_at: NaiveDate,
/// User's id to be used to locate their profile image
pub user_id: i32
}

View File

@ -3,6 +3,7 @@ pub mod auth;
pub mod songdata; pub mod songdata;
pub mod albumdata; pub mod albumdata;
pub mod artistdata; pub mod artistdata;
pub mod frienddata;
pub mod playstatus; pub mod playstatus;
pub mod playbar; pub mod playbar;
pub mod database; pub mod database;

View File

@ -14,10 +14,11 @@ extern crate diesel_migrations;
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
use axum::{routing::get, Router, extract::Path}; use axum::{routing::get, Router, extract::Path, middleware::from_fn};
use leptos::*; use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes}; use leptos_axum::{generate_route_list, LeptosRoutes};
use libretunes::app::*; use libretunes::app::*;
use libretunes::util::require_auth::require_auth_middleware;
use libretunes::fileserv::{file_and_error_handler, get_asset_file, get_static_file, AssetType}; use libretunes::fileserv::{file_and_error_handler, get_asset_file, get_static_file, AssetType};
use axum_login::tower_sessions::SessionManagerLayer; use axum_login::tower_sessions::SessionManagerLayer;
use tower_sessions_redis_store::{fred::prelude::*, RedisStore}; use tower_sessions_redis_store::{fred::prelude::*, RedisStore};
@ -63,6 +64,7 @@ async fn main() {
.route("/assets/audio/:song", get(|Path(song) : Path<String>| get_asset_file(song, AssetType::Audio))) .route("/assets/audio/:song", get(|Path(song) : Path<String>| get_asset_file(song, AssetType::Audio)))
.route("/assets/images/:image", get(|Path(image) : Path<String>| get_asset_file(image, AssetType::Image))) .route("/assets/images/:image", get(|Path(image) : Path<String>| get_asset_file(image, AssetType::Image)))
.route("/assets/*uri", get(|uri| get_static_file(uri, ""))) .route("/assets/*uri", get(|uri| get_static_file(uri, "")))
.layer(from_fn(require_auth_middleware))
.layer(auth_layer) .layer(auth_layer)
.fallback(file_and_error_handler) .fallback(file_and_error_handler)
.with_state(leptos_options); .with_state(leptos_options);

View File

@ -2,3 +2,4 @@ pub mod login;
pub mod signup; pub mod signup;
pub mod profile; pub mod profile;
pub mod albumpage; pub mod albumpage;
pub mod friends;

133
src/pages/friends.rs Normal file
View File

@ -0,0 +1,133 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_router::*;
use crate::api::friends::*;
use crate::components::friend_list::*;
use crate::components::loading::Loading;
#[derive(Params, PartialEq)]
struct FriendParams {
id: i32
}
#[component]
pub fn Friends() -> impl IntoView {
let params = use_params::<FriendParams>();
let id = move || {params.with(|params| {
params.as_ref()
.map(|params| params.id)
.map_err(|e| e.clone())
})
};
let friend_list = create_resource(
id,
|value| async move {
match value {
Ok(v) => {friends(v).await},
Err(e) => {Err(ServerFnError::Request(format!("Error getting song data: {}", e).into()))},
}
},
);
view! {
<div class="friend-page-container">
<h1 class="friend-header"> "Friends:" </h1>
<Transition
fallback=move || view! {
<Loading />
}
>
<ErrorBoundary
fallback=|errors| view! {
{move || errors.get()
.into_iter()
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
.collect_view()
}
}
>
{
friend_list.get().map(|friend_list| {
friend_list.map(|friend_list| {
view! {<FriendList friends={friend_list} />}
})
})
}
</ErrorBoundary>
</Transition>
</div>
}
}
#[component]
pub fn FriendRequests() -> impl IntoView {
let params = use_params::<FriendParams>();
let id = move || {params.with(|params| {
params.as_ref()
.map(|params| params.id)
.map_err(|e| e.clone())
})
};
let friend_list_incoming = create_resource(
id,
|value| async move {
match value {
Ok(v) => {friend_requests_incoming(v).await},
Err(e) => {Err(ServerFnError::Request(format!("Error getting song data: {}", e).into()))},
}
},
);
let friend_list_outgoing = create_resource(
id,
|value| async move {
match value {
Ok(v) => {friend_requests_outgoing(v).await},
Err(e) => {Err(ServerFnError::Request(format!("Error getting song data: {}", e).into()))},
}
},
);
view! {
<div class="friend-page-container">
<h1 class="friend-header"> "Friend Requests:" </h1>
<Transition
fallback=move || view! {
<Loading />
}
>
<ErrorBoundary
fallback=|errors| view! {
{move || errors.get()
.into_iter()
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
.collect_view()
}
}
>
<h2>Sent: </h2>
{
friend_list_outgoing.get().map(|friend_list| {
friend_list.map(|friend_list| {
view! {<FriendList friends={friend_list} />}
})
})
}
<h2>Received: </h2>
{
friend_list_incoming.get().map(|friend_list| {
friend_list.map(|friend_list| {
view! {<FriendList friends={friend_list} />}
})
})
}
</ErrorBoundary>
</Transition>
</div>
}
}

View File

@ -16,10 +16,9 @@ pub fn Login() -> impl IntoView {
let loading = create_rw_signal(false); let loading = create_rw_signal(false);
let error_msg = create_rw_signal(None); let error_msg = create_rw_signal(None);
let toggle_password = move |ev: leptos::ev::MouseEvent| { let toggle_password = move |_| {
ev.prevent_default();
set_show_password.update(|show_password| *show_password = !*show_password); set_show_password.update(|show_password| *show_password = !*show_password);
log!("Password visibility toggled"); log!("showing password");
}; };
let on_submit = move |ev: leptos::ev::SubmitEvent| { let on_submit = move |ev: leptos::ev::SubmitEvent| {
@ -95,17 +94,17 @@ pub fn Login() -> impl IntoView {
/> />
<span>Password</span> <span>Password</span>
<i></i> <i></i>
<Show when=move || { show_password() == false } <Show
fallback=move || view! { when=move || {show_password() == false}
<button on:click=toggle_password class="login-password-visibility"> fallback=move || view!{ <button on:click=toggle_password class="login-password-visibility">
<Icon icon=icondata::AiEyeInvisibleFilled /> <Icon icon=icondata::AiEyeInvisibleFilled />
</button> </button> /> }
}
> >
<button on:click=toggle_password class="login-password-visibility"> <button on:click=toggle_password class="login-password-visibility">
<Icon icon=icondata::AiEyeFilled /> <Icon icon=icondata::AiEyeFilled />
</button> </button>
</Show>
</Show>
</div> </div>
<a href="" class="forgot-pw">Forgot Password?</a> <a href="" class="forgot-pw">Forgot Password?</a>
<div class="error-msg" >{ move || error_msg.get() }</div> <div class="error-msg" >{ move || error_msg.get() }</div>

View File

@ -3,6 +3,7 @@ use cfg_if::cfg_if;
cfg_if! { cfg_if! {
if #[cfg(feature = "ssr")] { if #[cfg(feature = "ssr")] {
pub mod audio; pub mod audio;
pub mod require_auth;
} }
} }

46
src/util/require_auth.rs Normal file
View File

@ -0,0 +1,46 @@
use axum::extract::Request;
use axum::response::Response;
use axum::body::Body;
use axum::middleware::Next;
use axum_login::AuthSession;
use http::StatusCode;
use crate::auth_backend::AuthBackend;
use axum::extract::FromRequestParts;
// Things in pkg/ are allowed automatically. This includes the CSS/JS/WASM files
const ALLOWED_PATHS: [&str; 5] = ["/login", "/signup", "/api/login", "/api/signup", "/favicon.ico"];
/**
* Middleware to require authentication for all paths except those in ALLOWED_PATHS
*
* If a user is not authenticated, they will be redirected to the login page
*/
pub async fn require_auth_middleware(req: Request, next: Next) -> Result<Response<Body>, (StatusCode, &'static str)> {
let path = req.uri().path();
if !ALLOWED_PATHS.iter().any(|&x| x == path) {
let (mut parts, body) = req.into_parts();
let auth_session = AuthSession::<AuthBackend>::from_request_parts(&mut parts, &())
.await?;
if auth_session.user.is_none() {
let response = Response::builder()
.status(StatusCode::TEMPORARY_REDIRECT)
.header("Location", "/login")
.body(Body::empty())
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Failed to build response"))?;
return Ok(response);
}
let req = Request::from_parts(parts, body);
let response = next.run(req).await;
Ok(response)
} else {
let response = next.run(req).await;
Ok(response)
}
}

60
style/friend.scss Normal file
View File

@ -0,0 +1,60 @@
@import 'theme.scss';
.friend-page-container {
width: 100%;
}
.friend-container {
width: 100%;
border-collapse: collapse;
.friend-row {
border: solid;
border-width: 1px 0;
border-color: #303030;
position: relative;
min-width: 100%;
height: 50px;
display: flex;
flex-flow: row nowrap;
justify-content: space-between;
align-items: center;
.friend-info {
display: flex;
flex-flow: row nowrap;
}
.friend-item {
max-width: max-content;
margin: 0 20px;
.friend-image {
width: 35px;
height: 35px;
border-radius: 50%;
}
}
.friend-created-date {
margin-right: 50px;
}
a {
color: $text-controls-color;
}
a:visited {
color: $text-controls-color;
}
a:hover {
color: $controls-hover-color;
}
a:active {
color: $controls-click-color;
}
}
}

View File

@ -16,6 +16,7 @@
@import 'profile.scss'; @import 'profile.scss';
@import 'loading.scss'; @import 'loading.scss';
@import 'album_page.scss'; @import 'album_page.scss';
@import 'friend.scss';
body { body {
font-family: sans-serif; font-family: sans-serif;