Add login
This commit is contained in:
62
src/auth.rs
Normal file
62
src/auth.rs
Normal 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))
|
||||
}
|
||||
Reference in New Issue
Block a user