<div>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" th:href="@{/}">Spring Security OAuth</a>
    </div>
    
  </div><!-- /.container-fluid -->
</nav>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-resource.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-cookies.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.9/ngStorage.min.js"></script>


<script th:src="@{/resources/angular-utf8-base64.min.js}"></script>
<script>
/*<![CDATA[*/
var app = angular.module('myApp', ["ngResource","ngRoute","ngCookies"]);

app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,$cookies) {
	$scope.foo = {id:0 , name:"sample foo"};
	$scope.foos = $resource("http://localhost:8081/spring-security-oauth-resource/foos/:fooId",{fooId:'@id'});
    
	$scope.getFoo = function(){
		$scope.foo = $scope.foos.get({fooId:$scope.foo.id});
	}
	
    $scope.data = {grant_type:"password", username: "", password: "", client_id: "clientIdPassword"};
    $scope.encoded = btoa("clientIdPassword:secret");
    
    var isLoginPage = window.location.href.indexOf("login") != -1;
    if(isLoginPage){
    	if($cookies.get("access_token")){
            window.location.href = "index";
        }else{
            $http.defaults.headers.common.Authorization= 'Basic ' + $scope.encoded;
        }
    }else{
    	if($cookies.get("access_token")){
    		$http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token");
    	}else{
    		window.location.href = "login";
    	}

    }
    
    $scope.login = function() {   
     	var req = {
            method: 'POST',
            url: "http://localhost:8081/spring-security-oauth-server/oauth/token",
            headers: {
                "Authorization": "Basic " + $scope.encoded,
                "Content-type": "application/x-www-form-urlencoded; charset=utf-8"
            },
            data: $httpParamSerializer($scope.data)
        }
        $http(req).then(
        		function(data){
        			   $http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token;
        			   $cookies.put("access_token", data.data.access_token);
        			   window.location.href="index";
        	    },function(){
        	    	console.log("error");
        	    });   
   } 
    
});
/*]]>*/
</script>
</div>