How to redirect if a guard fail

689 Views Asked by At

I'm using a guard to authenticated a user.

How can i easily redirect the user to the login page if a guard fail (redirect to /login in my example) ?

#[rocket::async_trait]
impl<'r> FromRequest<'r> for User {
    type Error = ();

    async fn from_request(request: &'r Request<'_>) -> Outcome<User, ()> {
        let db = request.guard::<&State<Db>>().await.succeeded().unwrap();
        
        /* Get user_id cookie */
        let c = request.cookies().get_private("user_id");

        match c {
            Some(c) => {
                ...
                Outcome::Success(user)
            },
            None => {
                Outcome::Failure((Status::BadRequest, ()))
            }
        }
    }
}

#[get("/")]
async fn home(user: User) -> Template {
   ...
}

#[get("/login")]
async fn login() -> Template {
   ...
}
2

There are 2 best solutions below

2
On

As doc illustrate:

use rocket::response::Redirect;

#[get("/", rank = 2)]
async fn not_user() -> Redirect {
   Redirect::to(uri!(login))
}
0
On

Register a 401 catcher:

https://api.rocket.rs/v0.5-rc/rocket/struct.Rocket.html#method.register

use rocket::Request;
    
#[catch(401)]
fn not_authorized(req: &Request) -> Redirect {
    // redirect here
}

#[launch]
fn rocket() -> _ {
    rocket::build().register("/", catchers![not_authorized])
}