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, "/") }