2

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 {
   ...
}
Poxy
  • 51
  • 4
  • Have you tried looking at https://api.rocket.rs/master/rocket/response/struct.Redirect.html and using it when the outcome is a failure? – jh316 Apr 06 '22 at 10:58

2 Answers2

2

As doc illustrate:

use rocket::response::Redirect;

#[get("/", rank = 2)]
async fn not_user() -> Redirect {
   Redirect::to(uri!(login))
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
1

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])
}
yzernik
  • 1,161
  • 2
  • 13
  • 19