2016-07-16 04:09:08 +00:00
|
|
|
#![feature(plugin, custom_derive)]
|
2016-09-09 03:38:58 +00:00
|
|
|
#![plugin(rocket_codegen)]
|
2016-07-16 04:09:08 +00:00
|
|
|
|
|
|
|
extern crate rocket;
|
|
|
|
|
|
|
|
mod files;
|
|
|
|
|
|
|
|
use rocket::response::Redirect;
|
|
|
|
use rocket::form::FromFormValue;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct StrongPassword<'r>(&'r str);
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct AdultAge(isize);
|
|
|
|
|
|
|
|
#[derive(FromForm)]
|
|
|
|
struct UserLogin<'r> {
|
|
|
|
username: &'r str,
|
2016-08-02 02:47:21 +00:00
|
|
|
password: Result<StrongPassword<'r>, &'static str>,
|
|
|
|
age: Result<AdultAge, &'static str>,
|
2016-07-16 04:09:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'v> FromFormValue<'v> for StrongPassword<'v> {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
2016-09-30 08:25:07 +00:00
|
|
|
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
2016-07-16 04:09:08 +00:00
|
|
|
if v.len() < 8 {
|
|
|
|
Err("Too short!")
|
|
|
|
} else {
|
|
|
|
Ok(StrongPassword(v))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'v> FromFormValue<'v> for AdultAge {
|
|
|
|
type Error = &'static str;
|
|
|
|
|
2016-09-30 08:25:07 +00:00
|
|
|
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
|
|
|
let age = match isize::from_form_value(v) {
|
2016-07-16 04:09:08 +00:00
|
|
|
Ok(v) => v,
|
2016-08-02 02:47:21 +00:00
|
|
|
Err(_) => return Err("Age value is not a number."),
|
2016-07-16 04:09:08 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
match age > 20 {
|
|
|
|
true => Ok(AdultAge(age)),
|
2016-08-02 02:47:21 +00:00
|
|
|
false => Err("Must be at least 21."),
|
2016-07-16 04:09:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-04 11:06:28 +00:00
|
|
|
#[post("/login", form = "<user>")]
|
2016-07-16 04:09:08 +00:00
|
|
|
fn login(user: UserLogin) -> Result<Redirect, String> {
|
|
|
|
if user.age.is_err() {
|
|
|
|
return Err(String::from(user.age.unwrap_err()));
|
|
|
|
}
|
|
|
|
|
|
|
|
if user.password.is_err() {
|
|
|
|
return Err(String::from(user.password.unwrap_err()));
|
|
|
|
}
|
|
|
|
|
|
|
|
match user.username {
|
2016-08-02 02:47:21 +00:00
|
|
|
"Sergio" => {
|
|
|
|
match user.password.unwrap().0 {
|
|
|
|
"password" => Ok(Redirect::other("/user/Sergio")),
|
|
|
|
_ => Err("Wrong password!".to_string()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => Err(format!("Unrecognized user, '{}'.", user.username)),
|
2016-07-16 04:09:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-04 11:06:28 +00:00
|
|
|
#[get("/user/<username>")]
|
2016-07-16 04:09:08 +00:00
|
|
|
fn user_page(username: &str) -> String {
|
|
|
|
format!("This is {}'s page.", username)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2016-10-04 02:48:33 +00:00
|
|
|
rocket::ignite()
|
|
|
|
.mount("/", routes![files::index, files::files, user_page, login])
|
|
|
|
.launch();
|
2016-07-16 04:09:08 +00:00
|
|
|
}
|