Can join a family
This commit is contained in:
		@@ -1,7 +1,9 @@
 | 
			
		||||
use crate::constants::StaticConstraints;
 | 
			
		||||
use crate::controllers::HttpResult;
 | 
			
		||||
use crate::services::families_service;
 | 
			
		||||
use crate::services::login_token_service::LoginToken;
 | 
			
		||||
use crate::services::rate_limiter_service::RatedAction;
 | 
			
		||||
use crate::services::{families_service, rate_limiter_service};
 | 
			
		||||
use actix_remote_ip::RemoteIP;
 | 
			
		||||
use actix_web::{web, HttpResponse};
 | 
			
		||||
 | 
			
		||||
#[derive(Debug, serde::Deserialize)]
 | 
			
		||||
@@ -22,3 +24,42 @@ pub async fn create(req: web::Json<CreateFamilyReq>, token: LoginToken) -> HttpR
 | 
			
		||||
 | 
			
		||||
    Ok(HttpResponse::Created().json(family))
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#[derive(Debug, serde::Deserialize)]
 | 
			
		||||
pub struct JoinFamilyReq {
 | 
			
		||||
    code: String,
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/// Join a family
 | 
			
		||||
pub async fn join(
 | 
			
		||||
    remote_ip: RemoteIP,
 | 
			
		||||
    req: web::Json<JoinFamilyReq>,
 | 
			
		||||
    token: LoginToken,
 | 
			
		||||
) -> HttpResult {
 | 
			
		||||
    // Rate limiting
 | 
			
		||||
    if rate_limiter_service::should_block_action(remote_ip.0, RatedAction::JoinFamily).await? {
 | 
			
		||||
        return Ok(HttpResponse::TooManyRequests().finish());
 | 
			
		||||
    }
 | 
			
		||||
    rate_limiter_service::record_action(remote_ip.0, RatedAction::JoinFamily).await?;
 | 
			
		||||
 | 
			
		||||
    let family = match families_service::get_by_invitation_code(&req.code).await {
 | 
			
		||||
        Ok(f) => f,
 | 
			
		||||
        Err(e) => {
 | 
			
		||||
            log::error!("Could not find family by invitation code! {e}");
 | 
			
		||||
            return Ok(HttpResponse::NotFound().finish());
 | 
			
		||||
        }
 | 
			
		||||
    };
 | 
			
		||||
 | 
			
		||||
    if families_service::is_member(family.id(), token.user_id).await? {
 | 
			
		||||
        log::error!(
 | 
			
		||||
            "Could not add {:?} to family {:?} because it is already a member of the family!",
 | 
			
		||||
            token.user_id,
 | 
			
		||||
            family.id()
 | 
			
		||||
        );
 | 
			
		||||
        return Ok(HttpResponse::Conflict().finish());
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    families_service::add_member(family.id(), token.user_id, false).await?;
 | 
			
		||||
 | 
			
		||||
    Ok(HttpResponse::Accepted().finish())
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user