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

Suggestion: single use tokenizer example #52

Closed
jonknapp opened this issue Mar 8, 2024 · 2 comments · Fixed by #62
Closed

Suggestion: single use tokenizer example #52

jonknapp opened this issue Mar 8, 2024 · 2 comments · Fixed by #62

Comments

@jonknapp
Copy link
Contributor

jonknapp commented Mar 8, 2024

With Rails 7.1 and generates_token_for I was able to create a single use tokenizer example pretty easily.

Sharing in case it's helpful:

class SingleUseTokenizer
  def self.decode(token, resource_class, *args)
    resource = resource_class.find_by_token_for(:passwordless_login, token)
    raise Devise::Passwordless::ExpiredTokenError unless resource
    raise Devise::Passwordless::InvalidTokenError unless resource.is_a?(resource_class)
    [resource, {}]
  end

  def self.encode(resource, *args)
    resource.generate_token_for(:passwordless_login)
  end
end

then in my User model

  generates_token_for :passwordless_login, expires_in: passwordless_login_within do
    current_sign_in_at
  end

It relies on the current_sign_in_at attribute changing on my user after a successful login. Once it changes, the same token will always be invalid and cannot be reused.

@abevoelker
Copy link
Owner

Ooh I love this! 🚀 🎉 Want to add it as an example to the README?

@jonknapp
Copy link
Contributor Author

jonknapp commented May 6, 2024

PR submitted. Feel free to adjust and/or delete however you'd like!

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 a pull request may close this issue.

2 participants