Plume/src/routes/session.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

2018-05-19 09:39:59 +02:00
use rocket::{
http::{Cookie, Cookies, uri::Uri},
2018-05-19 09:39:59 +02:00
response::{Redirect, status::NotFound},
request::{Form,FlashMessage}
2018-05-19 09:39:59 +02:00
};
2018-04-24 11:21:39 +02:00
use rocket_contrib::Template;
2018-04-23 11:52:44 +02:00
use db_conn::DbConn;
2018-04-24 11:21:39 +02:00
use models::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-04-23 11:52:44 +02:00
#[derive(FromForm)]
struct LoginForm {
email_or_name: String,
password: String
}
#[post("/login", data = "<data>")]
fn create(conn: DbConn, data: Form<LoginForm>, flash: Option<FlashMessage>, mut cookies: Cookies) -> Result<Redirect, NotFound<String>> {
2018-04-23 11:52:44 +02:00
let form = data.get();
let user = match User::find_by_email(&*conn, form.email_or_name.to_string()) {
Some(usr) => Ok(usr),
2018-05-01 13:48:19 +02:00
None => match User::find_local(&*conn, form.email_or_name.to_string()) {
2018-04-23 11:52:44 +02:00
Some(usr) => Ok(usr),
None => Err("Invalid username or password")
}
};
match user {
Ok(usr) => {
if usr.auth(form.password.to_string()) {
cookies.add_private(Cookie::new(AUTH_COOKIE, usr.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()))
))
2018-04-23 11:52:44 +02:00
} else {
Err(NotFound(String::from("Invalid username or password")))
}
},
Err(e) => Err(NotFound(String::from(e)))
}
}
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("/")
}