hooked up jwt token in angular

This commit is contained in:
Brad Rydzewski 2014-09-30 00:43:50 -07:00
parent 58f287a541
commit 5f950d21c4
22 changed files with 138 additions and 91 deletions

View file

@ -43,7 +43,7 @@ func (r *Bitbucket) Authorize(res http.ResponseWriter, req *http.Request) (*mode
RequestTokenURL: "https://bitbucket.org/api/1.0/oauth/request_token/", RequestTokenURL: "https://bitbucket.org/api/1.0/oauth/request_token/",
AuthorizationURL: "https://bitbucket.org/!api/1.0/oauth/authenticate", AuthorizationURL: "https://bitbucket.org/!api/1.0/oauth/authenticate",
AccessTokenURL: "https://bitbucket.org/api/1.0/oauth/access_token/", AccessTokenURL: "https://bitbucket.org/api/1.0/oauth/access_token/",
CallbackURL: httputil.GetScheme(req) + "://" + httputil.GetHost(req) + "/login/bitbucket.org", CallbackURL: httputil.GetScheme(req) + "://" + httputil.GetHost(req) + "/api/auth/bitbucket.org",
ConsumerKey: r.Client, ConsumerKey: r.Client,
ConsumerSecret: r.Secret, ConsumerSecret: r.Secret,
} }

View file

@ -59,7 +59,7 @@ func (r *GitHub) Authorize(res http.ResponseWriter, req *http.Request) (*model.L
Scope: DefaultScope, Scope: DefaultScope,
AuthURL: fmt.Sprintf("%s/login/oauth/authorize", r.URL), AuthURL: fmt.Sprintf("%s/login/oauth/authorize", r.URL),
TokenURL: fmt.Sprintf("%s/login/oauth/access_token", r.URL), TokenURL: fmt.Sprintf("%s/login/oauth/access_token", r.URL),
RedirectURL: fmt.Sprintf("%s/login/%s", httputil.GetURL(req), r.GetKind()), RedirectURL: fmt.Sprintf("%s/api/auth/%s", httputil.GetURL(req), r.GetKind()),
} }
// get the OAuth code // get the OAuth code

View file

@ -13,14 +13,14 @@
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans" /> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Orbitron" /> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Orbitron" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Droid+Sans+Mono" /> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Droid+Sans+Mono" />
<link rel="stylesheet" href="/styles/drone.css" /> <link rel="stylesheet" href="/static/styles/drone.css" />
</head> </head>
<body ng-controller="MainCtrl" ng-cloak> <body ng-controller="MainCtrl" ng-cloak>
<div id="container"> <div id="container">
<input id="drawer-checkbox" type="checkbox" ng-if="user != undefined" /> <input id="drawer-checkbox" type="checkbox" ng-if="user != undefined" />
<header id="header" ng-include src=" '/views/header.html' "></header> <header id="header" ng-include src=" '/static/views/header.html' "></header>
<aside id="drawer" ng-include src=" '/views/drawer.html' "></aside> <aside id="drawer" ng-include src=" '/static/views/drawer.html' "></aside>
<div ng-view id="body"></div> <div ng-view id="body"></div>
</div> </div>
@ -31,25 +31,25 @@
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.6.0/moment.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.6.0/moment.min.js"></script>
<!-- main javascript application --> <!-- main javascript application -->
<script src="/scripts/line_formatter.js"></script> <script src="/static/scripts/line_formatter.js"></script>
<script src="/scripts/commit_updates.js"></script> <script src="/static/scripts/commit_updates.js"></script>
<script src="/scripts/app.js"></script> <script src="/static/scripts/app.js"></script>
<script src="/scripts/controllers/conf.js"></script> <script src="/static/scripts/controllers/conf.js"></script>
<script src="/scripts/controllers/home.js"></script> <script src="/static/scripts/controllers/home.js"></script>
<script src="/scripts/controllers/repo.js"></script> <script src="/static/scripts/controllers/repo.js"></script>
<script src="/scripts/controllers/user.js"></script> <script src="/static/scripts/controllers/user.js"></script>
<script src="/scripts/controllers/users.js"></script> <script src="/static/scripts/controllers/users.js"></script>
<script src="/scripts/controllers/setup.js"></script> <script src="/static/scripts/controllers/setup.js"></script>
<script src="/scripts/controllers/sync.js"></script> <script src="/static/scripts/controllers/sync.js"></script>
<script src="/scripts/controllers/main.js"></script> <script src="/static/scripts/controllers/main.js"></script>
<script src="/scripts/controllers/login.js"></script> <script src="/static/scripts/controllers/login.js"></script>
<script src="/scripts/services/auth.js"></script> <script src="/static/scripts/services/auth.js"></script>
<script src="/scripts/services/conf.js"></script> <script src="/static/scripts/services/conf.js"></script>
<script src="/scripts/services/repo.js"></script> <script src="/static/scripts/services/repo.js"></script>
<script src="/scripts/services/user.js"></script> <script src="/static/scripts/services/user.js"></script>
<script src="/scripts/services/feed.js"></script> <script src="/static/scripts/services/feed.js"></script>
<script src="/scripts/services/remote.js"></script> <script src="/static/scripts/services/remote.js"></script>
<script src="/scripts/services/stdout.js"></script> <script src="/static/scripts/services/stdout.js"></script>
<script src="/scripts/filters/filters.js"></script> <script src="/static/scripts/filters/filters.js"></script>
</body> </body>
</html> </html>

View file

@ -5,9 +5,10 @@ var app = angular.module('app', [
'ui.filters' 'ui.filters'
]); ]);
app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider) { app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/', { $routeProvider.when('/', {
templateUrl: '/views/home.html', templateUrl: '/static/views/home.html',
controller: 'HomeController', controller: 'HomeController',
title: 'Dashboard', title: 'Dashboard',
resolve: { resolve: {
@ -17,31 +18,31 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/sync', { .when('/sync', {
templateUrl: '/views/sync.html', templateUrl: '/static/views/sync.html',
controller: 'SyncController', controller: 'SyncController',
title: 'Sync' title: 'Sync'
}) })
.when('/login', { .when('/login', {
templateUrl: '/views/login.html', templateUrl: '/static/views/login.html',
controller: 'LoginController', controller: 'LoginController',
title: 'Login', title: 'Login',
}) })
.when('/gitlab', { .when('/gitlab', {
templateUrl: '/views/login_gitlab.html', templateUrl: '/static/views/login_gitlab.html',
title: 'GitLab Login', title: 'GitLab Login',
}) })
.when('/setup', { .when('/setup', {
templateUrl: '/views/setup.html', templateUrl: '/static/views/setup.html',
controller: 'SetupController', controller: 'SetupController',
title: 'Setup' title: 'Setup'
}) })
.when('/setup/:remote', { .when('/setup/:remote', {
templateUrl: '/views/setup.html', templateUrl: '/static/views/setup.html',
controller: 'SetupController', controller: 'SetupController',
title: 'Setup' title: 'Setup'
}) })
.when('/account/profile', { .when('/account/profile', {
templateUrl: '/views/account.html', templateUrl: '/static/views/account.html',
controller: 'UserController', controller: 'UserController',
title: 'Profile', title: 'Profile',
resolve: { resolve: {
@ -51,7 +52,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/account/repos', { .when('/account/repos', {
templateUrl: '/views/repo_list.html', templateUrl: '/static/views/repo_list.html',
controller: 'AccountReposController', controller: 'AccountReposController',
title: 'Repositories', title: 'Repositories',
resolve: { resolve: {
@ -61,7 +62,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/admin/users/add', { .when('/admin/users/add', {
templateUrl: '/views/users_add.html', templateUrl: '/static/views/users_add.html',
controller: 'UserAddController', controller: 'UserAddController',
title: 'Add User', title: 'Add User',
resolve: { resolve: {
@ -71,7 +72,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/admin/users/:host/:login', { .when('/admin/users/:host/:login', {
templateUrl: '/views/users_edit.html', templateUrl: '/static/views/users_edit.html',
controller: 'UserEditController', controller: 'UserEditController',
title: 'Edit User', title: 'Edit User',
resolve: { resolve: {
@ -81,7 +82,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/admin/users', { .when('/admin/users', {
templateUrl: '/views/users.html', templateUrl: '/static/views/users.html',
controller: 'UsersController', controller: 'UsersController',
title: 'System Users', title: 'System Users',
resolve: { resolve: {
@ -91,7 +92,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/admin/settings', { .when('/admin/settings', {
templateUrl: '/views/config.html', templateUrl: '/static/views/config.html',
controller: 'ConfigController', controller: 'ConfigController',
title: 'System Settings', title: 'System Settings',
resolve: { resolve: {
@ -101,7 +102,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/:remote/:owner/:name/settings', { .when('/:remote/:owner/:name/settings', {
templateUrl: '/views/repo_edit.html', templateUrl: '/static/views/repo_edit.html',
controller: 'RepoConfigController', controller: 'RepoConfigController',
title: 'Repository Settings', title: 'Repository Settings',
resolve: { resolve: {
@ -111,7 +112,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/:remote/:owner/:name/:branch/:commit', { .when('/:remote/:owner/:name/:branch/:commit', {
templateUrl: '/views/commit.html', templateUrl: '/static/views/commit.html',
controller: 'CommitController', controller: 'CommitController',
title: 'Recent Commits', title: 'Recent Commits',
resolve: { resolve: {
@ -121,7 +122,7 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
} }
}) })
.when('/:remote/:owner/:name', { .when('/:remote/:owner/:name', {
templateUrl: '/views/repo.html', templateUrl: '/static/views/repo.html',
controller: 'RepoController', controller: 'RepoController',
title: 'Recent Commits', title: 'Recent Commits',
resolve: { resolve: {
@ -140,10 +141,26 @@ app.config(['$routeProvider', '$locationProvider', '$httpProvider', function($ro
// use the HTML5 History API // use the HTML5 History API
$locationProvider.html5Mode(true); $locationProvider.html5Mode(true);
// First, parse the query string
var params = {}, queryString = location.hash.substring(1),
regex = /([^&=]+)=([^&]*)/g, m;
while (m = regex.exec(queryString)) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// if the user is authenticated we should add Basic
// auth token to each request.
if (params.access_token) {
$httpProvider.defaults.headers.common.Authorization = 'Bearer '+params.access_token;
window.history.replaceState( {} , document.title, '/sync' );
}
$httpProvider.interceptors.push(function($q, $location) { $httpProvider.interceptors.push(function($q, $location) {
return { return {
'responseError': function(rejection) { 'responseError': function(rejection) {
if (rejection.status == 401 && rejection.config.url != "/v1/user") { if (rejection.status == 401 && rejection.config.url != "/api/user") {
$location.path('/login'); $location.path('/login');
} }
return $q.reject(rejection); return $q.reject(rejection);
@ -179,7 +196,7 @@ app.controller("AccountReposController", function($scope, $http, user) {
$scope.user = user; $scope.user = user;
// get the user details // get the user details
$http({method: 'GET', url: '/v1/user/repos'}). $http({method: 'GET', url: '/api/user/repos'}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.repos = (typeof data==='string')?[]:data; $scope.repos = (typeof data==='string')?[]:data;
}). }).
@ -224,7 +241,7 @@ app.controller("CommitController", function($scope, $http, $routeParams, stdout,
}); });
// load the repo meta-data // load the repo meta-data
$http({method: 'GET', url: '/v1/repos/'+remote+'/'+owner+"/"+name}). $http({method: 'GET', url: '/api/repos/'+remote+'/'+owner+"/"+name}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.repo = data; $scope.repo = data;
}). }).
@ -233,12 +250,12 @@ app.controller("CommitController", function($scope, $http, $routeParams, stdout,
}); });
// load the repo commit data // load the repo commit data
$http({method: 'GET', url: '/v1/repos/'+remote+'/'+owner+"/"+name+"/branches/"+branch+"/commits/"+commit}). $http({method: 'GET', url: '/api/repos/'+remote+'/'+owner+"/"+name+"/branches/"+branch+"/commits/"+commit}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.commit = data; $scope.commit = data;
if (data.status!='Started' && data.status!='Pending') { if (data.status!='Started' && data.status!='Pending') {
$http({method: 'GET', url: '/v1/repos/'+remote+'/'+owner+"/"+name+"/branches/"+branch+"/commits/"+commit+"/console"}). $http({method: 'GET', url: '/api/repos/'+remote+'/'+owner+"/"+name+"/branches/"+branch+"/commits/"+commit+"/console"}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
var lineFormatter = new Drone.LineFormatter(); var lineFormatter = new Drone.LineFormatter();
var el = document.querySelector('#output'); var el = document.querySelector('#output');
@ -261,7 +278,7 @@ app.controller("CommitController", function($scope, $http, $routeParams, stdout,
}); });
$scope.rebuildCommit = function() { $scope.rebuildCommit = function() {
$http({method: 'POST', url: '/v1/repos/'+remote+'/'+owner+'/'+name+'/'+'branches/'+branch+'/'+'commits/'+commit+'/?action=rebuild' }) $http({method: 'POST', url: '/api/repos/'+remote+'/'+owner+'/'+name+'/'+'branches/'+branch+'/'+'commits/'+commit+'/?action=rebuild' })
} }

View file

@ -6,7 +6,7 @@ angular.module('app').controller("HomeController", function($scope, $http, feed)
// todo toast notification // todo toast notification
}); });
$http({method: 'GET', url: '/v1/user/feed'}). $http({method: 'GET', url: '/api/user/feed'}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.feed = (typeof data==='string')?[]:data; $scope.feed = (typeof data==='string')?[]:data;
}). }).
@ -14,7 +14,7 @@ angular.module('app').controller("HomeController", function($scope, $http, feed)
console.log(data); console.log(data);
}); });
$http({method: 'GET', url: '/v1/user/repos'}). $http({method: 'GET', url: '/api/user/repos'}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.repos = (typeof data==='string')?[]:data; $scope.repos = (typeof data==='string')?[]:data;
}). }).

View file

@ -42,7 +42,7 @@ angular.module('app').controller("RepoController", function($scope, $http, $rout
$scope.activate = function() { $scope.activate = function() {
// request to create a new repository // request to create a new repository
$http({method: 'POST', url: '/v1/repos/'+repo.host+'/'+repo.owner+"/"+repo.name }). $http({method: 'POST', url: '/api/repos/'+repo.host+'/'+repo.owner+"/"+repo.name }).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.repo = data; $scope.repo = data;
}). }).
@ -79,7 +79,7 @@ angular.module('app').controller("RepoConfigController", function($scope, $http,
// load the repo meta-data // load the repo meta-data
// request admin details for the repository as well. // request admin details for the repository as well.
$http({method: 'GET', url: '/v1/repos/'+remote+'/'+owner+"/"+name+"?admin=1"}). $http({method: 'GET', url: '/api/repos/'+remote+'/'+owner+"/"+name+"?admin=1"}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.repo = data; $scope.repo = data;
}). }).
@ -89,7 +89,7 @@ angular.module('app').controller("RepoConfigController", function($scope, $http,
$scope.save = function() { $scope.save = function() {
// request to create a new repository // request to create a new repository
$http({method: 'PUT', url: '/v1/repos/'+remote+'/'+owner+"/"+name, data: $scope.repo }). $http({method: 'PUT', url: '/api/repos/'+remote+'/'+owner+"/"+name, data: $scope.repo }).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
delete $scope.failure; delete $scope.failure;
}). }).

View file

@ -27,7 +27,7 @@ angular.module('app').controller("SetupController", function($scope, $http, $rou
// todo(bradrydzewski) move this to the remote.js service. // todo(bradrydzewski) move this to the remote.js service.
$scope.save = function() { $scope.save = function() {
// request to create a new repository // request to create a new repository
$http({method: 'POST', url: '/v1/remotes', data: $scope.remote }). $http({method: 'POST', url: '/api/remotes', data: $scope.remote }).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
delete $scope.failure; delete $scope.failure;
$location.path("/login"); $location.path("/login");

View file

@ -5,7 +5,7 @@ angular.module('app').controller("UserController", function($scope, $http, user)
$scope.account = user; $scope.account = user;
// get the user details // get the user details
$http({method: 'GET', url: '/v1/user'}). $http({method: 'GET', url: '/api/user'}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.user = data; $scope.user = data;
$scope.userTemp = { $scope.userTemp = {
@ -19,7 +19,7 @@ angular.module('app').controller("UserController", function($scope, $http, user)
$scope.save = function() { $scope.save = function() {
// request to create a new repository // request to create a new repository
$http({method: 'PUT', url: '/v1/user', data: $scope.userTemp }). $http({method: 'PUT', url: '/api/user', data: $scope.userTemp }).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
delete $scope.failure; delete $scope.failure;
$scope.user = data; $scope.user = data;

View file

@ -4,7 +4,7 @@ angular.module('app').controller("UsersController", function($scope, $http, user
$scope.user = user; $scope.user = user;
$http({method: 'GET', url: '/v1/users'}). $http({method: 'GET', url: '/api/users'}).
success(function(data, status, headers, config) { success(function(data, status, headers, config) {
$scope.users = data; $scope.users = data;
}). }).

View file

@ -16,7 +16,7 @@ angular.module('app').service('authService', function($q, $http) {
} }
// else we need to fetch from the server // else we need to fetch from the server
$http({method: 'GET', url: '/v1/user'}). $http({method: 'GET', url: '/api/user'}).
success(function(data) { success(function(data) {
_this.user=data; _this.user=data;
defer.resolve(_this.user); defer.resolve(_this.user);

View file

@ -4,7 +4,7 @@ angular.module('app').service('confService', function($q, $http) {
return{ return{
getConfig : function() { getConfig : function() {
var defer = $q.defer(); var defer = $q.defer();
var route = '/v1/config'; var route = '/api/config';
$http.get(route).success(function(data){ $http.get(route).success(function(data){
defer.resolve(data); defer.resolve(data);
}); });

View file

@ -3,7 +3,7 @@
angular.module('app').service('feed', ['$http', '$window', function($http, $window) { angular.module('app').service('feed', ['$http', '$window', function($http, $window) {
var proto = ($window.location.protocol == 'https:' ? 'wss' : 'ws'); var proto = ($window.location.protocol == 'https:' ? 'wss' : 'ws');
var route = [proto, "://", $window.location.host, '/ws/user'].join(''); var route = [proto, "://", $window.location.host, '/api/stream/user'].join('');
var wsCallback = undefined; var wsCallback = undefined;
var ws = new WebSocket(route); var ws = new WebSocket(route);

View file

@ -4,10 +4,10 @@
angular.module('app').service('remotes', ['$http', function($http) { angular.module('app').service('remotes', ['$http', function($http) {
this.get = function() { this.get = function() {
return $http.get('/v1/remotes'); return $http.get('/api/remotes');
}; };
this.getLogins = function() { this.getLogins = function() {
return $http.get('/v1/logins'); return $http.get('/api/logins');
}; };
}]); }]);

View file

@ -7,7 +7,7 @@ angular.module('app').service('repos', ['$q', '$http', function($q, $http) {
// @deprecated // @deprecated
this.getRepo = function(host, owner, name) { this.getRepo = function(host, owner, name) {
var defer = $q.defer(); var defer = $q.defer();
var route = '/v1/repos/'+host+'/'+owner+'/'+name; var route = '/api/repos/'+host+'/'+owner+'/'+name;
$http.get(route).success(function(data){ $http.get(route).success(function(data){
defer.resolve(data); defer.resolve(data);
}); });
@ -16,30 +16,30 @@ angular.module('app').service('repos', ['$q', '$http', function($q, $http) {
// Gets a repository by host, owner and name. // Gets a repository by host, owner and name.
this.get = function(host, owner, name) { this.get = function(host, owner, name) {
return $http.get('/v1/repos/'+host+'/'+owner+'/'+name); return $http.get('/api/repos/'+host+'/'+owner+'/'+name);
}; };
// Gets a repository by host, owner and name. // Gets a repository by host, owner and name.
this.feed = function(host, owner, name) { this.feed = function(host, owner, name) {
return $http.get('/v1/repos/'+host+'/'+owner+'/'+name+'/feed'); return $http.get('/api/repos/'+host+'/'+owner+'/'+name+'/feed');
}; };
// Updates an existing repository // Updates an existing repository
this.update = function(repo) { this.update = function(repo) {
// todo(bradrydzewski) add repo to the request body // todo(bradrydzewski) add repo to the request body
return $http.post('/v1/repos/'+repo.host+'/'+repo.owner+'/'+repo.name); return $http.post('/api/repos/'+repo.host+'/'+repo.owner+'/'+repo.name);
}; };
// Activates a repository on the backend, registering post-commit // Activates a repository on the backend, registering post-commit
// hooks with the remote hosting service (ie github). // hooks with the remote hosting service (ie github).
this.activate = function(repo) { this.activate = function(repo) {
// todo(bradrydzewski) add repo to the request body // todo(bradrydzewski) add repo to the request body
return $http.post('/v1/repos/'+repo.host+'/'+repo.owner+'/'+repo.name); return $http.post('/api/repos/'+repo.host+'/'+repo.owner+'/'+repo.name);
}; };
// Deactivate a repository sets the active flag to false, instructing // Deactivate a repository sets the active flag to false, instructing
// the system to ignore all post-commit hooks for the repository. // the system to ignore all post-commit hooks for the repository.
this.deactivate = function(repo) { this.deactivate = function(repo) {
return $http.delete('/v1/repos/'+repo.host+'/'+repo.owner+'/'+repo.name); return $http.delete('/api/repos/'+repo.host+'/'+repo.owner+'/'+repo.name);
}; };
}]); }]);

View file

@ -8,7 +8,7 @@ angular.module('app').service('stdout', ['$window', function($window) {
callback = _callback; callback = _callback;
var proto = ($window.location.protocol == 'https:' ? 'wss' : 'ws'); var proto = ($window.location.protocol == 'https:' ? 'wss' : 'ws');
var route = [proto, "://", $window.location.host, '/ws/stdout/', path].join(''); var route = [proto, "://", $window.location.host, '/api/feed/stdout/', path].join('');
websocket = new WebSocket(route); websocket = new WebSocket(route);
websocket.onmessage = function(event) { websocket.onmessage = function(event) {

View file

@ -2,15 +2,15 @@
angular.module('app').service('users', ['$http', function($http) { angular.module('app').service('users', ['$http', function($http) {
this.getCurrent = function() { this.getCurrent = function() {
return $http.get('/v1/user'); return $http.get('/api/user');
}; };
this.get = function(host, login) { this.get = function(host, login) {
return $http.get('/v1/users/'+host+'/'+login); return $http.get('/api/users/'+host+'/'+login);
}; };
this.create = function(host, login) { this.create = function(host, login) {
return $http.post('/v1/users/'+host+'/'+login); return $http.post('/api/users/'+host+'/'+login);
}; };
this.delete = function(host, login) { this.delete = function(host, login) {
return $http.delete('/v1/users/'+host+'/'+login); return $http.delete('/api/users/'+host+'/'+login);
}; };
}]); }]);

View file

@ -11,7 +11,7 @@ minor modifications to the style that only apply to this view
<article id="loginpage"> <article id="loginpage">
<div class="pure-g"> <div class="pure-g">
<div class="pure-u-1" ng-if="state == 1 && remotes.length != 0" ng-repeat="remote in remotes"> <div class="pure-u-1" ng-if="state == 1 && remotes.length != 0" ng-repeat="remote in remotes">
<a ng-href="/login/{{ remote.type }}" target="_self" ng-if="remote.type != 'gitlab.com' "> <a ng-href="/api/auth/{{ remote.type }}" target="_self" ng-if="remote.type != 'gitlab.com' ">
<i class="fa {{ remote.type | remoteIcon }}"></i> {{ remote.type | remoteName }} <i class="fa {{ remote.type | remoteIcon }}"></i> {{ remote.type | remoteName }}
</a> </a>
<a ng-href="/gitlab" ng-if="remote.type == 'gitlab.com' "> <a ng-href="/gitlab" ng-if="remote.type == 'gitlab.com' ">

View file

@ -9,7 +9,7 @@ minor modifications to the style that only apply to this view
</style> </style>
<article id="loginpage"> <article id="loginpage">
<form class="pure-g" method="POST" action="/login/gitlab.com"> <form class="pure-g" method="POST" action="/api/auth/gitlab.com">
<div class="pure-u-1"> <div class="pure-u-1">
<input type="text" name="username" placeholder="Email Address" /> <input type="text" name="username" placeholder="Email Address" />
</div> </div>

View file

@ -1,6 +1,7 @@
package handler package handler
import ( import (
"encoding/json"
"log" "log"
"net/http" "net/http"
"time" "time"
@ -156,3 +157,20 @@ func GetLogin(c web.C, w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, redirect, http.StatusSeeOther) http.Redirect(w, r, redirect, http.StatusSeeOther)
} }
// GetLoginList accepts a request to retrive a list of
// all OAuth login options.
//
// GET /api/remotes/login
//
func GetLoginList(c web.C, w http.ResponseWriter, r *http.Request) {
var list = remote.Registered()
var logins []interface{}
for _, item := range list {
logins = append(logins, struct {
Type string `json:"type"`
Host string `json:"host"`
}{item.GetKind(), item.GetHost()})
}
json.NewEncoder(w).Encode(&logins)
}

View file

@ -4,9 +4,9 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/drone/drone-dart/worker" "github.com/drone/drone/server/worker"
"github.com/drone/drone-dart/worker/director" "github.com/drone/drone/server/worker/director"
"github.com/drone/drone-dart/worker/pool" "github.com/drone/drone/server/worker/pool"
"github.com/goji/context" "github.com/goji/context"
"github.com/zenazn/goji/web" "github.com/zenazn/goji/web"
) )

View file

@ -8,16 +8,12 @@ import (
"strings" "strings"
"github.com/drone/config" "github.com/drone/config"
//"github.com/drone/drone/server/database"
"github.com/drone/drone/server/handler" "github.com/drone/drone/server/handler"
"github.com/drone/drone/server/middleware" "github.com/drone/drone/server/middleware"
//"github.com/drone/drone/server/pubsub" "github.com/drone/drone/server/pubsub"
//"github.com/drone/drone/server/session"
//"github.com/drone/drone/server/worker"
"github.com/drone/drone/shared/build/log" "github.com/drone/drone/shared/build/log"
//"github.com/drone/drone/shared/model"
//"github.com/GeertJohan/go.rice" "github.com/GeertJohan/go.rice"
"code.google.com/p/go.net/context" "code.google.com/p/go.net/context"
webcontext "github.com/goji/context" webcontext "github.com/goji/context"
@ -66,6 +62,8 @@ var (
// director // director
worker *director.Director worker *director.Director
pub *pubsub.PubSub
nodes StringArr nodes StringArr
db *sql.DB db *sql.DB
@ -105,6 +103,7 @@ func main() {
workers.Allocate(docker.New()) workers.Allocate(docker.New())
worker = director.New() worker = director.New()
pub = pubsub.NewPubSub()
/* /*
if nodes == nil || len(nodes) == 0 { if nodes == nil || len(nodes) == 0 {
worker.NewWorker(workerc, users, repos, commits, pubsub, &model.Server{}).Start() worker.NewWorker(workerc, users, repos, commits, pubsub, &model.Server{}).Start()
@ -117,6 +116,7 @@ func main() {
} }
*/ */
goji.Get("/api/logins", handler.GetLoginList)
goji.Get("/api/stream/stdout/:id", handler.WsConsole) goji.Get("/api/stream/stdout/:id", handler.WsConsole)
goji.Get("/api/stream/user", handler.WsUser) goji.Get("/api/stream/user", handler.WsUser)
goji.Get("/api/auth/:host", handler.GetLogin) goji.Get("/api/auth/:host", handler.GetLogin)
@ -164,6 +164,14 @@ func main() {
work.Get("/api/workers", handler.GetWorkers) work.Get("/api/workers", handler.GetWorkers)
goji.Handle("/api/work*", work) goji.Handle("/api/work*", work)
// Include static resources
assets := rice.MustFindBox("app").HTTPBox()
assetserve := http.FileServer(rice.MustFindBox("app").HTTPBox())
http.Handle("/static/", http.StripPrefix("/static", assetserve))
goji.Get("/*", func(c web.C, w http.ResponseWriter, r *http.Request) {
w.Write(assets.MustBytes("index.html"))
})
// Add middleware and serve // Add middleware and serve
goji.Use(ContextMiddleware) goji.Use(ContextMiddleware)
goji.Use(middleware.SetHeaders) goji.Use(middleware.SetHeaders)
@ -187,6 +195,7 @@ func ContextMiddleware(c *web.C, h http.Handler) http.Handler {
ctx = blobstore.NewContext(ctx, database.NewBlobstore(db)) ctx = blobstore.NewContext(ctx, database.NewBlobstore(db))
ctx = pool.NewContext(ctx, workers) ctx = pool.NewContext(ctx, workers)
ctx = director.NewContext(ctx, worker) ctx = director.NewContext(ctx, worker)
ctx = pubsub.NewContext(ctx, pub)
// add the context to the goji web context // add the context to the goji web context
webcontext.Set(c, ctx) webcontext.Set(c, ctx)

View file

@ -1,6 +1,7 @@
package session package session
import ( import (
"fmt"
"net/http" "net/http"
"time" "time"
@ -19,14 +20,13 @@ var secret = securecookie.GenerateRandomKey(32)
// http.Request. The user details will be stored as either // http.Request. The user details will be stored as either
// a simple API token or JWT bearer token. // a simple API token or JWT bearer token.
func GetUser(c context.Context, r *http.Request) *model.User { func GetUser(c context.Context, r *http.Request) *model.User {
var token = r.FormValue("access_token")
switch { switch {
case len(token) == 0: case r.Header.Get("Authorization") != "":
return nil return getUserBearer(c, r)
case len(token) == 32: case r.FormValue("access_token") != "":
return getUserToken(c, r) return getUserToken(c, r)
default: default:
return getUserBearer(c, r) return nil
} }
} }
@ -52,17 +52,20 @@ func getUserToken(c context.Context, r *http.Request) *model.User {
// getUserBearer gets the currently authenticated user for the given // getUserBearer gets the currently authenticated user for the given
// bearer token (JWT) // bearer token (JWT)
func getUserBearer(c context.Context, r *http.Request) *model.User { func getUserBearer(c context.Context, r *http.Request) *model.User {
var tokenstr = r.FormValue("access_token") var tokenstr = r.Header.Get("Authorization")
fmt.Sscanf(tokenstr, "Bearer %s", &tokenstr)
var token, err = jwt.Parse(tokenstr, func(t *jwt.Token) (interface{}, error) { var token, err = jwt.Parse(tokenstr, func(t *jwt.Token) (interface{}, error) {
return secret, nil return secret, nil
}) })
if err != nil || token.Valid { if err != nil || !token.Valid {
println("invalid token")
return nil return nil
} }
var userid, ok = token.Claims["user_id"].(int64) var userid, ok = token.Claims["user_id"].(float64)
if !ok { if !ok {
return nil return nil
} }
var user, _ = datastore.GetUser(c, userid) var user, _ = datastore.GetUser(c, int64(userid))
return user return user
} }