admin管理员组

文章数量:1122832

I have custom AuthGuard


pub struct AuthGuard {
  pub value: User,
}




#[async_trait]
impl<'r> FromRequest<'r> for AuthGuard {
  type Error = JsonValue;


  async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {

    let config: &State<ConfigModel> = req.guard().await.unwrap();
    let mongo: &State<Database> = req.guard().await.unwrap();


    // get cookie
    let access_cookie = req.cookies().get("psw-manager.access_token");
    if access_cookie.is_none() {
      return Outcome::Error( (Status::Unauthorized, json!({"err": "Unauthorized"})) ); // return
    }


    // proceed token
    /* ...getting token... */
    match jsonwebtoken::decode::<AccessToken>(token, &secret, &_validation) {
        

      Ok(parsed_token) => {

        // check if token expired
        let time_now = chrono::prelude::Local::now();
        let time_expires_at = chrono::DateTime::parse_from_rfc2822(
          &parsed_token.claims.this_jwt_expires_at
        ).unwrap();
        if time_now > time_expires_at {
          return Outcome::Error( (Status::Unauthorized, json!({"err": "Unauthorized"})) ); // return
        }

        // check if user exists / is verifie]
        // bunch of checks with on err return Outcome::Error( (Status::Forbidden, json!({"err": "User is not verified"})) ); // return
        }

        // if ok
        Outcome::Success( AuthGuard {value: user.unwrap()} )
      },



      // on jwt verify failure
      Err(e) => {
        println!("{}", e);
        return Outcome::Error( (Status::Unauthorized, json!({"err": "Invalid token"})) ); // return
      }


    }
    
  }
}

So, basically, on error this guard returns Outcome::Error with simple json, but it fallbacks to 401 error handler (which i don't have)

   >> Request guard `AuthGuard` failed: Object {"err": String("Invalid token")}.
   >> Outcome: Error(401 Unauthorized)
   >> No 401 catcher registered. Using Rocket default.
   >> Response succeeded.

How to just respond with 401 {some json} from this guard? Or at least how to make handler which will pass JsonValue?

P.S. I know this gode is gross, but i can't rewrite guard until i find out how to make it respond

本文标签: rustHow to force rocket to respond in custom guardStack Overflow