I am making rails api authentication using devise but could not understand properly what sign_in of devise is doing for us.
I have session controller with create method for sign in a user.
def create
user_email = params[:session][:email]
user_password = params[:session][:password]
user = user_email.present? && User.find_by(email: user_email)
if user.valid_password?(user_password)
sign_in user, store: false /* exactly this line */
render json: user, status: 200, location: [:api, user]
else
render json: { errors: "Invalid email or password" }, status: 422
end
end
On rubydoc its description is written like this
Sign in a user that already was authenticated. This helper is useful for logging users in after sign up. All options given to sign_in is passed forward to the set_user method in warden.
But it is not clear to me. Thanks.
Devise is an excellent authentication system made for Rails that allows us to easily drop-in User functionality into our project. Devise only includes an email and password for registration, let's also add our own username to our User model. We also want to have a unique index on our username.
current_user works by storing id of current user in the application session. Most commonly session is stored in cookies. Whether or not the cookies survive browser restart depends on client's browser settings.
Devise is a well known solution for authentication in Rails applications. It's full featured (it not only adds authentication but also password recovery, email changing, session timeout, locking, ip tracking, etc.) and can be expanded to add even more (like JWT authentication).
Devise uses the session storage that Rails is configured to. So it depends on which session storage you will use in your app, not on Devise. If you want to store the session data in the database, then yes, you need to tell Rails about that and run the Rails generator that creates the database table for you.
sign_in
is for when you already have a User
object that you created or loaded/authenticated yourself and thus want to store in the session as the authenticated user for the rest of the current as well as upcoming requests.
If you look at the source code for the default Devise SessionsController
you'll see that it also uses sign_in
to log in a user.
Devise is a layer over warden, so you might want to look at its documentation to understand this level of functionality. As the Devise documentation you quoted states, sign_in
just calls the set_user
method from warden. What Devise adds on top is a lot of convenience like the ability to work with multiple scopes and various warden authentication strategies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With