Here is a program with the two handlers taken from the web server running duplicacy.com. It compiles but I didn’t get a chance to test it.
You’ll need to fill in your own client id and client secret.
package main
import (
"fmt"
"encoding/json"
"net/http"
"crypto/tls"
"golang.org/x/oauth2"
"golang.org/x/crypto/acme/autocert"
)
var (
oneOauthConfig = oauth2.Config{
ClientID: "",
ClientSecret: "",
RedirectURL: "https://yourwebsite/one_oauth",
Scopes: []string{"Files.ReadWrite", "offline_access"},
Endpoint: oauth2.Endpoint{
AuthURL: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
TokenURL: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
},
}
)
// OauthHandler ...
func oneOauthHandler(w http.ResponseWriter, r *http.Request) {
token, err := oneOauthConfig.Exchange(r.Context(), r.URL.Query().Get("code"))
if err != nil {
http.Error(w, fmt.Sprintf("Error exchanging the code for an access token: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Disposition", "attachment; filename=one-token.json")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(token); err != nil {
http.Error(w, fmt.Sprintf("Error encoding the token in JSON: %v", err), http.StatusInternalServerError)
return
}
}
// RefreshHandler ...
func oneRefreshHandler(w http.ResponseWriter, r *http.Request) {
var token oauth2.Token
defer r.Body.Close()
if err := json.NewDecoder(r.Body).Decode(&token); err != nil {
http.Error(w, fmt.Sprintf("Error decoding the token from the request: %v", err), http.StatusBadRequest)
return
}
tokenSource := oneOauthConfig.TokenSource(r.Context(), &token)
newToken, err := tokenSource.Token()
if err != nil {
http.Error(w, fmt.Sprintf("Error fetching a new token: %v", err), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(newToken); err != nil {
http.Error(w, fmt.Sprintf("Error encoding the token in JSON: %v", err), http.StatusInternalServerError)
return
}
}
func main() {
http.HandleFunc("/one_oauth", oneOauthHandler)
http.HandleFunc("/one_refresh", oneRefreshHandler)
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache("certs"),
}
server := &http.Server{
Addr: ":https",
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
},
}
go func() {
err := http.ListenAndServe(":80", certManager.HTTPHandler(nil))
fmt.Printf("Failed to start the http server: %v\n", err)
} ()
err := server.ListenAndServeTLS("", "")
if err != nil {
fmt.Printf("Failed to start the https server: %v\n", err)
}
}