117 lines
2.2 KiB
Go
117 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/lunny/tango"
|
|
"github.com/tango-contrib/renders"
|
|
"github.com/tango-contrib/session"
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
type Home struct {
|
|
tango.Ctx
|
|
renders.Renderer
|
|
session.Session
|
|
}
|
|
|
|
const (
|
|
oriState = "11111112334"
|
|
)
|
|
|
|
var (
|
|
conf = &oauth2.Config{
|
|
ClientID: "e9b8c4d9-152b-413e-b912-2456f84196c9", // change this to your gitea client id
|
|
ClientSecret: "1UBmIsOCdO4Po_4Cma7tX1zxtBfDu1-PAJ4yNFuz9hA=", // change this to your gitea secret id
|
|
Endpoint: oauth2.Endpoint{
|
|
TokenURL: "http://localhost:3000/login/oauth/access_token",
|
|
AuthURL: "http://localhost:3000/login/oauth/authorize",
|
|
},
|
|
RedirectURL: "http://localhost:8000/callback",
|
|
}
|
|
)
|
|
|
|
func (h *Home) Get() error {
|
|
user := h.Session.Get("user")
|
|
if user == nil {
|
|
h.Session.Set("state", oriState)
|
|
|
|
url := conf.AuthCodeURL(oriState, oauth2.AccessTypeOffline)
|
|
fmt.Printf("Visit the URL for the auth dialog: %v", url)
|
|
|
|
h.Redirect(url)
|
|
return nil
|
|
}
|
|
|
|
data := user.(map[string]interface{})
|
|
|
|
return h.Render("home.html", renders.T{
|
|
"user": data,
|
|
})
|
|
}
|
|
|
|
type Callback struct {
|
|
tango.Ctx
|
|
session.Session
|
|
}
|
|
|
|
func (c *Callback) Get() error {
|
|
state := c.Form("state")
|
|
if state != oriState {
|
|
c.Abort(500)
|
|
return nil
|
|
}
|
|
|
|
ctx := context.Background()
|
|
httpClient := &http.Client{Timeout: 20 * time.Second}
|
|
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
|
|
|
|
code := c.Form("code")
|
|
tok, err := conf.Exchange(ctx, code)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Println(tok)
|
|
|
|
client := conf.Client(ctx, tok)
|
|
resp, err := client.Get("http://localhost:3000/api/v1/user")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
bs, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Println(string(bs))
|
|
|
|
var user = make(map[string]interface{})
|
|
err = json.NewDecoder(bytes.NewReader(bs)).Decode(&user)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Println(user)
|
|
c.Session.Set("user", user)
|
|
|
|
c.Redirect("/")
|
|
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
t := tango.Classic()
|
|
t.Use(renders.New(renders.Options{}))
|
|
t.Use(session.New(session.Options{}))
|
|
t.Get("/", new(Home))
|
|
t.Get("/callback", new(Callback))
|
|
t.Run()
|
|
}
|