2017-01-16 1 views
0

Tout ce que je veux faire est d'avoir un Angular sur le front-end connecter à un api de rails pour enregistrer/connecter un utilisateur. J'ai besoin d'aide pour m'authentifier. Une gemme CORS a été installée sur les rails api. S'il y a de bons passe-partout ou de bons documents, veuillez envoyer des liens! Merci d'avance!Comment enregistrer un utilisateur, en utilisant Angular.js, puis en se connectant à une API Rails?

Connexion partielle:

<form name="regField" ng-submit="create(user, regField.$valid)" novalidate> 
<fieldset> 
    <legend>Register</legend> 
    <label>Username<input type="text" ng-model="user.username" required></label> 
    <label>PW<input type="password" ng-model="user.password" required></label> 
    <label>PW confirm<input type="password" ng-model="user.pw_confirm" required></label> 
    <button>Submit</button> 
</fieldset> 

Connexion Contrôleur:

app.controller('loginController', ['$scope','$location','userFactory', function($scope, $location, UserFactory){ 
$scope.loginErr = ""; 
$scope.regErr = ""; 
// UserFactory.allAppointments(); 
$scope.create = function(user, isValid){ 
    if(isValid){ 
     UserFactory.create(user,function(res){ 
      if(res.data.duplicate){ 
       $scope.regErr = "Username must be unique"; 
      } else { 
       $location.url('/dashboard'); 
      } 
     }) 
    } else{ 
     $scope.regErr = "Invalid Combination"; 
    } 
} 
$scope.login = function(user, isValid){ 
    if (isValid){ 
     UserFactory.login(user,function(){ 
      $location.url('/dashboard'); 
     }) 
    } else { 
     $scope.loginErr = "Invalid Combination"; 
    } 
} 
}]) 

UserFactory:

app.factory('userFactory', ['$http', function($http){ 
var currentUser = {}; 
return { 
    getCurrentUser: function(callback){ 
     $http({ 
      method: "GET", 
      url: "/currentUser" 
     }).then(function(user){ 
      currentUser = user; 
      callback(user.data); 
     }) 
    }, 
    create:function(user, callback){ 
     $http({ 
      method:"POST", 
      url:"https://nameofapp.herokuapp.com/api/v1/auth", 
      dataType:'json', 
      headers: { 
       'Content-Type': 'application/json' 
      } 
     }).then(function(user){ 
      currentUser = user; 
      callback(user); 
     }) 
    }, 
    login:function(user,callback){ 
     $http({ 
      method:"POST", 
      url:"/login", 
      data:user 
     }).then(function(user){ 
      currentUser = user; 
      callback(user); 
     }) 
    }, 
    logout: function(callback){ 
     $http({ 
     method:"GET", 
     url:'/logout' 
     }).then(callback) 
    } 
} 
}]) 
+0

vous pouvez essayer https://github.com/rjurado01/rails_jwt_auth – drinor

Répondre