Skip to content

Instantly share code, notes, and snippets.

@dtan4
Last active June 24, 2020 14:11
Show Gist options
  • Save dtan4/a3b5027dd3c7d5c5ed3119ea97fb7235 to your computer and use it in GitHub Desktop.
Save dtan4/a3b5027dd3c7d5c5ed3119ea97fb7235 to your computer and use it in GitHub Desktop.
GitHub OAuth Login w/ gin
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weboauth</title>
</head>
<body>
<h1>weboauth</h1>
{{ if .logged_in }}
Logged in: {{ .login }} ({{ .name }})
{{ else }}
<a href="/signin">Sign in with GitHub</a>
{{ end }}
</body>
</html>
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
githuboauth "golang.org/x/oauth2/github"
)
func generateSecretKey() (string, error) {
b := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
fmt.Println("error:", err)
return "", err
}
return strings.TrimRight(base64.StdEncoding.EncodeToString(b), "="), nil
}
func main() {
oauthConf := &oauth2.Config{
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
Scopes: []string{"user"},
Endpoint: githuboauth.Endpoint,
}
secretKey := os.Getenv("SECRET_KEY_BASE")
if secretKey == "" {
sk, err := generateSecretKey()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
secretKey = sk
}
r := gin.Default()
store := sessions.NewCookieStore([]byte(secretKey))
r.Use(sessions.Sessions("paus", store))
r.LoadHTMLGlob("templates/*")
r.GET("/", func(c *gin.Context) {
session := sessions.Default(c)
token := session.Get("token")
if token == nil {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"logged_in": false,
})
} else {
oauthClient := oauthConf.Client(oauth2.NoContext, &oauth2.Token{AccessToken: token.(string)})
client := github.NewClient(oauthClient)
user, _, err := client.Users.Get("")
if err != nil {
c.String(http.StatusNotFound, "User not found")
return
}
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"logged_in": true,
"login": user.Login,
"name": user.Name,
})
}
})
r.GET("/signin", func(c *gin.Context) {
url := oauthConf.AuthCodeURL("hoge", oauth2.AccessTypeOnline)
c.Redirect(http.StatusMovedPermanently, url)
})
r.GET("/callback", func(c *gin.Context) {
code := c.Query("code")
token, err := oauthConf.Exchange(oauth2.NoContext, code)
if err != nil {
c.String(http.StatusBadRequest, "Error: %s", err)
return
}
session := sessions.Default(c)
fmt.Println(token.AccessToken)
session.Set("token", token.AccessToken)
session.Save()
c.Redirect(http.StatusMovedPermanently, "/")
})
r.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment