diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index d44c2eda8..7146807a0 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,4 +1,7 @@ class SessionsController < ApplicationController + respond_to :html, :json + skip_forgery_protection only: :create, if: -> { request.format.json? } + def new @user = User.new end @@ -8,9 +11,18 @@ class SessionsController < ApplicationController if session_creator.authenticate url = params[:url] if params[:url] && params[:url].start_with?("/") - redirect_to(url || posts_path, :notice => "You are now logged in") + url = posts_path if url.nil? + respond_with(session_creator.user, location: url, methods: [:api_token]) else - redirect_to(new_session_path, :notice => "Password was incorrect") + respond_with("password was incorrect", location: new_session_path) do |fmt| + fmt.json do + render json: { error: true, message: "password was incorrect"}.to_json, status: 401 + end + + fmt.html do + flash[:notice] = "Password was incorrect" + end + end end end diff --git a/app/logical/session_creator.rb b/app/logical/session_creator.rb index b21c3eb72..cf22bbdaa 100644 --- a/app/logical/session_creator.rb +++ b/app/logical/session_creator.rb @@ -1,5 +1,6 @@ class SessionCreator attr_reader :session, :cookies, :name, :password, :ip_addr, :remember, :secure + attr_reader :user def initialize(session, cookies, name, password, ip_addr, remember = false, secure = false) @session = session @@ -13,23 +14,23 @@ class SessionCreator def authenticate if User.authenticate(name, password) - user = User.find_by_name(name) + @user = User.find_by_name(name) if remember.present? cookies.permanent.signed[:user_name] = { - :value => user.name, + :value => @user.name, :secure => secure, :httponly => true } cookies.permanent[:password_hash] = { - :value => user.bcrypt_cookie_password_hash, + :value => @user.bcrypt_cookie_password_hash, :secure => secure, :httponly => true } end - session[:user_id] = user.id - user.update_column(:last_ip_addr, ip_addr) + session[:user_id] = @user.id + @user.update_column(:last_ip_addr, ip_addr) return true else return false diff --git a/app/models/user.rb b/app/models/user.rb index 1fd46c82c..cd4b15ef2 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -612,6 +612,10 @@ class User < ApplicationRecord "created_at" => created_at.strftime("%Y-%m-%d %H:%M") }.to_json end + + def api_token + api_key.try(:key) + end end module CountMethods