Created
March 15, 2016 12:43
-
-
Save hchood/141e832d7bd4c432702d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/user.rb | |
def reset_token! | |
AuthenticationToken.reset(user: self) | |
end | |
# app/services/authentication_token.rb | |
class AuthenticationToken | |
attr_reader :user | |
def initialize(user:) | |
@user = user | |
end | |
def self.reset(user:) | |
new(user: user).reset | |
end | |
def reset | |
params = { authentication_token: generate_unique_token, | |
authentication_token_expires_at: expires_at } | |
user.update(params) | |
end | |
def generate_unique_token | |
token = generate_token | |
until unique?(token) | |
token = generate_token | |
end | |
token | |
end | |
def expires_at | |
token_duration.days.from_now | |
end | |
private | |
def generate_token | |
SecureRandom.hex(20).encode('UTF-8') | |
end | |
def unique?(token) | |
!existing_tokens.include?(token) | |
end | |
def existing_tokens | |
@existing_tokens ||= User.pluck(:authentication_token) | |
end | |
def token_duration | |
ENV.fetch('TOKEN_DURATION_DAYS').to_i | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment