From 3fbb3d1dc9b9d80ba2b7d843d7e89e0f432b1a71 Mon Sep 17 00:00:00 2001 From: Harlan T Wood Date: Sun, 13 Mar 2016 00:20:18 -0800 Subject: [PATCH 1/2] 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 From f3eb55897156bd4e2e41460d66a1edabe60c29aa Mon Sep 17 00:00:00 2001 From: Harlan T Wood Date: Sun, 13 Mar 2016 13:28:07 -0700 Subject: [PATCH 2/2] fix test regex --- spec/models/token_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/models/token_spec.rb b/spec/models/token_spec.rb index 9fedeb2a..ddb8d696 100644 --- a/spec/models/token_spec.rb +++ b/spec/models/token_spec.rb @@ -4,7 +4,7 @@ RSpec.describe Token, type: :model do 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}/ + expect(token.send(:generate_token)).to match /^[a-zA-Z0-9]{32}$/ end end end