Add login

This commit is contained in:
2020-11-13 00:30:39 +01:00
parent fdab612863
commit 9b9cc4e0bd
8 changed files with 333 additions and 24 deletions

62
src/auth.rs Normal file
View File

@ -0,0 +1,62 @@
use crate::routes::pages;
use rocket::{
catch,
http::{Cookie, CookieJar, Status},
post,
request::{Form, FromForm, FromRequest, Outcome, Request},
response::Redirect,
uri, State,
};
use rocket_contrib::templates::Template;
pub struct MasterPassword(String);
impl From<String> for MasterPassword {
fn from(pass: String) -> Self {
Self(pass)
}
}
const AUTH_COOKIE_KEY: &str = "authorized";
const AUTH_COOKIE_VAL: &str = "true";
#[derive(Debug)]
pub struct Authorized;
#[derive(Debug)]
pub struct Unauthorized;
#[rocket::async_trait]
impl<'a, 'r> FromRequest<'a, 'r> for Authorized {
type Error = Unauthorized;
async fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> {
let cookies = request.cookies();
match cookies.get_private(AUTH_COOKIE_KEY) {
Some(cookie) if cookie.value() == AUTH_COOKIE_VAL => Outcome::Success(Authorized),
_ => Outcome::Failure((Status::Unauthorized, Unauthorized)),
}
}
}
#[catch(401)]
pub fn login_page(_req: &Request) -> Template {
Template::render("login", &())
}
#[derive(FromForm)]
pub struct Login {
password: String,
}
#[post("/login", data = "<login>")]
pub fn login(
cookies: &CookieJar,
login: Form<Login>,
master_pass: State<MasterPassword>,
) -> Redirect {
if login.password == master_pass.0 {
cookies.add_private(Cookie::new(AUTH_COOKIE_KEY, AUTH_COOKIE_VAL));
}
Redirect::to(uri!(pages::index))
}