You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
the title might not be the best, but TBH I cant think of anything else, forgive me for that
I have this App:
App::new().service(index).service(
web::scope("/api").service(login).service(
web::scope("").service(index).service(logout).service(
web::scope("/hello").service(hello)).wrap(middlewares::auth::JwtMiddleware))).wrap(Logger::new("%a [%t] - size:%bB, took %D ms : %r %{Referer}i STATUS %s ")).app_data(Data::clone(&pool))
which defines a /api scope that contains login, logout and another /hello scope
what Im trying to achieve is that the login shouldn't be processed by JwtMiddleware and also if a user is already logged-in, the login should not be allowed to call.
which is where the problem is, this is how im trying to do it:
#[get("/login/{id}")]pubasyncfnlogin(db: web::Data<PgPool>,user:Path<User>,req:HttpRequest) -> actix_web::Result<implResponder>{ifletSome(user) = req.extensions().get::<User>(){returnOk(HttpResponse::Ok().json(json!({"message":format!("you are already logged in with {}",user.id)})))}match db::user::exists(&db,&user.id).await{Ok(exist) => {if !exist{returnOk(HttpResponse::BadRequest().json(json!({"message":"user not found"})));}}Err(_) => {returnOk(HttpResponse::InternalServerError().json(json!({"message":"internal error"})));}};let now = Utc::now();let claims:TokenClaims = TokenClaims{sub: user.id.to_string(),exp:(now + Duration::days(365)).timestamp()asusize,iat: now.timestamp()asusize,};let token = encode(&Header::default(),&claims,&EncodingKey::from_secret("some secret".as_bytes())).unwrap();let cookie = Cookie::build("token", token.to_owned()).path("/").max_age(actix_web::cookie::time::Duration::days(365)).http_only(true).finish();
req.extensions_mut().insert::<User>(user.into_inner());Ok(HttpResponse::Ok().cookie(cookie).json(json!({"status":"success","token": token})))}
the JwtMiddleware call:
fncall(&self,req:ServiceRequest) -> Self::Future{ifletSome(token) = req.cookie("token"){matchdecode::<TokenClaims>(
token.value(),&DecodingKey::from_secret("some secret".as_bytes()),&Validation::default(),){Ok(decoded) => {let user = User{id: uuid::Uuid::parse_str(decoded.claims.sub.as_str()).unwrap()};if req.extensions().contains::<User>(){returnBox::pin(asyncmove{Ok(req.into_response(HttpResponse::Ok().json(json!({"message":format!("you are already logged in with {}",user.id)}))).map_into_boxed_body())});}
req.extensions_mut().insert::<User>(user);let fut = self.service.call(req);Box::pin(asyncmove{let res = fut.await?;Ok(res.map_into_boxed_body())})}Err(_) => {Box::pin(asyncmove{Ok(
req.into_response(HttpResponse::Unauthorized().json(json!({"message":"InvalidToken"}))).map_into_boxed_body())})}}}else{Box::pin(asyncmove{Ok(
req.into_response(HttpResponse::Unauthorized().json(json!({"message":"You are not logged in"}))).map_into_boxed_body())})}}
notice that im inserting the user in extensions as well as cookies, and at the beginning im checking if it already exist then do not proceed, but the check fails and it seems the extension is not storing the user or... IDK.
im not sure if this is even the best practice or not, but it doesn't work anyway..
what could be the problem here?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
the title might not be the best, but TBH I cant think of anything else, forgive me for that
I have this App:
which defines a
/api
scope that contains login, logout and another/hello
scopewhat Im trying to achieve is that the login shouldn't be processed by
JwtMiddleware
and also if a user is already logged-in, the login should not be allowed to call.which is where the problem is, this is how im trying to do it:
the JwtMiddleware call:
notice that im inserting the user in extensions as well as cookies, and at the beginning im checking if it already exist then do not proceed, but the check fails and it seems the extension is not storing the user or... IDK.
im not sure if this is even the best practice or not, but it doesn't work anyway..
what could be the problem here?
Beta Was this translation helpful? Give feedback.
All reactions