2015-04-03 16:48:37 +00:00
|
|
|
class ApiTokenRegistrator
|
|
|
|
|
|
|
|
def initialize(app)
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
2015-04-16 10:24:29 +00:00
|
|
|
request = Rack::Request.new(env)
|
2015-04-03 16:48:37 +00:00
|
|
|
auth = Rack::Auth::Basic::Request.new(env)
|
|
|
|
|
2015-04-16 10:24:29 +00:00
|
|
|
if request.post? && request.path == '/api/asciicasts'
|
|
|
|
if auth.provided? && auth.basic? && auth.credentials
|
|
|
|
ensure_user_with_token(*auth.credentials)
|
|
|
|
end
|
2015-04-03 16:48:37 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
@app.call(env)
|
2015-04-04 17:57:34 +00:00
|
|
|
|
|
|
|
rescue ActiveRecord::RecordInvalid
|
|
|
|
[401, { 'Content-Type' => 'text/plain' }, 'Invalid token']
|
2015-04-03 16:48:37 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def ensure_user_with_token(username, token)
|
|
|
|
unless ApiToken.where(token: token).exists?
|
|
|
|
ApiToken.create_with_tmp_user!(token, username)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|