API endpoints for authentication and registration

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
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

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.
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.


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:
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.



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
Notifications
You’re not receiving notifications from this thread.