Created
July 22, 2019 00:45
-
-
Save faustoct1/51d81aea46d94e2909950fe793837cab to your computer and use it in GitHub Desktop.
handle distributed user session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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