Created
August 8, 2014 09:49
-
-
Save stabenfeldt/8077a4c76a59546292b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app = angular.module("trenger") | |
app.controller 'SessionCtrl', ['$scope', '$http', '$window', '$localStorage', '$q', | |
($scope, $http, $window, $localStorage, $q) -> | |
$scope.current_user = JSON.parse($("meta[name='current_user']").attr('content')) | |
$scope.authErrors = [] | |
defer = $q.defer() | |
$scope.token = $localStorage.token | |
$scope.authorized = () -> | |
$scope.current_user? and $scope.current_user._id? and $localStorage.token? | |
getUserToken = (username, password) -> | |
params = { grant_type: "password", username: username, | |
password: password, client_id: "<%= ENV['TRENGER_CLIENT_ID'] %>", | |
client_secret: "<%= ENV['TRENGER_CLIENT_SECRET'] %>" } | |
$http( | |
method: "POST" | |
url: "/oauth/token" | |
params: params | |
).success((data, status, headers, config) -> | |
$localStorage.token = data.access_token | |
$http.defaults.headers.common.Authorization = \ | |
"Bearer #{data.access_token}" | |
).error (data, status, headers, config) -> | |
$scope.signIn = (data) -> | |
defer.promise | |
.then( getUserToken($scope.email, $scope.password) ) | |
.then( deviseLogin() ) | |
deviseLogin = () -> | |
$scope.authErrors = [] | |
authData = { user: { email: $scope.email, password: $scope.password }} | |
$http( | |
# Perform a regular Devise login | |
method: "POST" | |
url: "/users/sign_in" | |
data: authData | |
) | |
.success (data) -> | |
$window.location = data.url unless data.url == '/users/sign_in' | |
$scope.signOut = () -> | |
$http( url: "/users/sign_out") | |
$scope.current_user = null | |
$localStorage.token = null | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment