mirror of
https://github.com/wahyd4/libr-2.git
synced 2026-08-21 19:25:58 +10:00
53 lines
1.4 KiB
Ruby
53 lines
1.4 KiB
Ruby
class Api::V1::ApplicationController < ActionController::Base
|
|
include ActionController::Serialization
|
|
|
|
skip_before_action :verify_authenticity_token
|
|
|
|
serialization_scope :view_context
|
|
before_action :current_user!
|
|
before_action :authenticate_user_from_token
|
|
|
|
def current_user!
|
|
@current_user = nil
|
|
@current_user = current_user if user_signed_in?
|
|
end
|
|
|
|
def user_json(user= current_user)
|
|
{
|
|
user: {
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
token: JWT.encode({token: user.active_auth_token}, user.email)
|
|
}
|
|
}
|
|
end
|
|
|
|
def authenticate_user_from_token
|
|
auth_token = AuthToken.find_by(value: request.headers["Authorization"].try(:split, ' ').try(:last))
|
|
if auth_token
|
|
@current_user = auth_token.user
|
|
else
|
|
return render json: {message: 'Token is not valid'}, status: 401
|
|
end
|
|
end
|
|
|
|
def fetch_current_user
|
|
auth_token = AuthToken.find_by(value: request.headers["Authorization"].try(:split, ' ').try(:last))
|
|
@current_user = auth_token.user if auth_token
|
|
end
|
|
|
|
private
|
|
|
|
def load_target_user
|
|
@target_user = User.find_by id: params[:user_id]
|
|
render json: {msg: '不能找到该用户'}, status: 404 unless @target_user
|
|
end
|
|
|
|
def load_post
|
|
@target_post = Post.find_by id: params[:post_id] || params[:id]
|
|
render json: {msg: '不能找到该文章'}, status: 404 unless @target_post
|
|
end
|
|
|
|
end
|