Reimplementing Rails’ CSRF protection in Sinatra

CSRF?

My app

A screenshot of my online version of the game Snatch
A screenshot of my work-in-progress app
ws.send(JSON.stringify({
action: 'word',
room: '2',
handle: 'my arch nemesis',
word: 'floccinaucinihilipification' }));
module Snatch
class App < Sinatra::Base
enable :sessions
use Snatch::SnatchBackend
# ...
end
end
get '/' do
create_authenticity_token
erb :"index.html"
end

private

def create_authenticity_token
@authenticity_token = rand().to_s
session[:authenticity_token] = @authenticity_token
end
ws.send(JSON.stringify({
authenticity_token: '0.123456789',
action: 'word',
room: '2',
handle: 'my arch nemesis',
word: 'floccinaucinihilipification' }));
module Snatch
class SnatchBackend
...



def call(env)
@session = Rack::Request.new(env).session

if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env, nil, { ping: KEEPALIVE_TIME })

...

ws.on :message do |event|
@data = JSON.parse(event.data).transform_values { |value| ERB::Util.html_escape(value) }

if authenticated?
initialize_room if @redis.hget(room_key, 'tiles').nil?
perform_any_actions

@redis.publish(CHANNEL, JSON.generate(data_to_publish))
end
end
...
end
end

private

def authenticated?
@session['authenticity_token'] == data['authenticity_token']
end

...
end
end

It’s not exactly Rails

  • Aforementioned cryptography
  • I’m not resending the session cookie with each request (I think?), because I’m not using HTTP. So the session data used in SnatchBackend is probably unchanged since the most recent page load.

Questions to investigate further

--

--

--

This is my programming blog. www.github.com/david-mears

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Trade Safe? Key tips for to protect yourself from losing money.

Making Solid Profits with Crypto Trading Bots

OolongSwap Airdrop (Potential)

How Are You So Easy to Find on the Internet?

{UPDATE} Игра 4 картинки 1 слово Hack Free Resources Generator

CORONA CRYPTO AIRDROP

Claim your CSM from ERC20 to Crust Shadow

SpiderDAO Announces first public Pro Connect router firmware test

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Mears

David Mears

This is my programming blog. www.github.com/david-mears

More from Medium

BLOG APPLICATION WITH AN MVC DESIGN PATTERN AND CRUD OPERATIONS.

Bridge Design Pattern — StudySection Blog

Bridge Design Pattern — StudySection Blog

Restful Api’s

Using Sessions with Sinatra in Web Apps