Plume/src/routes/session.rs

80 lines
2.3 KiB
Rust
Raw Normal View History

2018-05-19 09:39:59 +02:00
use rocket::{
http::{Cookie, Cookies, uri::Uri},
2018-07-06 11:51:19 +02:00
response::Redirect,
2018-06-24 18:58:57 +02:00
request::{LenientForm,FlashMessage}
2018-05-19 09:39:59 +02:00
};
2018-04-24 11:21:39 +02:00
use rocket_contrib::Template;
2018-07-06 11:51:19 +02:00
use validator::{Validate, ValidationError, ValidationErrors};
2018-04-24 11:21:39 +02:00
use plume_models::{
db_conn::DbConn,
users::{User, AUTH_COOKIE}
};
2018-04-23 11:52:44 +02:00
#[get("/login")]
2018-05-10 22:31:52 +02:00
fn new(user: Option<User>) -> Template {
Template::render("session/login", json!({
"account": user
}))
2018-04-23 11:52:44 +02:00
}
#[derive(FromForm)]
struct Message {
m: String
}
#[get("/login?<message>")]
fn new_message(user: Option<User>, message: Message) -> Template {
Template::render("session/login", json!({
"account": user,
"message": message.m
}))
}
2018-06-29 14:56:00 +02:00
#[derive(FromForm, Validate)]
2018-04-23 11:52:44 +02:00
struct LoginForm {
2018-06-29 14:56:00 +02:00
#[validate(length(min = "1"))]
2018-04-23 11:52:44 +02:00
email_or_name: String,
2018-06-29 14:56:00 +02:00
#[validate(length(min = "8"))]
2018-04-23 11:52:44 +02:00
password: String
}
#[post("/login", data = "<data>")]
2018-07-06 11:51:19 +02:00
fn create(conn: DbConn, data: LenientForm<LoginForm>, flash: Option<FlashMessage>, mut cookies: Cookies) -> Result<Redirect, Template> {
2018-04-23 11:52:44 +02:00
let form = data.get();
2018-07-06 11:51:19 +02:00
let user = User::find_by_email(&*conn, form.email_or_name.to_string())
.map(|u| Ok(u))
.unwrap_or_else(|| User::find_local(&*conn, form.email_or_name.to_string()).map(|u| Ok(u)).unwrap_or(Err(())));
let mut errors = match form.validate() {
Ok(_) => ValidationErrors::new(),
Err(e) => e
2018-04-23 11:52:44 +02:00
};
2018-07-06 11:51:19 +02:00
if let Err(_) = user.clone() {
errors.add("email_or_name", ValidationError::new("invalid_login"))
} else if !user.clone().expect("User not found").auth(form.password.clone()) {
errors.add("email_or_name", ValidationError::new("invalid_login"))
}
if errors.is_empty() {
cookies.add_private(Cookie::new(AUTH_COOKIE, user.unwrap().id.to_string()));
Ok(Redirect::to(Uri::new(flash
.and_then(|f| if f.name() == "callback" { Some(f.msg().to_owned()) } else { None })
.unwrap_or("/".to_owned()))
))
} else {
Err(Template::render("session/login", json!({
"account": user,
"errors": errors.inner()
})))
2018-04-23 11:52:44 +02:00
}
}
2018-04-23 13:13:49 +02:00
#[get("/logout")]
fn delete(mut cookies: Cookies) -> Redirect {
let cookie = cookies.get_private(AUTH_COOKIE).unwrap();
cookies.remove_private(cookie);
Redirect::to("/")
}