add oauth flow routes
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go-cal/pkg/apis/google"
|
||||
"go-cal/pkg/config"
|
||||
"go-cal/pkg/storage"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RedirectToAuth url
|
||||
func RedirectToAuth(c *gin.Context) {
|
||||
conf := config.Get()
|
||||
if conf == nil {
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := url.Parse(conf.Google.AuthURL)
|
||||
if err != nil {
|
||||
c.AbortWithError(http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
_ = u
|
||||
|
||||
qs := url.Values{}
|
||||
qs.Set("client_id", conf.Google.ClientID)
|
||||
qs.Set("redirect_uri", conf.Google.RedirectURL)
|
||||
qs.Set("scope", strings.Join(conf.Google.Scopes, " "))
|
||||
qs.Set("access_type", "offline")
|
||||
qs.Set("response_type", "code")
|
||||
|
||||
targetURL := u.String() + "?" + qs.Encode()
|
||||
c.Redirect(http.StatusTemporaryRedirect, targetURL)
|
||||
}
|
||||
|
||||
// OAuthResponse -
|
||||
func OAuthResponse(c *gin.Context) {
|
||||
if respError := c.Query("error"); len(respError) > 0 {
|
||||
c.AbortWithError(http.StatusOK, fmt.Errorf("Get error : %s", respError))
|
||||
return
|
||||
}
|
||||
code := c.Query("code")
|
||||
if len(code) == 0 {
|
||||
c.AbortWithError(http.StatusOK, fmt.Errorf("Get response code fail"))
|
||||
return
|
||||
}
|
||||
|
||||
token, err := google.OAuthExchangeCodeToToken(code)
|
||||
if err != nil {
|
||||
c.AbortWithError(http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
|
||||
t := time.Now().Unix()
|
||||
token.ExpiresIn += t
|
||||
|
||||
st := storage.Get()
|
||||
if st == nil {
|
||||
c.AbortWithError(http.StatusInternalServerError, fmt.Errorf("storage object not init"))
|
||||
return
|
||||
}
|
||||
st.Set("google_token", token)
|
||||
|
||||
c.Redirect(http.StatusTemporaryRedirect, "/")
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"go-cal/route/auth"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// NewEngine -
|
||||
func NewEngine() *gin.Engine {
|
||||
e := gin.New()
|
||||
|
||||
e.Use(gin.Logger())
|
||||
e.Use(gin.Recovery())
|
||||
|
||||
return e
|
||||
}
|
||||
|
||||
// SetRoutes -
|
||||
func SetRoutes(e *gin.Engine) {
|
||||
e.GET("/health", func(c *gin.Context) {
|
||||
c.String(http.StatusOK, "ok")
|
||||
})
|
||||
|
||||
e.GET("/auth", auth.RedirectToAuth)
|
||||
|
||||
e.GET("/auth/verify", auth.OAuthResponse)
|
||||
}
|
||||
Reference in New Issue
Block a user