0

On my ruby on rails 4.2 app, I am using Devise to authenticate (sign in and sign up) users. Let's take an example: when a user signs ups, for example, he's automatically redirected to the homepage as a signed-in user.

I need to provide for the case of users who would have cookies (and other Web storage) blocked or deactivated.

Today, if it is the case and cookies are blocked, when he signs up on my sign-up page, he will still be redirected to the homepage but he won't be signed-in: devise fails to work.

How can Rails identify server-side that cookies are disabled so that I can show a nice message to the user after he submits the signup/in form such as "please activate cookies to proceed".

I would like a clean solution that integrates well with Devise (vs some front end detection that need to be passed from javascript to the server and seems like a "dirty" hack :-).

Note: This is the strategy used by Google by the way even if for them it takes place in a 2-step form.

MZaragoza
  • 10,108
  • 9
  • 71
  • 116
Mathieu
  • 4,587
  • 11
  • 57
  • 112
  • See if this helps: https://stackoverflow.com/questions/531393/how-to-detect-server-side-whether-cookies-are-disabled – jdgray Dec 21 '17 at 01:32
  • Thanks but the SO link you provide is really general http-request and javascript. My question was how to deal with this issue within the context of the Rails framework and Devise specifically. – Mathieu Dec 21 '17 at 07:58

1 Answers1

1

I have not found a way to do this in rails but there is a simple way to do it with JS. You can use Javascript to accomplish this.

Library:

# make sure to incclude this file in app/assets/javascripts/application.js.coffee
#app/assets/javascripts/cookie.js.coffee
createCookie = (name, value, days) ->
  expires = undefined
  if days
    date = new Date
    date.setTime date.getTime() + days * 24 * 60 * 60 * 1000
    expires = '; expires=' + date.toGMTString()
  else
    expires = ''
  document.cookie = name + '=' + value + expires + '; path=/'
  return

readCookie = (name) ->
  nameEQ = name + '='
  ca = document.cookie.split(';')
  i = 0
  while i < ca.length
    c = ca[i]
    while c.charAt(0) == ' '
      c = c.substring(1, c.length)
    if c.indexOf(nameEQ) == 0
      return c.substring(nameEQ.length, c.length)
    i++
  null

eraseCookie = (name) ->
  createCookie name, '', -1
  return

areCookiesEnabled = ->
  r = false
  createCookie 'testing', 'Hello', 1
  if readCookie('testing') != null
    r = true
    eraseCookie 'testing'
  r

Code to run:

alert(areCookiesEnabled());

This only works if Javascript is enabled!

MZaragoza
  • 10,108
  • 9
  • 71
  • 116