AngularJS: Use devise with multiple models

前端 未结 2 1836
悲哀的现实
悲哀的现实 2021-01-14 15:44

I have a rails app using devise with 2 different models corresponding to vastly different roles (no STI - different models altogether).

I am planning to move to fron

2条回答
  •  自闭症患者
    2021-01-14 16:11

    I would suggest that you rethink your problem pretending that devise and angular have nothing to do with each other.

    Let's assume that you're not going to render any html templates in rails. You're just going to use rails to create a json api http://railscasts.com/episodes/350-rest-api-versioning?view=asciicast, and the interface for the app is going to be a single page angular app. UI routing will all be done from within your angular app.

    1. You create a sign in route in your angular app, it has a form pointing to your server's devise sign-in route /api/v1/user/sign-in.
    2. When a user hits submit on the form angular can do some front end validation and send the data to your server.
    3. In your rails controller devise will authenticate who this person is, after devise authenticates them your server route should send back the user's information as a json response (or the error messages).

    The angular service which made the request to your devise endpoint will now have access to the user's information (from the server's json response). It can check properties on this user object like their role, and then it can use angular's location service to change the route to wherever this role should go.

    When the route changes angular will render the route's view and everything will continue on its merry way.

    If you need to change the UI within a route based on the role see this question RESTful Authorization in the UI

    When the user comes back to your site later you can make the angular app detect that they're still logged in. The angular service that you wrote to to sign a user in can also be responsible for attempting to get the current user, and if there is none, redirect to the sign in page.

    Devise gives you a helper called current_user which will give you access to an instance of the user that is logged in. You should create a server route like /api/v1/current_user and have it return the users information. If the user is logged in, redirect to their home page just like after a sign in. Otherwise redirect to the sign in page.

    If you don't know angular very well I'd suggest that you spend some time on this site https://egghead.io/

    Also you may need to to implement authorization logic on the server http://railscasts.com/episodes/192-authorization-with-cancan

提交回复
热议问题