start working on auth
This commit is contained in:
47
src/rest/auth.rs
Normal file
47
src/rest/auth.rs
Normal file
@ -0,0 +1,47 @@
|
||||
use rocket::{
|
||||
form::Form,
|
||||
get, post,
|
||||
request::FlashMessage,
|
||||
response::{status, Flash, Redirect},
|
||||
routes, FromForm, Responder, Route, State,
|
||||
};
|
||||
use rocket_dyn_templates::{context, tera, Template};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::model::user::{self, User, Users};
|
||||
|
||||
#[get("/")]
|
||||
async fn index(flash: Option<FlashMessage<'_>>) -> Template {
|
||||
let mut context = tera::Context::new();
|
||||
|
||||
if let Some(msg) = flash {
|
||||
context.insert("flash", &msg.into_inner());
|
||||
}
|
||||
|
||||
Template::render("auth/login", context.into_json())
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct LoginForm {
|
||||
name: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[post("/", data = "<login>")]
|
||||
async fn login(login: Form<LoginForm>, db: &State<SqlitePool>) -> Flash<Redirect> {
|
||||
let user = User::login(db, login.name.clone(), login.password.clone()).await;
|
||||
|
||||
//TODO: be able to use for find_by_name. This would get rid of the following match clause.
|
||||
let user = match user {
|
||||
Ok(user) => user,
|
||||
Err(_) => {
|
||||
return Flash::error(Redirect::to("/auth"), "Falscher Benutzername/Passwort");
|
||||
}
|
||||
};
|
||||
|
||||
Flash::success(Redirect::to("/"), "Login erfolgreich")
|
||||
}
|
||||
|
||||
pub fn routes() -> Vec<Route> {
|
||||
routes![index, login]
|
||||
}
|
@ -1,14 +1,21 @@
|
||||
use rocket::{get, routes, Build, Rocket};
|
||||
use rocket_dyn_templates::Template;
|
||||
use rocket_dyn_templates::{context, Template};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::model::user::Users;
|
||||
|
||||
mod auth;
|
||||
|
||||
#[get("/")]
|
||||
fn index() -> &'static str {
|
||||
"Hello, world!"
|
||||
fn index() -> Template {
|
||||
Template::render("index", context! {})
|
||||
}
|
||||
|
||||
pub fn start() -> Rocket<Build> {
|
||||
pub fn start(db: SqlitePool) -> Rocket<Build> {
|
||||
rocket::build()
|
||||
.manage(db)
|
||||
.mount("/", routes![index])
|
||||
.mount("/auth", auth::routes())
|
||||
.attach(Template::fairing())
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user