Unable to destroy session/logout in Rails

Viewed 280

I am trying to learn Rails API with React front end and have created a login, signup and logout feature. Currently, I am using localstorage to check if a user is signed in or registered. If the value is true, the logout button appears, and clicking logout empties the localstorage and sets the value to false. But I think this isn't the correct way of doing it since rails devise has its own session and logout endpoint. I tried writing some code for the destroy session and when testing it using the endpoint in POSTMAN it doesn't seem to work the way I want.

Here's the code:

class API::V1::SessionsController < Devise::SessionsController
  def create
    @user = User.find_by_email(user_params[:email])
    if @user && @user.valid_password?(user_params[:password])
      session[:user_id]=@user.id
      sign_in :user, @user
      render json: @user
    elsif @user && not(@user.valid_password?(user_params[:password]))
      invalid_attempt
    else
      no_user
    end
  end



   def destroy
    puts "logout clicked"
    @user = User.find_by_email(user_params[:email])
    if @user.valid_password(user_params[:password]) && @user.destroy
      render :json => { success: "user was successfully deleted" }, :status => 201
    else
      render :json => { error: "user could not be deleted" }, :status => 422
    end
  end

  private

  def no_user
    render json: {error: "An account with this email doesn't exist. Please create a new one"}, status: :unprocessable_entity
  end

  def invalid_attempt
    render json: { error: "Your password isn't correct" }, status: :unprocessable_entity
  end

  def user_params
    params.require(:user).permit(:email, :password)
  end
  end

http://localhost:3000/users/sign_out

{
    "user":{
        "email":"test1@test.com",
        "password":"test1@test.com"
    }
}

Please note that this user does exist. Sending a delete request to http://localhost:3000/users/sign_out isn't even logging the "logout clicked" and the status gives 204.

0 Answers
Related