feat: port login page to tera

This commit is contained in:
Aravinth Manivannan 2023-01-24 19:25:56 +05:30
parent c645bf83a3
commit d2f266c689
Signed by: realaravinth
GPG key ID: AD9F0F08E855ED88
2 changed files with 120 additions and 123 deletions

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net> * Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as * it under the terms of the GNU Affero General Public License as
@ -14,90 +14,87 @@
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use std::cell::RefCell;
use actix_identity::Identity; use actix_identity::Identity;
use actix_web::HttpResponseBuilder; use actix_web::http::header::{self, ContentType};
use actix_web::{error::ResponseError, http::header, web, HttpResponse, Responder}; use tera::Context;
use lazy_static::lazy_static;
use my_codegen::{get, post};
use sailfish::TemplateOnce;
use crate::api::v1::admin::auth::runners; use crate::api::v1::admin::auth::runners;
use crate::api::v1::RedirectQuery; use crate::api::v1::RedirectQuery;
use crate::errors::*; use crate::pages::errors::*;
use crate::pages::errors::ErrorPage; use crate::settings::Settings;
use crate::AppData; use crate::AppData;
use crate::PAGES;
#[derive(Clone, TemplateOnce)] pub use super::*;
#[template(path = "auth/login/index.html")]
struct IndexPage<'a> { pub struct Login {
error: Option<ErrorPage<'a>>, ctx: RefCell<Context>,
} }
const PAGE: &str = "Login"; pub const LOGIN: TemplateFile = TemplateFile::new("login", "auth/login/index.html");
impl<'a> Default for IndexPage<'a> { impl CtxError for Login {
fn default() -> Self { fn with_error(&self, e: &ReadableError) -> String {
IndexPage { error: None } self.ctx.borrow_mut().insert(ERROR_KEY, e);
self.render()
} }
} }
impl<'a> IndexPage<'a> { impl Login {
pub fn new(title: &'a str, message: &'a str) -> Self { pub fn new(settings: &Settings) -> Self {
Self { let ctx = RefCell::new(context(settings, "Login"));
error: Some(ErrorPage::new(title, message)), Self { ctx }
} }
pub fn render(&self) -> String {
TEMPLATES.render(LOGIN.name, &self.ctx.borrow()).unwrap()
}
pub fn page(s: &Settings) -> String {
let p = Self::new(s);
p.render()
} }
} }
lazy_static! { #[actix_web_codegen_const_routes::get(path = "PAGES.auth.login")]
static ref INDEX: String = IndexPage::default().render_once().unwrap(); #[tracing::instrument(name = "Serve login page", skip(ctx))]
pub async fn get_login(ctx: AppData) -> impl Responder {
let login = Login::page(&ctx.settings);
let html = ContentType::html();
HttpResponse::Ok().content_type(html).body(login)
} }
#[get(path = "PAGES.auth.login")] pub fn services(cfg: &mut web::ServiceConfig) {
pub async fn login() -> impl Responder { cfg.service(get_login);
HttpResponse::Ok() cfg.service(login_submit);
.content_type("text/html; charset=utf-8")
.body(&*INDEX.as_str())
} }
#[post(path = "PAGES.auth.login")] #[actix_web_codegen_const_routes::post(path = "PAGES.auth.login")]
#[tracing::instrument(name = "Web UI Login", skip(id, payload, data, path))]
pub async fn login_submit( pub async fn login_submit(
id: Identity, id: Identity,
payload: web::Form<runners::Login>, payload: web::Form<runners::Login>,
data: AppData, data: AppData,
path: web::Path<RedirectQuery>, path: web::Path<RedirectQuery>,
) -> PageResult<impl Responder> { ) -> PageResult<impl Responder, Login> {
let payload = payload.into_inner(); let payload = payload.into_inner();
match runners::login_runner(&payload, &data).await { let username = runners::login_runner(&payload, &data)
Ok(username) => { .await
id.remember(username); .map_err(|e| PageError::new(Login::new(&data.settings), e))?;
let path = path.into_inner();
if let Some(redirect_to) = path.redirect_to {
Ok(HttpResponse::Found()
.insert_header((header::LOCATION, redirect_to))
.finish())
} else {
Ok(HttpResponse::Found()
.insert_header((header::LOCATION, PAGES.home))
.finish())
}
}
Err(e) => {
let status = e.status_code();
let heading = status.canonical_reason().unwrap_or("Error");
Ok(HttpResponseBuilder::new(status) id.remember(username);
.content_type("text/html; charset=utf-8") let path = path.into_inner();
.body( if let Some(redirect_to) = path.redirect_to {
IndexPage::new(heading, &format!("{}", e)) Ok(HttpResponse::Found()
.render_once() .insert_header((header::LOCATION, redirect_to))
.unwrap(), .finish())
)) } else {
} Ok(HttpResponse::Found()
.insert_header((header::LOCATION, PAGES.home))
.finish())
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_web::test; use actix_web::test;
@ -105,14 +102,13 @@ mod tests {
use super::*; use super::*;
use crate::api::v1::admin::auth::runners::{Login, Register}; use crate::api::v1::admin::auth::runners::{Login, Register};
use crate::data::Data;
use crate::tests::*; use crate::tests::*;
use crate::*; use crate::*;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
#[actix_rt::test] #[actix_rt::test]
async fn auth_form_works() { async fn auth_form_works() {
let data = Data::new().await; let data = get_test_data().await;
const NAME: &str = "testuserform"; const NAME: &str = "testuserform";
const PASSWORD: &str = "longpassword"; const PASSWORD: &str = "longpassword";

View file

@ -1,69 +1,70 @@
<. include!("../../components/base/top.html"); .> {% extends 'base' %}
<body class="auth__body"> {% block body %}
<main class="auth__container">
<img src="<.= crate::assets::LOGO.path .>" alt="logo" class="auth__logo" />
<h1>Join Survey</h1>
<. include!("../../components/error/index.html"); .>
<form
action="<.= crate::PAGES.auth.join .>"
method="POST"
class="form"
accept-charset="utf-8"
>
<label class="form__label" for="username">
Username
<input
class="form__input"
name="username"
required
id="username"
type="text"
/>
</label>
<label class="form__label" for="email"> <body class="auth__body">
Email(optional) <main class="auth__container">
<input <img src="{{ assets.logo.path }}" alt="logo" class="auth__logo" />
class="form__input" <h1>Join Survey</h1>
name="email" {% include "error_comp" %}
id="email" <form
type="email" action="{{ page.auth.join }}"
/> method="POST"
</label> class="form"
accept-charset="utf-8"
>
<label class="form__label" for="username">
Username
<input
class="form__input"
name="username"
required
id="username"
type="text"
/>
</label>
<label class="form__label" for="password"> <label class="form__label" for="email">
password Email(optional)
<input <input
class="form__input" class="form__input"
name="password" name="email"
required id="email"
id="password" type="email"
type="password" />
/> </label>
</label>
<label class="form__label" for="confirm_password"> <label class="form__label" for="password">
Re-enter Password password
<input <input
class="form__input" class="form__input"
name="confirm_password" name="password"
required required
id="confirm_password" id="password"
type="password" type="password"
/> />
</label> </label>
<div class="form__action-container"> <label class="form__label" for="confirm_password">
<a href="/forgot-password">Forgot password?</a> Re-enter Password
<button class="form__submit" type="submit">Join</button> <input
</div> class="form__input"
</form> name="confirm_password"
required
id="confirm_password"
type="password"
/>
</label>
<p class="form__alt-action"> <div class="form__action-container">
Already have an account? <a href="/forgot-password">Forgot password?</a>
<a href="<.= crate::PAGES.auth.login .>"> Login </a> <button class="form__submit" type="submit">Join</button>
</p> </div>
</main> </form>
<. include!("../../components/footer/index.html"); .>
</body> <p class="form__alt-action">
<. include!("../../components/base/bottom.html"); .> Already have an account?
<a href="{{ page.auth.login }}"> Login </a>
</p>
</main>
</body>
{% endblock body %}