For my project, I had the task of setting up a backbone login system in Rails utilizing devise. Unlike typical user registration scenarios, I only needed a single admin user which I manually created through the terminal.
By sending an AJAX post request to the appropriate devise route, the login process is seamlessly handled by devise, provided that the setup process was followed accurately. In Backbone, this post request can be initiated with a new model save function.
Referencing a helpful tutorial, I was able to configure my Backbone model and view. Although the tutorial covered registration functionality, I focused on simplifying my implementation to the essential components.
The creation of a model with a matching urlRoot
corresponding to the devise login route is essential. Most users opting for the standard User model can utilize the urlRoot
route specified below. Please note that my implementation is in coffeescript.
class MyApplication.Models.UserSession extends Backbone.Model
urlRoot: '/users/sign_in.json'
defaults:
email: ""
password: ""
toJSON: ->
{ user: _.clone(@attributes) }
It is crucial to wrap the params within 'user' for devise, necessitating the override of the toJSON
method
In the view, saving the model along with login credentials is all that is required. Although success and failure callbacks may vary, a rudimentary implementation is provided below:
events:
'submit form': 'login'
initialize: =>
@model = new MyApplication.Models.UserSession()
render: =>
$(@el).html( @template() )
@
credentials: ->
{
email: @$('#email').val(),
password: @$('#password').val(),
remember_me: 1
}
login: (event)->
event.preventDefault()
@model.save(@credentials(),
success: (userSession, response) =>
window.location.href = "/"
error: (userSession, response) =>
message = $.parseJSON(response.responseText).error
alert(message)
)
Additionally, this tutorial provides insights on setting up devise ajax authentication.
Upon completing the aforementioned tasks, successful login can be achieved by saving the UserSession
model with correct credentials, as demonstrated in the view. A redirect to the success callback indicates a successful login.
In subsequent controllers within your application, devise helpers like user_signed_in?
and current_user
can be utilized.
(In case of an undefined method error for these helpers despite being logged in, consider adding:
include Devise::Controllers::Helpers
to your controllers).
Lastly, guidance from Alex P's response can assist in effectively implementing the user_signed_in?
boolean in your Backbone views.