-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
105 lines (82 loc) · 2.26 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/google"
)
func main() {
r := gin.Default()
err := godotenv.Load()
if err != nil {
log.Fatal(".env file failed to load!")
}
clientID := os.Getenv("CLIENT_ID")
clientSecret := os.Getenv("CLIENT_SECRET")
clientCallbackURL := os.Getenv("CLIENT_CALLBACK_URL")
if clientID == "" || clientSecret == "" || clientCallbackURL == "" {
log.Fatal("Environment variables (CLIENT_ID, CLIENT_SECRET, CLIENT_CALLBACK_URL) are required")
}
goth.UseProviders(
google.New(clientID, clientSecret, clientCallbackURL))
r.LoadHTMLGlob("templates/*")
r.GET("/", home)
r.GET("/auth/:provider", signInWithProvider)
r.GET("/auth/:provider/callback", callbackHandler)
r.GET("/success", Success)
r.Run(":5000")
}
func home(c *gin.Context) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
err = tmpl.Execute(c.Writer, gin.H{})
if err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
}
func signInWithProvider(c *gin.Context) {
provider := c.Param("provider")
q := c.Request.URL.Query()
q.Add("provider", provider)
c.Request.URL.RawQuery = q.Encode()
gothic.BeginAuthHandler(c.Writer, c.Request)
}
func callbackHandler(c *gin.Context) {
provider := c.Param("provider")
q := c.Request.URL.Query()
q.Add("provider", provider)
c.Request.URL.RawQuery = q.Encode()
_, err := gothic.CompleteUserAuth(c.Writer, c.Request)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Redirect(http.StatusTemporaryRedirect, "/success")
}
func Success(c *gin.Context) {
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(fmt.Sprintf(`
<div style="
background-color: #fff;
padding: 40px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
">
<h1 style="
color: #333;
margin-bottom: 20px;
">You have Successfully signed in!</h1>
</div>
</div>
`)))
}