Skip to content

Commit

Permalink
Add Docker ID integration
Browse files Browse the repository at this point in the history
  • Loading branch information
xetorthio committed Oct 10, 2017
1 parent 978fd78 commit e9dd97e
Show file tree
Hide file tree
Showing 11 changed files with 125 additions and 10 deletions.
18 changes: 18 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ var SecureCookie *securecookie.SecureCookie

var GithubClientID, GithubClientSecret string
var FacebookClientID, FacebookClientSecret string
var DockerClientID, DockerClientSecret string

type stringslice []string

Expand Down Expand Up @@ -78,6 +79,9 @@ func ParseFlags() {
flag.StringVar(&FacebookClientID, "oauth-facebook-client-id", "", "Facebook OAuth Client ID")
flag.StringVar(&FacebookClientSecret, "oauth-facebook-client-secret", "", "Facebook OAuth Client Secret")

flag.StringVar(&DockerClientID, "oauth-docker-client-id", "", "Docker OAuth Client ID")
flag.StringVar(&DockerClientSecret, "oauth-docker-client-secret", "", "Docker OAuth Client Secret")

flag.Parse()

SecureCookie = securecookie.New([]byte(CookieHashKey), []byte(CookieBlockKey))
Expand Down Expand Up @@ -107,6 +111,20 @@ func registerOAuthProviders() {

Providers["facebook"] = conf
}
if DockerClientID != "" && DockerClientSecret != "" {
oauth2.RegisterBrokenAuthHeaderProvider(".id.docker.com")
conf := &oauth2.Config{
ClientID: DockerClientID,
ClientSecret: DockerClientSecret,
Scopes: []string{"openid"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://id.docker.com/id/oauth/authorize/",
TokenURL: "https://id.docker.com/id/oauth/token",
},
}

Providers["docker"] = conf
}
}

func GetDindImageName() string {
Expand Down
1 change: 1 addition & 0 deletions handlers/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ func Register(extend HandlerExtender) {
http.ServeFile(rw, r, "./www/landing.html")
}).Methods("GET")

r.HandleFunc("/users/me", LoggedInUser).Methods("GET")
r.HandleFunc("/oauth/providers", ListProviders).Methods("GET")
r.HandleFunc("/oauth/providers/{provider}/login", Login).Methods("GET")
r.HandleFunc("/oauth/providers/{provider}/callback", LoginCallback).Methods("GET")
Expand Down
9 changes: 5 additions & 4 deletions handlers/cookie_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ type CookieID struct {
func (c *CookieID) SetCookie(rw http.ResponseWriter) error {
if encoded, err := config.SecureCookie.Encode("id", c); err == nil {
cookie := &http.Cookie{
Name: "id",
Value: encoded,
Path: "/",
Secure: config.UseLetsEncrypt,
Name: "id",
Value: encoded,
Path: "/",
Secure: config.UseLetsEncrypt,
HttpOnly: true,
}
http.SetCookie(rw, cookie)
} else {
Expand Down
43 changes: 41 additions & 2 deletions handlers/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,25 @@ import (
fb "github.com/huandu/facebook"
"github.com/play-with-docker/play-with-docker/config"
"github.com/play-with-docker/play-with-docker/pwd/types"
"github.com/twinj/uuid"
)

func LoggedInUser(rw http.ResponseWriter, req *http.Request) {
cookie, err := ReadCookie(req)
if err != nil {
log.Println("Cannot read cookie")
rw.WriteHeader(http.StatusUnauthorized)
return
}
user, err := core.UserGet(cookie.Id)
if err != nil {
log.Printf("Couldn't get user with id %s. Got: %v\n", cookie.Id, err)
rw.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(rw).Encode(user)
}

func ListProviders(rw http.ResponseWriter, req *http.Request) {
providers := []string{}
for name, _ := range config.Providers {
Expand Down Expand Up @@ -51,7 +68,7 @@ func Login(rw http.ResponseWriter, req *http.Request) {
host = req.Host
}
provider.RedirectURL = fmt.Sprintf("%s://%s/oauth/providers/%s/callback", scheme, host, providerName)
url := provider.AuthCodeURL(loginRequest.Id)
url := provider.AuthCodeURL(loginRequest.Id, oauth2.SetAuthURLParam("nonce", uuid.NewV4().String()))

http.Redirect(rw, req, url, http.StatusFound)
}
Expand Down Expand Up @@ -125,6 +142,28 @@ func LoginCallback(rw http.ResponseWriter, req *http.Request) {
user.Name = res.Get("name").(string)
user.Avatar = res.Get("picture.data.url").(string)
user.Email = res.Get("email").(string)
} else if providerName == "docker" {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: tok.AccessToken},
)
tc := oauth2.NewClient(ctx, ts)
resp, err := tc.Get("https://id.docker.com/api/id/v1/openid/userinfo")
if err != nil {
log.Printf("Could not get user from docker. Got: %v\n", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}

userInfo := map[string]string{}
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
log.Printf("Could not decode user info. Got: %v\n", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}

user.ProviderUserId = userInfo["sub"]
user.Name = userInfo["preferred_username"]
user.Email = userInfo["email"]
}

user, err = core.UserLogin(loginRequest, user)
Expand All @@ -142,5 +181,5 @@ func LoginCallback(rw http.ResponseWriter, req *http.Request) {
return
}

http.Redirect(rw, req, "/", http.StatusFound)
fmt.Fprintf(rw, `<html><head><script>window.close();</script></head><body></body></html>`)
}
4 changes: 4 additions & 0 deletions pwd/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,7 @@ func (m *Mock) UserLogin(loginRequest *types.LoginRequest, user *types.User) (*t
args := m.Called(loginRequest, user)
return args.Get(0).(*types.User), args.Error(1)
}
func (m *Mock) UserGet(id string) (*types.User, error) {
args := m.Called(id)
return args.Get(0).(*types.User), args.Error(1)
}
1 change: 1 addition & 0 deletions pwd/pwd.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ type PWDApi interface {
UserNewLoginRequest(providerName string) (*types.LoginRequest, error)
UserGetLoginRequest(id string) (*types.LoginRequest, error)
UserLogin(loginRequest *types.LoginRequest, user *types.User) (*types.User, error)
UserGet(id string) (*types.User, error)
}

func NewPWD(f docker.FactoryApi, e event.EventApi, s storage.StorageApi, sp provisioner.SessionProvisionerApi, ipf provisioner.InstanceProvisionerFactoryApi) *pwd {
Expand Down
7 changes: 7 additions & 0 deletions pwd/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,10 @@ func (p *pwd) UserLogin(loginRequest *types.LoginRequest, user *types.User) (*ty

return user, nil
}
func (p *pwd) UserGet(id string) (*types.User, error) {
if user, err := p.storage.UserGet(id); err != nil {
return nil, err
} else {
return user, nil
}
}
10 changes: 10 additions & 0 deletions storage/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,16 @@ func (store *storage) UserPut(user *types.User) error {

return nil
}
func (store *storage) UserGet(id string) (*types.User, error) {
store.rw.Lock()
defer store.rw.Unlock()

if user, found := store.db.Users[id]; !found {
return nil, NotFoundError
} else {
return user, nil
}
}

func (store *storage) load() error {
file, err := os.Open(store.path)
Expand Down
4 changes: 4 additions & 0 deletions storage/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,7 @@ func (m *Mock) UserPut(user *types.User) error {
args := m.Called(user)
return args.Error(0)
}
func (m *Mock) UserGet(id string) (*types.User, error) {
args := m.Called(id)
return args.Get(0).(*types.User), args.Error(1)
}
1 change: 1 addition & 0 deletions storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ type StorageApi interface {

UserFindByProvider(providerName, providerUserId string) (*types.User, error)
UserPut(user *types.User) error
UserGet(id string) (*types.User, error)
}
37 changes: 33 additions & 4 deletions www/landing.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ <h1 class="display-3">Play with Docker</h1>
Login
</button>
<div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<a ng-repeat="provider in providers" class="dropdown-item" href="/oauth/providers/{{provider}}/login">{{provider}}</a>
<a ng-repeat="provider in providers" class="dropdown-item" ng-click="login(provider)">{{provider}}</a>
</div>
</div>
<form id="landingForm" method="POST" action="/">
Expand All @@ -68,10 +68,27 @@ <h1 class="display-3">Play with Docker</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script>
angular.module('PWDLanding', ['ngCookies'])
.controller('LoginController', ['$cookies', '$scope', '$http', function($cookies, $scope, $http) {
angular.module('PWDLanding', [])
.controller('LoginController', ['$scope', '$http', '$window', function($scope, $http, $window) {
$scope.providers = [];
$scope.loggedIn = $cookies.get('id') !== undefined;
$scope.loggedIn = false;
$scope.user = null;

function checkLoggedIn() {
$http({
method: 'GET',
url: '/users/me'
}).then(function(response) {
$scope.user = response.data;
$scope.loggedIn = true;
}, function(response) {
console.log('ERROR', response);
$scope.user = null;
$scope.loggedIn = false;
});
}

checkLoggedIn();

$http({
method: 'GET',
Expand All @@ -85,6 +102,18 @@ <h1 class="display-3">Play with Docker</h1>
console.log('ERROR', response);
});


$scope.login = function(provider) {
var width = screen.width*0.6;
var height = screen.height*0.6;
var x = screen.width/2 - width/2;
var y = screen.height/2 - height/2;
var loginWnd = $window.open('/oauth/providers/' + provider + '/login', 'PWDLogin', 'width='+width+',height='+height+',left='+x+',top='+y);
loginWnd.onunload = function() {
checkLoggedIn();
}
}

$scope.start = function() {
function getParameterByName(name, url) {
if (!url) url = window.location.href;
Expand Down

0 comments on commit e9dd97e

Please sign in to comment.