Синатра JWT 4.90 с TTFB латентность - PullRequest
1 голос
/ 16 января 2020

Здравствуйте, после установки простого аутентификации, с проверочным токеном после входа в систему, Sinatra занимает в среднем 4. несколько секунд, чтобы проверить токен. На Rails TTFB берет всего несколько миллисекод, используя тот же самый драгоценный камень. поэтому я попытался изменить json на обычный текст и все еще занимал слишком много времени! Является ли jwt config?

middleware
JwtAuth

# frozen_string_literal: true

class JwtAuth
  def initialize(app)
    @app = app
  end

  def call(env)
    begin
    auth_token = env.fetch('HTTP_AUTHORIZATION', '')

    payload = JsonWebToken.decode(auth_token)

    unless User.exists?(email: payload['user']['email'])
      raise JWT::InvalidPayload
     end

    #raise JWT::InvalidPayload unless User.exists?(email: payload['user']['email'])
    env[:user] = User.find_by(email: payload['user']['email'])


    # puts headers # show headers on this request

    @app.call env
  rescue JWT::DecodeError
    [401, { 'Content-Type' => 'text/plain' }, ['A token must be passed.']]
  rescue JWT::ExpiredSignature
    [403, { 'Content-Type' => 'text/plain' }, ['The token has expired.']]
  rescue JWT::InvalidIssuerError
    [403, { 'Content-Type' => 'text/plain' }, ['The token does not have a valid issuer.']]
  rescue JWT::InvalidIatError
    [403, { 'Content-Type' => 'text/plain' }, ['The token does not have a valid "issued at" time.']]
  rescue JWT::InvalidIatError
    [403, { 'Content-Type' => 'text/plain' }, ['Invalid token']]
  end
  end
end
the JsonWebToken

class JsonWebToken
  class << self
    def encode(email)

      JWT.encode payload(email), ENV['JWT_SECRET'], 'HS256' 
    end

    def decode(auth_token)
      options = { algorithm: 'HS256', iss: ENV['JWT_ISSUER'] }

      JWT.decode(auth_token, ENV['JWT_SECRET'],  true, options)[0]
    end

    def payload(email)
      {
        exp: 24.hours.from_now.to_i,
        iat: Time.now.to_i,
        iss: ENV['JWT_ISSUER'],
        user: {
          email: email
        }
       # user_id: user.id
      }
    end
  end
end

ApiController

class ApiController < Sinatra::Base
  use JwtAuth
  before do
    content_type :json, charset: 'utf-8'
  end




  get '/verify' do
    # add token to Authorization Header

    auth_token = JsonWebToken.encode(@email)

    if auth_token
      {  message: 'verified',tatus: 200 }.to_json

    else
      halt 401, { message: 'Token failed verification' }.to_json

    end
  end

  def current_user
    @current_user ||= request.env[:user]
  #  request.env[:user]
  end
end
config.ru

use Rack::Deflater
use Rack::MethodOverride


run Rack::URLMap.new(
  '/' => PublicController,
  '/api' => ApiController

)

enter image description here

...