Created
February 16, 2020 12:42
-
-
Save adigunhammedolalekan/1318696ba6319e727260d573d0b53bb8 to your computer and use it in GitHub Desktop.
This file contains 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
func (srv *tokenServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
username, password, ok := r.BasicAuth() | |
if !ok { | |
http.Error(w, "auth credentials not found", http.StatusUnauthorized) | |
return | |
} | |
// compare username and password against your datasets | |
// our example only allows foo:bar | |
if username != "foo" || password != "bar" { | |
http.Error(w, "invalid auth credentials", http.StatusUnauthorized) | |
return | |
} | |
// do authorization check | |
opt := srv.createTokenOption(r) | |
actions := srv.authorize(opt) | |
tk, err := srv.createToken(opt, actions) | |
if err != nil { | |
http.Error(w, "server error", http.StatusInternalServerError) | |
return | |
} | |
srv.ok(w, tk) | |
} | |
func (srv *tokenServer) authorize(opt *Option) []string { | |
// do proper comparison to check for user's access | |
// against the requested actions | |
if opt.account == "foo" { | |
return []string{"pull", "push"} | |
} | |
if opt.account == "bar" { | |
return []string{"pull"} | |
} | |
// unauthorized, no permission is granted | |
return []string{} | |
} | |
func (srv *tokenServer) run() error { | |
addr := fmt.Sprintf(":%s", os.Getenv("PORT")) | |
http.Handle("/auth", srv) | |
return http.ListenAndServeTLS(addr, srv.crt, srv.key, nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment