expose user's api key as api_token field on sessions

This commit is contained in:
r888888888
2019-10-07 13:54:52 -07:00
parent 4e630f50cc
commit 62a1aeabce
3 changed files with 24 additions and 7 deletions

View File

@@ -1,4 +1,7 @@
class SessionsController < ApplicationController class SessionsController < ApplicationController
respond_to :html, :json
skip_forgery_protection only: :create, if: -> { request.format.json? }
def new def new
@user = User.new @user = User.new
end end
@@ -8,9 +11,18 @@ class SessionsController < ApplicationController
if session_creator.authenticate if session_creator.authenticate
url = params[:url] if params[:url] && params[:url].start_with?("/") 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 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
end end

View File

@@ -1,5 +1,6 @@
class SessionCreator class SessionCreator
attr_reader :session, :cookies, :name, :password, :ip_addr, :remember, :secure 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) def initialize(session, cookies, name, password, ip_addr, remember = false, secure = false)
@session = session @session = session
@@ -13,23 +14,23 @@ class SessionCreator
def authenticate def authenticate
if User.authenticate(name, password) if User.authenticate(name, password)
user = User.find_by_name(name) @user = User.find_by_name(name)
if remember.present? if remember.present?
cookies.permanent.signed[:user_name] = { cookies.permanent.signed[:user_name] = {
:value => user.name, :value => @user.name,
:secure => secure, :secure => secure,
:httponly => true :httponly => true
} }
cookies.permanent[:password_hash] = { cookies.permanent[:password_hash] = {
:value => user.bcrypt_cookie_password_hash, :value => @user.bcrypt_cookie_password_hash,
:secure => secure, :secure => secure,
:httponly => true :httponly => true
} }
end end
session[:user_id] = user.id session[:user_id] = @user.id
user.update_column(:last_ip_addr, ip_addr) @user.update_column(:last_ip_addr, ip_addr)
return true return true
else else
return false return false

View File

@@ -612,6 +612,10 @@ class User < ApplicationRecord
"created_at" => created_at.strftime("%Y-%m-%d %H:%M") "created_at" => created_at.strftime("%Y-%m-%d %H:%M")
}.to_json }.to_json
end end
def api_token
api_key.try(:key)
end
end end
module CountMethods module CountMethods