-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
65 lines (58 loc) · 1.7 KB
/
auth.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
package main
import (
"log"
"net/http"
"net/url"
"github.com/gin-gonic/gin"
"github.com/stretchr/gomniauth"
"github.com/stretchr/objx"
)
func loginHandler(c *gin.Context) {
action := c.Param("action")
log.Println(action)
provider := c.Param("provider")
switch action {
case "login":
provider, err := gomniauth.Provider(provider)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Error when trying to get provider"})
return
}
loginUrl, err := provider.GetBeginAuthURL(nil, nil)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error when trying to GetBeginAuthURL"})
return
}
c.Redirect(http.StatusTemporaryRedirect, loginUrl)
case "callback":
provider, err := gomniauth.Provider(provider)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Error when trying to get provider"})
return
}
creds, err := provider.CompleteAuth(objx.MustFromURLQuery(c.Request.URL.RawQuery))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Error when trying complete Auth"})
return
}
user, err := provider.GetUser(creds)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Error when to get user"})
return
}
authCookieValue := objx.New(map[string]interface{}{
"name": user.Name(),
"avatar_url": user.AvatarURL(),
}).MustBase64()
unescapeCookie, err := url.QueryUnescape(authCookieValue)
if err != nil {
log.Println("QueryUnescape is failed:", err)
}
c.SetCookie("auth", unescapeCookie, 3600, "/", "", false, false)
c.Redirect(http.StatusTemporaryRedirect, "/api/chat.html")
return
default:
c.JSON(http.StatusNotFound, gin.H{"msg": "Auth action not supported"})
return
}
}