Skip to content

Instantly share code, notes, and snippets.

@faustoct1
Created July 22, 2019 00:45
Show Gist options
  • Save faustoct1/51d81aea46d94e2909950fe793837cab to your computer and use it in GitHub Desktop.
Save faustoct1/51d81aea46d94e2909950fe793837cab to your computer and use it in GitHub Desktop.
handle distributed user session
def auth_user user=nil
#token = JWT.decode(params[:token], hmac_secret, true, { :algorithm => 'HS256' })
token = request.env["HTTP_TOKEN"]
halt 401, "token + user are nil" if (token.blank? && user.blank?)
@user ||= CACHE.get(token)
unless @user.blank?
halt 400, "existent user for a blank token" if token.blank?
@user = JSON.parse(@user,:symbolize_names => true)[:user]
return @user
end
if @user.blank?
if user.blank?
halt 401
else
token = JWT.encode({uid: user.id.to_s, expires_in: 'never'}, HMAC_SECRET, 'HS256')
_user = {
id: user.id.to_s,
username: user.username,
name: user.name,
}
CACHE.set(token,{user: _user}.to_json)
@user = _user
end
end
@user
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment