We've moved discussions to Discord

API endpoints for authentication and registration

G Theivendran
Hi everyone,

I'm using Jumpstart to setup api endpoints for authentication and registration.  Jumpstart comes with `POST /api/v1/users` for registration, but I was wondering if anyone has already created endpoints for sign in, sing out, forgot password etc..?  Is there any best practices I should be aware of when doing this with Devise?

I am also a complete Rails newbie so apologies in advance if this is a dumb question!

- G
Chris Oliver
With APIs, there's no such thing as "sign in" or "sign out" because you always submit the API key with the request. They're always signed in because of the token in the request. 👍

For example, if you're building a mobile app to talk to the API, you create the user via the API and save the token on the device. When the token exists on the device, then you're logged in and can make API requests. If you delete the token from the device, you're "logged out" since you can't authenticate API requests anymore.
G Theivendran
Right, but how would you handle the case when they've logged out and want to log back in? How would you verify their email/password, and send them an api token once again to save on the device?
Chris Oliver
You can add an API route that accepts an email and password and looks up the user and verifies their password.

The code would be simple. Something like this:

def login
  user = User.find(params[:email])
  if user.valid_password?(params[:password])
    render json: { token: user.tokens.first_or_create_by(name: Jumpstart.config.application_name) }
  else
    head :unauthorized
  end
end

Our API implementation is simple right now and doesn't have that. I might add that to the template as that's definitely useful / missing. 
G Theivendran
I'm assuming it would be an endpoint like `api/v1/sessions/create`? so essentially a sessions controller for the api?  
Chris Oliver
You could name it that, sure. It's not really a session, so maybe you want to call it like /api/v1/auth or /api/v1/token?
G Theivendran
That makes sense, thank you!
Chris Oliver
Here's a draft of it that I tested and works nicely:

class Api::V1::AuthsController < Api::BaseController
  skip_before_action :authenticate_api_token!

  # Requires email and password params
  # Returns an API token for the user if valid
  def create
    user = User.find_by(email: params[:email])
    if user&.valid_password?(params[:password])
      render json: {
        token: user.api_tokens.find_or_create_by(name: "default").token
      }
    else
      head :unauthorized
    end
  end
end
G Theivendran
This is helpful, thank you!
Chris Oliver
I just published an update that includes an auth controller in the API for you. 👍
Leonard Bogdonoff
I am using this to use a React front end app that is connected to the rails app. Thank you  Chris Oliver  
Notifications
You’re not receiving notifications from this thread.