-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (73 loc) · 2.31 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
type response struct {
Success bool `json:"success"`
Error string `json:"error"`
Data interface{} `json:"data"`
}
const apiBase = "https://api.trax.management"
func githubAuth(c echo.Context) error {
key := os.Getenv("GH_CLIENT_ID")
secret := os.Getenv("GH_CLIENT_SECRET")
code := c.QueryParam("code")
if len(key) < 10 || len(secret) < 10 {
return c.JSON(http.StatusNotImplemented, response{Success: false, Error: "Github Client ID or Secret are missing"})
}
config := &oauth2.Config{
ClientID: key,
ClientSecret: secret,
Endpoint: oauth2.Endpoint{
TokenURL: "https://github.com/login/oauth/access_token",
},
}
token, err := config.Exchange(oauth2.NoContext, code)
if !token.Valid() {
log.Println("Error", err)
return c.JSON(http.StatusOK, response{Success: false, Error: fmt.Sprintf("Error fetching github token: %s", err)})
}
return c.JSON(http.StatusOK, response{Success: true, Data: token})
}
func googleAuth(c echo.Context) error {
key := os.Getenv("GOOGLE_CLIENT_ID")
secret := os.Getenv("GOOGLE_CLIENT_SECRET")
code := c.QueryParam("code")
randState := fmt.Sprintf("st%d", time.Now().UnixNano())
if len(key) < 10 || len(secret) < 10 {
return c.JSON(http.StatusNotImplemented, response{Success: false, Error: "Google Client ID or Secret are missing"})
}
config := &oauth2.Config{
ClientID: key,
ClientSecret: secret,
Endpoint: google.Endpoint,
Scopes: []string{"https://www.googleapis.com/auth/spreadsheets"},
RedirectURL: apiBase + "/google/auth",
}
if len(code) < 5 {
return c.Redirect(http.StatusTemporaryRedirect, config.AuthCodeURL(randState))
}
token, err := config.Exchange(oauth2.NoContext, code)
if !token.Valid() {
log.Println("Error", err)
return c.JSON(http.StatusOK, response{Success: false, Error: fmt.Sprintf("Error fetching google token: %s", err)})
}
return c.JSON(http.StatusOK, response{Success: true, Data: token})
}
func main() {
godotenv.Load()
e := echo.New()
e.Use(middleware.CORS())
e.GET("/github/auth", githubAuth)
e.GET("/google/auth", googleAuth)
e.Logger.Fatal(e.Start(":" + os.Getenv("PORT")))
}