Authentication
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
pub mod instance;
|
||||
pub mod session;
|
||||
pub mod user;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::collections::HashMap;
|
||||
use rocket_contrib::Template;
|
||||
use rocket::response::Redirect;
|
||||
use rocket::request::Form;
|
||||
use models::user::User;
|
||||
use rocket::response::status::NotFound;
|
||||
use rocket::http::Cookies;
|
||||
use db_conn::DbConn;
|
||||
use rocket::http::Cookie;
|
||||
use models::user::AUTH_COOKIE;
|
||||
|
||||
#[get("/login")]
|
||||
fn new() -> Template {
|
||||
Template::render("session/login", HashMap::<String, String>::new())
|
||||
}
|
||||
|
||||
#[derive(FromForm)]
|
||||
struct LoginForm {
|
||||
email_or_name: String,
|
||||
password: String
|
||||
}
|
||||
|
||||
#[post("/login", data = "<data>")]
|
||||
fn create(conn: DbConn, data: Form<LoginForm>, mut cookies: Cookies) -> Result<Redirect, NotFound<String>> {
|
||||
let form = data.get();
|
||||
let user = match User::find_by_email(&*conn, form.email_or_name.to_string()) {
|
||||
Some(usr) => Ok(usr),
|
||||
None => match User::find_by_name(&*conn, form.email_or_name.to_string()) {
|
||||
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("/"))
|
||||
} else {
|
||||
Err(NotFound(String::from("Invalid username or password")))
|
||||
}
|
||||
},
|
||||
Err(e) => Err(NotFound(String::from(e)))
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -2,16 +2,19 @@ use rocket::request::Form;
|
||||
use rocket::response::Redirect;
|
||||
use rocket_contrib::Template;
|
||||
use std::collections::HashMap;
|
||||
use bcrypt::{hash, DEFAULT_COST};
|
||||
|
||||
use db_conn::DbConn;
|
||||
use models::user::*;
|
||||
use models::instance::Instance;
|
||||
|
||||
#[get("/me")]
|
||||
fn me(user: User) -> String {
|
||||
format!("Logged in as {}", user.username.to_string())
|
||||
}
|
||||
|
||||
#[get("/@/<name>")]
|
||||
fn details(name: String) {
|
||||
|
||||
fn details(name: String) -> String {
|
||||
format!("Hello, @{}", name)
|
||||
}
|
||||
|
||||
#[get("/users/new")]
|
||||
@@ -41,7 +44,7 @@ fn create(conn: DbConn, data: Form<NewUserForm>) -> Redirect {
|
||||
is_admin: !inst.has_admin(&*conn),
|
||||
summary: String::from(""),
|
||||
email: Some(form.email.to_string()),
|
||||
hashed_password: Some(hash(form.password.as_str(), DEFAULT_COST).unwrap()),
|
||||
hashed_password: Some(User::hash_pass(form.password.to_string())),
|
||||
instance_id: inst.id
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user