15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# File 'app/openbel/api/middleware/auth.rb', line 15
def self.check_token(env)
cookie_hdr = env['HTTP_COOKIE']
auth_hdr = env['HTTP_AUTHORIZATION']
req = Rack::Request.new(env)
token_param = req.params['token']
if cookie_hdr.nil? && auth_hdr.nil? && token_param.nil?
raise 'missing authorization cookie, header, or parameter'
end
unless cookie_hdr.nil?
cookies = cookie_hdr.split('; ')
selected = cookies.select { |x| x.start_with?('jwt=') }
unless selected.empty?
tokens = selected[0].split('=')
token = tokens[1] if tokens.size > 1
end
end
unless auth_hdr.nil?
tokens = auth_hdr.split('Bearer ')
raise 'malformed authorization header' if tokens.size != 2
token = tokens[1]
end
token = token_param unless token_param.nil?
secret = OpenBEL::Settings[:auth][:secret]
pubkey = OpenSSL::PKey::RSA.new(secret)
verify = true
options = { :algorithm => 'RS256' }
begin
decoded_token = decode(token, pubkey, verify, options)
rescue ::JWT::VerificationError => ve
puts ve.inspect
raise 'invalid authorization token'
rescue ::JWT::DecodeError => je
puts je.inspect
raise 'malformed authorization token'
end
env['jwt.header'] = decoded_token.last unless decoded_token.nil?
env['jwt.payload'] = decoded_token.first unless decoded_token.nil?
exp = env['jwt.payload']['exp']
now = Time.now.to_i
raise 'token expired' if now > exp
env['email'] = env['jwt.payload']['email']
end
|