Compare commits

...

8 Commits

Author SHA1 Message Date
bfee85a963 Merge pull request 'send-blogpost-notification' (#680) from send-blogpost-notification into main
All checks were successful
CI/CD Pipeline / test (push) Successful in 9m1s
CI/CD Pipeline / deploy-staging (push) Has been skipped
CI/CD Pipeline / deploy-main (push) Successful in 7m21s
Reviewed-on: #680
2024-08-18 22:24:14 +02:00
c68593a67d proper docs; Fixes #645
Some checks failed
CI/CD Pipeline / deploy-staging (push) Has been cancelled
CI/CD Pipeline / deploy-main (push) Has been cancelled
CI/CD Pipeline / test (push) Has been cancelled
2024-08-18 22:23:08 +02:00
20da86f69e delete notification again, if article is unpublished
Some checks failed
CI/CD Pipeline / deploy-staging (push) Blocked by required conditions
CI/CD Pipeline / deploy-main (push) Blocked by required conditions
CI/CD Pipeline / test (push) Has been cancelled
2024-08-18 22:21:36 +02:00
8efb3aea2c push
Some checks failed
CI/CD Pipeline / deploy-staging (push) Has been cancelled
CI/CD Pipeline / test (push) Has been cancelled
CI/CD Pipeline / deploy-main (push) Has been cancelled
2024-08-18 21:57:20 +02:00
83aa9bc84c allow for article_titles 2024-08-18 21:46:11 +02:00
6171bb0f85 comment wordpress changes 2024-08-18 21:37:53 +02:00
eeab4c167b switch to new pw 2024-08-18 21:32:34 +02:00
25161fc8e9 first draft of sending blog post notifications
Some checks failed
CI/CD Pipeline / deploy-staging (push) Has been cancelled
CI/CD Pipeline / deploy-main (push) Has been cancelled
CI/CD Pipeline / test (push) Has been cancelled
2024-08-18 21:30:14 +02:00
8 changed files with 233 additions and 73 deletions

1
Cargo.lock generated
View File

@ -2271,6 +2271,7 @@ dependencies = [
"sqlx", "sqlx",
"tera", "tera",
"ureq", "ureq",
"urlencoding",
] ]
[[package]] [[package]]

View File

@ -28,6 +28,7 @@ itertools = "0.13"
job_scheduler_ng = "2.0" job_scheduler_ng = "2.0"
ureq = { version = "2.9", features = ["json"] } ureq = { version = "2.9", features = ["json"] }
regex = "1.10" regex = "1.10"
urlencoding = "2.1"
[target.'cfg(not(windows))'.dependencies] [target.'cfg(not(windows))'.dependencies]
openssl = { version = "0.10", features = [ "vendored" ] } openssl = { version = "0.10", features = [ "vendored" ] }

View File

@ -5,3 +5,4 @@ limits = { file = "10 MiB", data-form = "10 MiB"}
smtp_pw = "8kIjlLH79Ky6D3jQ" smtp_pw = "8kIjlLH79Ky6D3jQ"
usage_log_path = "./usage.txt" usage_log_path = "./usage.txt"
openweathermap_key = "c8dab8f91b5b815d76e9879cbaecd8d5" openweathermap_key = "c8dab8f91b5b815d76e9879cbaecd8d5"
wordpress_key = "pw-to-allow-sending-notifications"

View File

@ -1,73 +0,0 @@
# Wordpress auth
Add the following code to `wp-content/themes/bravada/functions.php`:
```
function rot_auth( $user, $username, $password ){
// Make sure a username and password are present for us to work with
if($username == '' || $password == '') return;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://app.rudernlinz.at/wikiauth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "name=$username&password=$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the cURL session and get the response
$response = curl_exec($ch);
// Check for cURL errors
if(curl_errno($ch)){
$user = new WP_Error( 'denied', __('Curl error: ' . curl_error($ch)) );
}
// Close the cURL session
curl_close($ch);
if (strpos($response, 'SUCC') !== false) {
$user = get_user_by('login', $username);
if (!$user) {
// User does not exist, create a new one
$userdata = array(
'user_email' => $username,
'user_login' => $username,
'first_name' => $username,
'last_name' => ''
);
$new_user_id = wp_insert_user($userdata);
if (!is_wp_error($new_user_id)) {
// Load the new user info
$user = new WP_User($new_user_id);
// Set role based on username
if ($username == 'Philipp Hofer' || $username == 'Marie Birner') {
$user->set_role('administrator');
} else {
$user->set_role('editor');
}
} else {
// Handle error in user creation
return $new_user_id;
}
} else {
}
} else {
$user = new WP_Error( 'denied', __("Falscher Benutzername/Passwort. Verwendest du deine Accountdaten vom Ruderassistenten?") );
}
return $user;
}
// Comment this line if you wish to fall back on WordPress authentication
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);
add_filter( 'authenticate', 'rot_auth', 10, 3 );
```

View File

@ -179,6 +179,13 @@ ORDER BY read_at DESC, created_at DESC;
.await .await
.unwrap(); .unwrap();
} }
pub(crate) async fn delete_by_link(db: &sqlx::Pool<Sqlite>, link: &str) {
sqlx::query!("DELETE FROM notification WHERE link=?", link)
.execute(db)
.await
.unwrap();
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -118,6 +118,56 @@ fn unauthorized_error(req: &Request) -> Redirect {
Redirect::to("/auth") Redirect::to("/auth")
} }
#[derive(FromForm, Debug)]
struct NewBlogpostForm<'r> {
article_url: &'r str,
article_title: &'r str,
pw: &'r str,
}
#[post("/", data = "<blogpost>")]
async fn new_blogpost(
db: &State<SqlitePool>,
blogpost: Form<NewBlogpostForm<'_>>,
config: &State<Config>,
) -> String {
if blogpost.pw == &config.wordpress_key {
let member = Role::find_by_name(&db, "Donau Linz").await.unwrap();
Notification::create_for_role(
db,
&member,
&urlencoding::decode(blogpost.article_title).expect("UTF-8"),
&format!("Neuer Blogpost"),
Some(blogpost.article_url),
None,
)
.await;
"ACK".into()
} else {
"WRONG pw".into()
}
}
#[derive(FromForm, Debug)]
struct BlogpostUnpublishedForm<'r> {
article_url: &'r str,
pw: &'r str,
}
#[post("/", data = "<blogpost>")]
async fn blogpost_unpublished(
db: &State<SqlitePool>,
blogpost: Form<BlogpostUnpublishedForm<'_>>,
config: &State<Config>,
) -> String {
if blogpost.pw == &config.wordpress_key {
Notification::delete_by_link(&db, blogpost.article_url).await;
"ACK".into()
} else {
"WRONG pw".into()
}
}
#[catch(403)] //forbidden #[catch(403)] //forbidden
fn forbidden_error() -> Flash<Redirect> { fn forbidden_error() -> Flash<Redirect> {
Flash::error(Redirect::to("/"), "Keine Berechtigung für diese Aktion. Wenn du der Meinung bist, dass du das machen darfst, melde dich bitte bei it@rudernlinz.at.") Flash::error(Redirect::to("/"), "Keine Berechtigung für diese Aktion. Wenn du der Meinung bist, dass du das machen darfst, melde dich bitte bei it@rudernlinz.at.")
@ -187,6 +237,7 @@ pub struct Config {
smtp_pw: String, smtp_pw: String,
usage_log_path: String, usage_log_path: String,
pub openweathermap_key: String, pub openweathermap_key: String,
wordpress_key: String,
} }
pub fn config(rocket: Rocket<Build>) -> Rocket<Build> { pub fn config(rocket: Rocket<Build>) -> Rocket<Build> {
@ -194,6 +245,8 @@ pub fn config(rocket: Rocket<Build>) -> Rocket<Build> {
.mount("/", routes![index, steering, impressum]) .mount("/", routes![index, steering, impressum])
.mount("/auth", auth::routes()) .mount("/auth", auth::routes())
.mount("/wikiauth", routes![wikiauth]) .mount("/wikiauth", routes![wikiauth])
.mount("/new-blogpost", routes![new_blogpost])
.mount("/blogpost-unpublished", routes![blogpost_unpublished])
.mount("/log", log::routes()) .mount("/log", log::routes())
.mount("/planned", planned::routes()) .mount("/planned", planned::routes())
.mount("/ergo", ergo::routes()) .mount("/ergo", ergo::routes())

View File

@ -33,6 +33,13 @@
<div class="mt-1">{{ notification.message | safe }}</div> <div class="mt-1">{{ notification.message | safe }}</div>
</div> </div>
<div> <div>
{% if notification.link %}
<a href="{{ notification.link }}" class="inline-block">
<button class="btn btn-primary" type="button">
🔗
</button>
</a>
{% endif %}
{% if not notification.read_at %} {% if not notification.read_at %}
<a href="/notification/{{ notification.id }}/read" class="inline-block"> <a href="/notification/{{ notification.id }}/read" class="inline-block">
<button class="btn btn-primary" type="button"> <button class="btn btn-primary" type="button">
@ -56,6 +63,13 @@
<strong>{{ notification.category }}</strong> &bullet; {{ notification.created_at | date(format="%d.%m.%Y %H:%M") }} <strong>{{ notification.category }}</strong> &bullet; {{ notification.created_at | date(format="%d.%m.%Y %H:%M") }}
</small> </small>
<div class="mt-1">{{ notification.message | safe }}</div> <div class="mt-1">{{ notification.message | safe }}</div>
{% if notification.link %}
<a href="{{ notification.link }}" class="inline-block">
<button class="btn btn-primary" type="button">
🔗
</button>
</a>
{% endif %}
</div> </div>
{% endif %} {% endif %}
{% endfor %} {% endfor %}

156
wordpress-notes.md Normal file
View File

@ -0,0 +1,156 @@
# Wordpress auth
Add the following code to `wp-content/themes/bravada/functions.php`:
```
function rot_auth( $user, $username, $password ){
// Make sure a username and password are present for us to work with
if($username == '' || $password == '') return;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://app.rudernlinz.at/wikiauth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "name=$username&password=$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the cURL session and get the response
$response = curl_exec($ch);
// Check for cURL errors
if(curl_errno($ch)){
$user = new WP_Error( 'denied', __('Curl error: ' . curl_error($ch)) );
}
// Close the cURL session
curl_close($ch);
if (strpos($response, 'SUCC') !== false) {
$user = get_user_by('login', $username);
if (!$user) {
// User does not exist, create a new one
$userdata = array(
'user_email' => $username,
'user_login' => $username,
'first_name' => $username,
'last_name' => ''
);
$new_user_id = wp_insert_user($userdata);
if (!is_wp_error($new_user_id)) {
// Load the new user info
$user = new WP_User($new_user_id);
// Set role based on username
if ($username == 'Philipp Hofer' || $username == 'Marie Birner') {
$user->set_role('administrator');
} else {
$user->set_role('editor');
}
} else {
// Handle error in user creation
return $new_user_id;
}
} else {
}
} else {
$user = new WP_Error( 'denied', __("Falscher Benutzername/Passwort. Verwendest du deine Accountdaten vom Ruderassistenten?") );
}
return $user;
}
// Comment this line if you wish to fall back on WordPress authentication
// Useful for times when the external service is offline
remove_action('authenticate', 'wp_authenticate_username_password', 20);
add_filter( 'authenticate', 'rot_auth', 10, 3 );
```
# Wordpress notify rowt on newly published article
Add the following code to `wp-content/themes/bravada/functions.php`:
```
function send_article_url_on_publish($new_status, $old_status, $post) {
// Check if the post is transitioning to 'publish' status
if ($new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'post') {
// Get the URL of the newly published article
$article_url = get_permalink($post->ID);
$article_title = get_the_title($post->ID);
// URL to send the POST request to
$api_url = 'https://app.rudernlinz.at/new-blogpost';
// Prepare the data for the POST request
$body = array(
'article_url' => $article_url,
'article_title' => $article_title,
'pw' => "wordpress_key"
);
// Prepare the arguments for wp_remote_post
$args = array(
'body' => $body,
'timeout' => '5',
'redirection' => '5',
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'cookies' => array()
);
// Send the POST request
$response = wp_remote_post($api_url, $args);
// Optional: Check if the request was successful
if (is_wp_error($response)) {
error_log('Failed to send POST request: ' . $response->get_error_message());
} else {
error_log('POST request sent successfully with article URL: ' . $article_url);
}
}
if ($new_status != 'publish' && $old_status == 'publish' && $post->post_type == 'post') {
$article_url = get_permalink($post->ID);
// URL to send the POST request to
$api_url = 'https://app.rudernlinz.at/blogpost-unpublished';
// Prepare the data for the POST request
$body = array(
'article_url' => $article_url,
'pw' => "wordpress_key"
);
// Prepare the arguments for wp_remote_post
$args = array(
'body' => $body,
'timeout' => '5',
'redirection' => '5',
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'cookies' => array()
);
// Send the POST request
$response = wp_remote_post($api_url, $args);
// Optional: Check if the request was successful
if (is_wp_error($response)) {
error_log('Failed to send POST request: ' . $response->get_error_message());
} else {
error_log('POST request sent successfully with article URL: ' . $article_url);
}
}
}
// Hook the function to the 'transition_post_status' action
add_action('transition_post_status', 'send_article_url_on_publish', 10, 3);
```