From 3fbb3d1dc9b9d80ba2b7d843d7e89e0f432b1a71 Mon Sep 17 00:00:00 2001 From: Harlan T Wood Date: Sun, 13 Mar 2016 00:20:18 -0800 Subject: [PATCH] more token entropy --- app/models/token.rb | 15 +++++++++++++-- spec/models/token_spec.rb | 7 ++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/models/token.rb b/app/models/token.rb index 15bdca79..714730fc 100644 --- a/app/models/token.rb +++ b/app/models/token.rb @@ -1,11 +1,22 @@ class Token < ActiveRecord::Base belongs_to :user - before_create :generate_token + before_create :assign_token + + CHARS = 32 private + def assign_token + self.token = generate_token + end + def generate_token - self.token = SecureRandom.uuid.gsub(/\-/,'') + loop do + candidate = SecureRandom.base64(CHARS).gsub(/\W/, '') + if candidate.size >= CHARS + return candidate[0...CHARS] + end + end end end diff --git a/spec/models/token_spec.rb b/spec/models/token_spec.rb index 18bba17d..9fedeb2a 100644 --- a/spec/models/token_spec.rb +++ b/spec/models/token_spec.rb @@ -1,5 +1,10 @@ require 'rails_helper' RSpec.describe Token, type: :model do - pending "add some examples to (or delete) #{__FILE__}" + context "#generate_token" do + subject (:token) { Token.new } + it "should generate an alphanumeric token of 32 characters" do + expect(token.send(:generate_token)).to match /[a-zA-Z0-9]{32}/ + end + end end