Skip to content

Commit

Permalink
ser redirect_url to github oauth2
Browse files Browse the repository at this point in the history
  • Loading branch information
azuki774 committed Oct 26, 2024
1 parent 4ab7a60 commit ab26448
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
Expand All @@ -14,6 +13,9 @@ import (
"go.uber.org/zap"
)

const XCallBackHeader = "X-Callback-URL"
const githubOAuthauthorizeURL = "https://github.com/login/oauth/authorize"

type Server struct {
Port int
Authenticator Authenticator
Expand All @@ -29,11 +31,6 @@ type Authenticator interface {
HandlingGitHubOAuth(ctx context.Context, code string) (ok bool, err error)
}

// https://hoge.example.com/callback/github -> https://hoge.example.com/
func (s Server) getServerBaseURL(r *url.URL) string {
return r.Scheme + "://" + r.Host + s.BasePath
}

func (s Server) addHandler(r *chi.Mux) {
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
Expand Down Expand Up @@ -73,9 +70,18 @@ func (s Server) addHandler(r *chi.Mux) {
})

r.Get("/login_page", func(w http.ResponseWriter, r *http.Request) {
clientId := os.Getenv("GITHUB_CLIENT_ID") // TODO
url := fmt.Sprintf("https://github.com/login/oauth/authorize?client_id=%s&scope=user:read", clientId)
clientId := os.Getenv("GITHUB_CLIENT_ID") // TODO
redirectURL := r.Header.Get(XCallBackHeader) // 指定するコールバック先のURL
var url string
if redirectURL != "" {
// コールバック先明示
url = fmt.Sprintf("%s?client_id=%s&redirect_uri=%s&scope=user:read", githubOAuthauthorizeURL, clientId, redirectURL)
} else {
url = fmt.Sprintf("%s?client_id=%s&scope=user:read", githubOAuthauthorizeURL, clientId)
}

zap.L().Info(fmt.Sprintf("move to %s", url))
zap.L().Info(fmt.Sprintf("redirect_uri is %s", redirectURL))
http.Redirect(w, r, url, http.StatusFound)
})

Expand Down Expand Up @@ -112,8 +118,8 @@ func (s Server) addHandler(r *chi.Mux) {
zap.L().Info("set Cookie")

// エラーでなければ親ページに返してあげる
zap.L().Info(fmt.Sprintf("move to %s", s.getServerBaseURL(r.URL)))
http.Redirect(w, r, s.getServerBaseURL(r.URL), http.StatusFound)
zap.L().Info(fmt.Sprintf("move to %s", s.BasePath))
http.Redirect(w, r, s.BasePath, http.StatusFound)

zap.L().Info("callback process done")
})
Expand Down

0 comments on commit ab26448

Please sign in to comment.