|
package main |
|
|
|
import ( |
|
"fmt" |
|
"log" |
|
"net/http" |
|
"net/url" |
|
"os" |
|
"strconv" |
|
"time" |
|
) |
|
|
|
func main() { |
|
|
|
router := http.NewServeMux() |
|
router.HandleFunc("/start/", MakeStartHandler()) |
|
router.HandleFunc("/oauth2/", MakeOAuth2Handler()) |
|
router.HandleFunc("/home/", MakeHomepageHandler()) |
|
|
|
timeout := time.Second * 10 |
|
port := 8080 |
|
if v, exists := os.LookupEnv("port"); exists { |
|
val, _ := strconv.Atoi(v) |
|
port = val |
|
} |
|
|
|
log.Printf("Using port: %d\n", port) |
|
|
|
s := &http.Server{ |
|
Addr: fmt.Sprintf(":%d", port), |
|
Handler: router, |
|
ReadTimeout: timeout, |
|
WriteTimeout: timeout, |
|
MaxHeaderBytes: 1 << 20, |
|
} |
|
|
|
log.Fatal(s.ListenAndServe()) |
|
} |
|
|
|
func MakeStartHandler() func(http.ResponseWriter, *http.Request) { |
|
|
|
// http://localhost:8081/start |
|
|
|
return func(w http.ResponseWriter, r *http.Request) { |
|
redirectRaw := "http://localhost:8081/oauth2/authorized" |
|
redirectURI, _ := url.Parse(redirectRaw) |
|
rQuery := redirectURI.Query() |
|
rQuery.Set("custom_param", "1") |
|
redirectURI.RawQuery = rQuery.Encode() |
|
|
|
redirect, _ := url.Parse(os.Getenv("base_url") + "/oauth/authorize") |
|
q := redirect.Query() |
|
q.Set("client_id", os.Getenv("client_id")) |
|
q.Set("response_type", "code") |
|
q.Set("state", "state") |
|
q.Set("redirect_uri", redirectURI.String()) |
|
|
|
redirect.RawQuery = q.Encode() |
|
|
|
w.Write([]byte(`<html><head></head>Redirecting.. <a href="redirect">to login</a>. <script>window.location.replace("` + redirect.String() + `");</script></html>`)) |
|
} |
|
} |
|
func MakeHomepageHandler() func(http.ResponseWriter, *http.Request) { |
|
|
|
return func(w http.ResponseWriter, r *http.Request) { |
|
w.Write([]byte("OK")) |
|
} |
|
} |
|
|
|
func MakeOAuth2Handler() func(http.ResponseWriter, *http.Request) { |
|
|
|
return func(w http.ResponseWriter, r *http.Request) { |
|
log.Printf("URL: %s", r.URL) |
|
if r.URL.Path != "/oauth2/authorized" { |
|
w.WriteHeader(http.StatusUnauthorized) |
|
w.Write([]byte("Unauthorized OAuth callback.")) |
|
return |
|
} |
|
|
|
if r.Body != nil { |
|
defer r.Body.Close() |
|
} |
|
|
|
log.Println(r.URL.Query()) |
|
|
|
w.Write([]byte(fmt.Sprintf("OK, got a code: %s", r.URL.Query().Get("code")))) |
|
} |
|
} |