use std::fmt::Debug; use std::time::SystemTime; use serde::{Deserialize, Serialize}; use easy_auth::core::token::errors::DecodeError; use easy_auth::core::token::token_service::TokenService; use easy_auth::prelude::token::jwt_token_service::JwtTokenService; #[test] fn encode_should_generate_jwt_token() { // given let secret_key = "my_secret_key"; let jwt_token_service = JwtTokenService::new(secret_key.to_string()); let claims = claim_test_with_expired(); let expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0X3N1YiIsImV4cCI6MTM1ODc4MTkyMSwicHNldWRvIjoicHNldWRvX3Rlc3QifQ.jV6TRv2GgyeniAwDVboXzbf2ftLczlHr5U6Uux6IOHk"; // when let result = jwt_token_service.encode(claims); // then assert_eq!(result, expected.to_string()) } #[test] fn decode_should_give_claims_from_jwt() { // given let secret_key = "my_secret_key"; let jwt_token_service = JwtTokenService::new(secret_key.to_string()); let claims_expected = claim_test_valid(); // current timestamp + 3600 let jwt_for_decoding = jwt_token_service.encode(claims_expected.clone()); // when let result = jwt_token_service .decode::(jwt_for_decoding.as_str()) .unwrap(); // then assert_eq!(result, claims_expected) } #[test] fn decode_should_be_wrong_with_expired_token() { // given let secret_key = "my_secret_key"; let jwt_token_service = JwtTokenService::new(secret_key.to_string()); let expired_claim = claim_test_with_expired(); // 21 janvier 2013 à 16h21 let jwt_for_decoding = jwt_token_service.encode(expired_claim.clone()); let expected_err = DecodeError :: new("ExpiredSignature".to_string()); // when let err = jwt_token_service .decode::(jwt_for_decoding.as_str()) .unwrap_err(); // then assert_eq!(err, expected_err) } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] struct Claims { sub: String, exp: usize, pseudo: String } fn claim_test_with_expired() -> Claims { claim_from_exp(1358781921) } fn claim_test_valid() -> Claims { claim_from_exp( SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as usize + 3600 ) } fn claim_from_exp(exp: usize) -> Claims { Claims { sub: "test_sub".to_string(), exp, pseudo: "pseudo_test".to_string() } }