1

So in my angular js app in service called 'authService' I have the following resources:

var userAreaLogin = $resource('/api/user_area/login');
var userAreaSignup = $resource('/api/user_area/signup');
var session = $resource('/api/user_area/getSession');
var userAreaLogout = $resource('/api/user_area/logout');

but this doesn't feel quite right, I'm using only the get methods, for example:

this.login = function(credentials) {
    var user = userAreaLogin.get(credentials, function() {
        ...
    });
};

this.signup = function(userInfo) {
    var signup = userAreaSignup.get(userInfo, function() {
        ...
    });
};

I'm confused about what resources to use, should I have something like this?

var session = $resource('/api/user/session');
var userArea = $resource('/api/user');

userArea.get(credentials); //should login the user?
userArea.post(credentials); //should signup the user?
session.delete(); //should logout the user?
session.get(); //should get the sessions of the logged user if any?
nacholibre
  • 3,874
  • 3
  • 32
  • 35

2 Answers2

0

By REST sessions are maintained by the client and not by the service. You should use HTTPS and send the username and password with every request (for example with HTTP basic auth headers) instead of using session cookies... (stateless constraint)

Ofc. on the client side you can have login and logout which will change the content of the auth headers sent via AJAX.

inf3rno
  • 24,976
  • 11
  • 115
  • 197
  • Why send auth headers with every request instead of keeping logged user on the server side in the session? That way I dont need to pass the credentials every time, only on login. – nacholibre Jun 02 '14 at 09:39
  • Because your service won't scale if it maintains the client state. That's why RESTful web services are stateless by default. – inf3rno Jun 02 '14 at 09:51
  • http://stackoverflow.com/questions/3105296/if-rest-applications-are-supposed-to-be-stateless-how-do-you-manage-sessions – inf3rno Jun 02 '14 at 09:53
  • Btw in your case you probably won't serve millions of users, so I don't think having a REST service is worth the effort. It may take years (at least by me 1-2 year) to learn how to do it properly... – inf3rno Jun 02 '14 at 09:57
-1

You are going to the right direction. In a well designed REST API you should have something like this.

POST   /users/sign_in      # Create a user session (signs in)
DELETE /users/sign_out     # Delete a user session (signs out)
POST   /users              # Create a new user resource
GET    /users/:id          # Get the user resource

Based on these API you can then define your services. I also suggest to use $http which is cleaner, although you'll write few lines of code more.

# Session related methods
Session.create
Session.delete

# User related methods
User.create
User.get

Hope this makes things clearer.

Andrea Reginato
  • 1,338
  • 1
  • 17
  • 23