OSDN Git Service

fix: token generator
authoryasushiito <yas@pen-chan.jp>
Thu, 9 Jul 2015 23:49:46 +0000 (08:49 +0900)
committeryasushiito <yas@pen-chan.jp>
Thu, 9 Jul 2015 23:49:46 +0000 (08:49 +0900)
app/controllers/application_controller.rb
app/models/user.rb

index 14c8e8c..634b9c3 100644 (file)
@@ -3,6 +3,7 @@ class ApplicationController < ActionController::Base
   protect_from_forgery with: :null_session, if: Proc.new {|c| c.request.format == 'application/json'}
   layout :devise_layout
   before_action :bf
+  before_action :authenticate_user_from_token!, if: -> {params[:email].present?}
   
   def devise_layout
     if devise_controller?
@@ -29,7 +30,6 @@ class ApplicationController < ActionController::Base
     else
       nil
     end
-    p user
     author = if user
       user.author
     else
@@ -53,6 +53,14 @@ class ApplicationController < ActionController::Base
     @operators = Operator.new [user, author, artist, admin, demand_user]
   end
   
+  def authenticate_user_from_token!
+    user = User.find_by(email: params[:email])
+    if Devise.secure_compare(user.try(:authentication_token), params[:auth_token])
+      sign_in user, store: false
+      self.bf
+    end
+  end
+  
   def authenticate_reader
     authenticate_user! unless @operators.reader?
   end
index f6b0cdf..d9872ca 100644 (file)
@@ -9,9 +9,19 @@ class User < ActiveRecord::Base
          :omniauthable#, :confirmable
 
   def create_token
-    self.ensure_authentication_token
+    loop do
+      token = Devise.friendly_token
+      if token_suitable?(token)
+        self.authentication_token = token
+        break
+      end
+    end
     self.save
   end
+
+  def token_suitable?(token)
+    !self.class.exists?(authentication_token: token)
+  end
   
   def delete_token
     self.authentication_token = nil