summaryrefslogtreecommitdiffstats
path: root/src/routes/login.rs
diff options
context:
space:
mode:
authorLibravatar cel 🌸 <cel@blos.sm>2023-12-12 14:14:30 +0000
committerLibravatar cel 🌸 <cel@blos.sm>2023-12-12 14:14:30 +0000
commit370a25e5a0cbb95e2aa1cec55305b22aeaf99aa0 (patch)
tree665163bc58c8e94320b843b1983376d9a67f99bf /src/routes/login.rs
parent5dc4774ed3380762b4d7aadc86193af6073c456a (diff)
downloadpinussy-370a25e5a0cbb95e2aa1cec55305b22aeaf99aa0.tar.gz
pinussy-370a25e5a0cbb95e2aa1cec55305b22aeaf99aa0.tar.bz2
pinussy-370a25e5a0cbb95e2aa1cec55305b22aeaf99aa0.zip
initial refactor
Diffstat (limited to 'src/routes/login.rs')
-rw-r--r--src/routes/login.rs82
1 files changed, 82 insertions, 0 deletions
diff --git a/src/routes/login.rs b/src/routes/login.rs
new file mode 100644
index 0000000..33f7f69
--- /dev/null
+++ b/src/routes/login.rs
@@ -0,0 +1,82 @@
+use actix_session::Session;
+use actix_web::http::header::LOCATION;
+use actix_web::{get, post, web, HttpResponse};
+use bcrypt::verify;
+use serde::Deserialize;
+
+use crate::notification::{Kind, Notification};
+use crate::templates;
+use crate::Pinussy;
+use crate::Result;
+
+#[get("/login")]
+async fn get() -> HttpResponse {
+ HttpResponse::Ok().body(render!(templates::login_html, None).unwrap())
+}
+
+#[derive(Deserialize)]
+struct LoginForm {
+ username: String,
+ password: String,
+ rememberme: Option<String>,
+}
+
+#[post("/login")]
+async fn post(
+ state: web::Data<Pinussy>,
+ session: Session,
+ form: web::Form<LoginForm>,
+) -> Result<HttpResponse> {
+ match sqlx::query!(
+ "select id, password from users where username = $1",
+ &form.username
+ )
+ .fetch_one(&state.db)
+ .await
+ {
+ Ok(user) => {
+ let password_hash: String = user.password;
+ if verify(&form.password, &password_hash)? {
+ session.insert("user_id", user.id)?;
+ return Ok(HttpResponse::SeeOther()
+ .insert_header((LOCATION, "/"))
+ .finish());
+ } else {
+ return Ok(HttpResponse::Unauthorized().body(
+ render!(
+ templates::login_html,
+ Some(Notification {
+ kind: Kind::Error,
+ message: "that password is incorrect".to_owned()
+ })
+ )
+ .unwrap(),
+ ));
+ }
+ }
+ Err(sqlx::Error::RowNotFound) => {
+ return Ok(HttpResponse::NotFound().body(
+ render!(
+ templates::login_html,
+ Some(Notification {
+ kind: Kind::Error,
+ message: format!("the user \"{}\" does not exist", &form.username)
+ })
+ )
+ .unwrap(),
+ ));
+ }
+ Err(_) => {
+ return Ok(HttpResponse::InternalServerError().body(
+ render!(
+ templates::login_html,
+ Some(Notification {
+ kind: Kind::Error,
+ message: "internal server error. please try again later".to_owned()
+ })
+ )
+ .unwrap(),
+ ));
+ }
+ }
+}