Generating unique token on the fly with Rails

前端 未结 6 1549
醉话见心
醉话见心 2021-01-31 18:50

I want to generate a token in my controller for a user in the \"user_info_token\" column. However, I want to check that no user currently has that token. Would this code suffice

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 19:48

    I have many models I apply unique tokens to. For this reason I've created a Tokened concern in app/models/concerns/tokened.rb

    module Tokened
    
      extend ActiveSupport::Concern
    
      included do
        after_initialize do
          self.token = generate_token if self.token.blank?
        end
      end
    
      private
        def generate_token
          loop do
            key = SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')
            break key unless self.class.find_by(token: key)
          end
        end
    end
    

    In any model I want to have unique tokens, I just do

    include Tokened
    

    But yes, your code looks fine too.

提交回复
热议问题