Get the current user as Json with Devise

263 views
Skip to first unread message

Linus Pettersson

unread,
Jul 30, 2011, 9:27:53 AM7/30/11
to rubyonra...@googlegroups.com
Hi!

I use Devise and Basic HTTP Authentication to access user areas from a mobile app. When the user enters its details in the app and it tries to "login" (you don't actually login with basic auth as you send the credentials with each request) I want to get a response back with the user info, like user ID, email (not password) etc.

- So, is there a way to do this out of the box with Devise?


If not I guess I could just create a "login" controller with an "index"-action that just has:

before_filter :authenticate_user!
respond_to :json
...
  respond_with current_user
...

So when I do a request from my app to http://example.com/login/ Devise will return an error by default if the username and password are incorrect, and if the credentials are correct it outputs the user object as JSON.


Are there any issues with the approach above?

Linus Pettersson

unread,
Jul 30, 2011, 11:19:42 AM7/30/11
to rubyonra...@googlegroups.com
Actually, the user is outputted when accessing other resources, I can work with that :)

One issue, I want the user object to also show the user ID. Now it only shows the email and username. It renders the json like this:

[
  • -
    {}
  • -
    [
    • -
      {
      • created_at: "2011-07-26T11:30:55Z"
      • id: 1
      • title: "Test"
      • updated_at: "2011-07-26T11:30:55Z"
      • user_id: 1
      }
    • -
      {
      • created_at: "2011-07-26T16:53:26Z"
      • id: 2
      • title: "Test2"
      • updated_at: "2011-07-26T16:53:26Z"
      • user_id: 1
      }
    ]
]


I can't use the user_id in the items because if the user don't have any items it would not be displayed.

Any tips?

Linus Pettersson

unread,
Jul 30, 2011, 12:07:03 PM7/30/11
to rubyonra...@googlegroups.com
Ok. Adding attr_accessible :id to my model works. But is it safe to do it like this?
Reply all
Reply to author
Forward
0 new messages