Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authorizations check #8

Merged
merged 4 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

50 changes: 34 additions & 16 deletions src/cmd_authentication.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use std::sync::Arc;

use crate::{commands::RESTRICTED_COMMANDS, config::config, HandlerResult};
use sqlx::SqlitePool;
use std::sync::Arc;
use teloxide::{requests::Requester, types::Message, Bot};

use crate::{config::config, HandlerResult};


pub async fn authenticate(
bot: Bot,
msg: Message,
Expand Down Expand Up @@ -52,7 +49,12 @@ pub async fn admin_list(bot: Bot, msg: Message, db: Arc<SqlitePool>) -> HandlerR
Ok(())
}

pub async fn admin_remove(bot: Bot, msg: Message, name: String, db: Arc<SqlitePool>) -> HandlerResult {
pub async fn admin_remove(
bot: Bot,
msg: Message,
name: String,
db: Arc<SqlitePool>,
) -> HandlerResult {
let mut tx = db.begin().await?;

if sqlx::query!("SELECT COUNT(*) AS count FROM admins WHERE name = $1", name)
Expand All @@ -77,10 +79,22 @@ pub async fn admin_remove(bot: Bot, msg: Message, name: String, db: Arc<SqlitePo
Ok(())
}

pub async fn authorize(bot: Bot, msg: Message, command: String, db: Arc<SqlitePool>) -> HandlerResult {
pub async fn authorize(
bot: Bot,
msg: Message,
command: String,
db: Arc<SqlitePool>,
) -> HandlerResult {
let mut tx = db.begin().await?;

let chat_id_str = msg.chat.id.to_string();

if !RESTRICTED_COMMANDS.iter().any(|c| c.shortand() == command) {
bot.send_message(msg.chat.id, "Cette commande n'existe pas")
.await?;
return Ok(());
}

let already_authorized = sqlx::query!(
r#"SELECT COUNT(*) AS count FROM authorizations WHERE chat_id = $1 AND command = $2"#,
chat_id_str,
Expand All @@ -89,7 +103,7 @@ pub async fn authorize(bot: Bot, msg: Message, command: String, db: Arc<SqlitePo
.fetch_one(tx.as_mut())
.await?;

if already_authorized.count == 0 {
if already_authorized.count > 0 {
sqlx::query!(
r#"INSERT INTO authorizations(command, chat_id) VALUES($1, $2)"#,
command,
Expand Down Expand Up @@ -160,14 +174,18 @@ pub async fn authorizations(bot: Bot, msg: Message, db: Arc<SqlitePool>) -> Hand

bot.send_message(
msg.chat.id,
format!(
"Ce groupe peut utiliser les commandes suivantes:\n{}",
authorizations
.into_iter()
.map(|s| format!(" - {}", s.command))
.collect::<Vec<_>>()
.join("\n")
),
if authorizations.is_empty() {
"Ce groupe ne peut utiliser aucune commande".to_owned()
} else {
format!(
"Ce groupe peut utiliser les commandes suivantes:\n{}",
authorizations
.into_iter()
.map(|s| format!(" - {}", s.command))
.collect::<Vec<_>>()
.join("\n")
)
},
)
.await?;

Expand Down
2 changes: 1 addition & 1 deletion src/cmd_bureau.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ pub async fn bureau(bot: Bot, msg: Message) -> HandlerResult {
.is_anonymous(false)
.await?;
Ok(())
}
}
11 changes: 3 additions & 8 deletions src/cmd_poll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ use teloxide::{
prelude::Dialogue,
requests::Requester,
types::{
CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, MessageId,
ReplyMarkup,
CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, Message, MessageId, ReplyMarkup,
},
Bot,
};
Expand All @@ -36,11 +35,7 @@ pub enum PollState {
pub type PollDialogue = Dialogue<PollState, InMemStorage<PollState>>;

/// Starts the /poll dialogue by sending a message with an inline keyboard to select the target of the /poll.
pub async fn start_poll_dialogue(
bot: Bot,
msg: Message,
dialogue: PollDialogue,
) -> HandlerResult {
pub async fn start_poll_dialogue(bot: Bot, msg: Message, dialogue: PollDialogue) -> HandlerResult {
log::info!("Starting /poll dialogue");

log::debug!("Removing /poll message");
Expand Down Expand Up @@ -207,4 +202,4 @@ pub async fn stats(bot: Bot, msg: Message) -> HandlerResult {
.await?;

Ok(())
}
}
16 changes: 10 additions & 6 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ use std::sync::Arc;

use sqlx::SqlitePool;
use teloxide::{
dispatching::DpHandlerDescription,
prelude::*,
types::{Message, MessageCommon, MessageKind},
utils::command::BotCommands,
Bot,
dispatching::DpHandlerDescription, prelude::*, types::Message, utils::command::BotCommands, Bot,
};

use crate::{
Expand Down Expand Up @@ -68,7 +64,7 @@ fn require_authorization() -> Endpoint<'static, DependencyMap, HandlerResult, Dp
|command: Command, msg: Message, pool: Arc<SqlitePool>| async move {
let chat_id = msg.chat.id.to_string();
let shortand = command.shortand();
match sqlx::query!(
let authorized = match sqlx::query!(
r#"SELECT COUNT(*) AS count FROM authorizations WHERE chat_id = $1 AND command = $2"#,
chat_id,
shortand
Expand All @@ -80,7 +76,13 @@ fn require_authorization() -> Endpoint<'static, DependencyMap, HandlerResult, Dp
log::error!("Could not check authorization in database: {:?}", e);
false
},
};

if !authorized {
log::warn!("Chat {} tried to use the commmand {}", msg.chat.id, command.shortand())
}

authorized
},
)
}
Expand Down Expand Up @@ -141,6 +143,8 @@ pub enum Command {
Stats,
}

pub const RESTRICTED_COMMANDS: [Command; 3] = [Command::Bureau, Command::Poll, Command::Stats];

impl Command {
// Used as key for the access control map
pub fn shortand(&self) -> &str {
Expand Down
11 changes: 6 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@ use teloxide::{
};

use crate::{
cmd_poll::PollState,
commands::{command_callback_query_handler, command_message_handler, Command},
directus::{update_committee, Committee},
cmd_poll::PollState
};

mod cmd_authentication;
mod cmd_bureau;
mod cmd_poll;
mod commands;
mod config;
mod directus;
mod cmd_poll;
mod cmd_bureau;
mod cmd_authentication;

pub type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;

Expand Down Expand Up @@ -47,7 +47,8 @@ async fn main() {
id: 1,
name: "".into(),
poll_count: 15,
}]).await;
}])
.await;

log::info!("Loading config files");
config::config();
Expand Down
Loading