Looking for a way to utilize a Devise user account in an unconfirmed or locked state for AJAX interactions?

Currently, I am attempting to integrate the devise views utilizing JS to manage the responses. While I aim to utilize the default devise error messages, I am facing difficulty in isolating individual types of errors such as unconfirmed or locked accounts due to warden.authenticate. As a workaround, I have implemented a 'caught' mechanism to prevent the occurrence of a 406 or similar Error.

My primary issue lies in determining the corresponding symbol for a 'locked' state. Despite knowing that "caught[:message] == :unconfirmed" can provide the 'unconfirmed' state of the user, I am unsure of the appropriate symbol for 'locked'. The ":locked" symbol does not offer the desired outcome, and I am unable to locate relevant documentation.

My Sessions_controller is structured as follows:

def create
    caught = catch(:warden) do
        self.resource = warden.authenticate :scope => resource_name
    end
    if resource 
        # User is confirmed
        sign_in(resource_name, resource)
        puts "LOGGED IN!!!"
        respond_to js{
            set_flash_message(:success, :signed_in)
            render :template => "remote_content/flashes.js.erb"
            flash.discard
        }
    elsif caught and caught[:message] == :unconfirmed
        # User is unconfirmed
        puts "UNCONFIRMED ACCOUNT!!!"
        # send the email or display the flash with a link to send an email
        respond_to js{
            set_flash_message(:error, :problem)
            render :template => "remote_content/form_flashes.js.erb"
            flash.discard
        }
    else
        # User is not signed in, potentially due to error in credentials or a locked account
        puts "ERROR IN CREDENTIALS!!!"
        respond_to js{
            set_flash_message(:error, :invalid)
            render :template => "remote_content/form_flashes.js.erb"
            flash.discard
        }
    end
end

Fortunately, the flashes.js.erb/form_flashes.js.erb function effectively without any issues. Here is a snippet of their functionality:

$('.modal').modal('hide');
// append flash messages to the body
$('.body').append("<%= escape_javascript raw(flash_normal) %>");

What are your thoughts on my approach? Would it be more suitable to implement a CustomFailure instead? I am unable to locate any examples of a CustomFailure or the original Devise method to integrate with my JS files.

Answer №1

After examining the caught variable, I discovered that the message was always unconfirmed and never reached the unlocked state. This led me to retrieve the User by their email and utilize the devise helper access_locked? to obtain more information about their account. Although it may pose a security risk, if an account is locked, there is little that can be done with it. Below is the missing portion of the code:

  ...
  else
  ## User is not signed in, should be... error in credentials or locked...
  ## Let's see if it's locked

  # This function is only utilized in this manner (without any security measures)
  # when authentication has already failed in the current action
  # yet we still need to retrieve the user to determine if it is locked

  user = User.find_by email: params[:user][:email]
  if !user.nil? and user.access_locked?
    # A minor flaw: it is possible for anyone to determine if an email is locked without entering a password
    puts "ACCOUNT LOCKED!!!"
    respond_to js{
        set_flash_message(:error, :locked)
        render :template => "remote_content/form_flashes.js.erb"
        flash.discard
      }
  else
    ## If it's not Locked, then there is an error in credentials
    puts "ERROR IN CREDENTIALS!!!"
    respond_to js{
        set_flash_message(:error, :invalid)
        render :template => "remote_content/form_flashes.js.erb"
        flash.discard
      }
  end
end

I acknowledge that it may not be the most elegant solution, but it gets the job done.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preventing CSRF Attacks in CodeIgniter Using AJAX and Form Submission - Issue with Sending Data

I initially disabled my CSRF protection for the sake of simplicity to get my form and AJAX functionality working smoothly. However, now that I have enabled it and attempted to implement CSRF tokens in my inputs, nothing seems to be functioning correctly. M ...

For the past 8 hours, my main focus has been on successfully transmitting a basic JSON object containing data from an API from my Express backend to a React component

I have been trying to achieve my initial goal of retrieving data from the API I am using on the backend, inserting that data into my database, and then sending that data through res.json so it can be accessed on the frontend via fetch. Despite all my attem ...

React and Redux Toolkit collaborated to create a seamless shared state management system,

Currently, I am developing a simple application to experiment with Redux Toolkit alongside React. Despite being able to view the object in the Redux Chrome tab, I am facing difficulties accessing it using React hooks within components. The code for my sli ...

What is the best way to execute AJAX requests in a loop synchronously while ensuring that each request is completed

I am looking to implement an AJAX loop where each call must finish before moving on to the next iteration. for (var i = 1; i < songs.length; i++) { getJson('get_song/' + i).done(function(e) { var song = JSON.parse(e); addSongToPlayl ...

Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs. Currently, I have managed to assign backg ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...

The error message "404 Not Found" was triggered when attempting to deliver the

Here is the server-side code snippet that I am using: var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile( ...

Unable to maintain active status on Vuejs (PrimeVue) Sidebar component leads to malfunction

I currently have a PrimeVue Sidebar component set up with a dynamic component being passed to it. At the moment, I am only using a single component to test this functionality. <Sidebar v-model:visible="sidebarState" :baseZIndex="1000" ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

Retrieving the value of a JavaScript variable from an HTML document using Python

I am looking to extract the value of myJSONObject from an HTML document that includes javascript code with a JSON object. Here is an example snippet: <html> <head> </head> <body> <script type="text/javascript"> ...

Issue with JQuery Each function not waiting for the inner function to complete

When I have this section inside an ajax function $.each(data['Result'][0], function(Key, Value) { InputGen(Value['Type'], Value['Name'], Value['Other'], Value['Value'], function(Html){ Table = ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

JavaScript encountered an error stating "phone is not defined" due to an uncaught ReferenceError

Whenever I click on the Phone Number, it displays an error message saying that the function is not defined. How can I fix this issue? Thank you in advance! Here's the code snippet: <div class="product-label"> <h4><?php echo $p["Fu ...

Steps for eliminating double quotes from the start and end of a numbered value within a list

I currently have the following data: let str = "1,2,3,4" My goal is to convert it into an array like this: arr = [1,2,3,4] ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

Assign specific CSS classes to elements based on the v-model value in Vue.js

Looking to create a dynamic table using Vue and trying to add a class to a row when a checkbox is checked. Each checkbox is associated with a specific value in an object of objects. View the code on Codepen. <tbody> <tr v-for="row in filter ...

When executing a function, the previous React state continues to linger

Why is the updateUser() function only updating the last user instead of all users despite using useCallback and including users as a dependency? The expected output after clicking the update button should be: {"id":1,"name":"John& ...

Is the AJAX call returning JSON data?

Currently, I am utilizing AJAX technology to scrape player names and their respective ratings from a website. The approach I have chosen involves having AJAX return a JSON object which is then manipulated using jQuery to append each element of the JSON obj ...

Tips for preventing a page from automatically scrolling to the top after submitting a form

Recently, I set up a form where users can input values. The form is set to submit either on change or when the user hits enter, depending on which value they want to update. However, after the values are submitted, the page automatically jumps back to the ...