Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Decoding of Subclasses in decode Method #68

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

llaine
Copy link

@llaine llaine commented Dec 9, 2024

I was struggling with an issue for the past days and I manage to fix it in my case, so I figure i'd do a PR so maybe it can help others.

Summary

This PR modifies the decode method to allow children classes of the specified resource_class to be decoded. By changing the class comparison logic, this adjustment ensures that subclasses can be properly authenticated without throwing an InvalidTokenError.

Rationale

This change enhances the flexibility of the decode method by allowing subclasses to be decoded. For example:

class User
  devise :magic_link_authenticatable
end

class AnonymousUser < User
end

class Admin < User
end

In a controller, a token generated for a User can now be decoded into either an AnonymousUser or an Admin without raising an error:

At this point, user could be an AnonymousUser or an Admin

token = user.encode_passwordless_token(expires_at: 2.hours.from_now)

This works without throwing an InvalidTokenError

User.decode_passwordless_token(token, User).first

Benefits

  • Supports more dynamic and hierarchical user models.
  • Aligns with typical object-oriented inheritance principles, allowing subclasses to function as intended when decoding tokens.
  • Backward Compatibility
  • This change is backward-compatible for scenarios where no subclasses are involved, as the comparison using <= still ensures strict type matching if no inheritance is present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant