Skip to content

Instantly share code, notes, and snippets.

@faustoct
Created Jul 22, 2019
Embed
What would you like to do?
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