From 820c30c76a59221ddd294f173e70bcc2d3884380 Mon Sep 17 00:00:00 2001 From: sedflix Date: Sat, 3 Oct 2020 12:54:08 +0530 Subject: [PATCH] refactor and flush cache when new user is registered --- src/fitness.go | 39 +++++---------------------------------- src/main.go | 18 ++++++++++++++---- src/oauth.go | 12 ++++++++++-- src/view.go | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 40 deletions(-) create mode 100644 src/view.go diff --git a/src/fitness.go b/src/fitness.go index 698050e..e8c34e9 100644 --- a/src/fitness.go +++ b/src/fitness.go @@ -3,15 +3,11 @@ package main import ( "context" "fmt" - "github.com/gin-gonic/contrib/sessions" - "github.com/gin-gonic/gin" "github.com/snabb/isoweek" "google.golang.org/api/fitness/v1" "google.golang.org/api/option" "google.golang.org/api/people/v1" "log" - "net/http" - "sort" "strings" "time" ) @@ -34,9 +30,10 @@ func (a allUserInfo) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // getFitnessService returns the service object google fitness with apt permission to read steps func getFitnessService(user OAuthUser) (*fitness.Service, error) { - tokenSource := config.TokenSource(context.TODO(), user.Token) + tokenSource := getTokenSource(user) + service, err := fitness.NewService( - context.TODO(), + context.Background(), option.WithScopes(fitness.FitnessActivityReadScope), option.WithTokenSource(tokenSource), ) @@ -124,9 +121,9 @@ func getAllStepsOfUser(user OAuthUser) (int64, int64, error) { } func getProfilePicUrl(user OAuthUser) (Name string, Url string, err error) { - tokenSource := config.TokenSource(context.TODO(), user.Token) + tokenSource := getTokenSource(user) service, err := people.NewService( - context.TODO(), + context.Background(), option.WithScopes(people.UserinfoProfileScope), option.WithTokenSource(tokenSource), ) @@ -219,29 +216,3 @@ func getAll() ([]userInfoElement, error) { return result, nil } -func list(ctx *gin.Context) { - _ = sessions.Default(ctx) - - result, err := getAll() - if err != nil { - _ = ctx.AbortWithError(http.StatusInternalServerError, err) - return - } - sort.Sort(allUserInfo(result)) - ctx.IndentedJSON(http.StatusOK, result) -} - -func index(ctx *gin.Context) { - _ = sessions.Default(ctx) - result, err := getAll() - if err != nil { - _ = ctx.AbortWithError(http.StatusInternalServerError, err) - return - } - sort.Sort(allUserInfo(result)) - ctx.HTML( - http.StatusOK, - "index.html", - result, - ) -} diff --git a/src/main.go b/src/main.go index 67fbd8d..1eb6103 100644 --- a/src/main.go +++ b/src/main.go @@ -6,10 +6,20 @@ import ( "github.com/gin-contrib/cache/persistence" "github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/gin" + "log" "net/http" "time" ) +var cacheStore *persistence.InMemoryStore + +func flushCache() { + err := cacheStore.Flush() + if err != nil { + log.Printf("unable to flush the page cahce due to %v", err) + } +} + func ErrorHandle() gin.HandlerFunc { return func(c *gin.Context) { c.Next() @@ -64,13 +74,13 @@ func main() { gin.SetMode(gin.ReleaseMode) // cache setup - cacheStore := persistence.NewInMemoryStore(time.Minute) + cacheStore = persistence.NewInMemoryStore(time.Minute) // setup session cookie storage var store = sessions.NewCookieStore([]byte("secret")) router.Use(sessions.Sessions("goquestsession", store)) - // custom error handling TODO: add ui + // custom error handling router.Use(ErrorHandle()) // static @@ -80,8 +90,8 @@ func main() { router.StaticFile("/favicon.ico", "./web/favicon.ico") router.LoadHTMLFiles("web/index.html") - router.GET("/", cache.CachePage(cacheStore, 2*time.Minute, index)) // index page - router.GET("/list/json", list) // show information in json + router.GET("/", cache.CachePageWithoutQuery(cacheStore, 10*time.Minute, index)) // index page + router.GET("/list/json", list) // show information in json router.GET("/login", authoriseUserHandler) // to register router.GET("/auth", oAuthCallbackHandler) // oauth callback diff --git a/src/oauth.go b/src/oauth.go index 4c1beea..3e32f27 100644 --- a/src/oauth.go +++ b/src/oauth.go @@ -32,6 +32,13 @@ var scope = []string{ "email", } +// getTokenSource refreshes the token +func getTokenSource(user OAuthUser) oauth2.TokenSource { + tokenSource := config.TokenSource(context.Background(), user.Token) + tokenSource = oauth2.ReuseTokenSource(user.Token, tokenSource) + return tokenSource +} + // setupOAuthClientCredentials will create oauth2.config and oidc.Provider // using fileName the path to a json storing credentials obtained from google console func setupOAuthClientCredentials(fileName string) (err error) { @@ -76,7 +83,7 @@ func oAuthCallbackHandler(ctx *gin.Context) { // get oauth TOKEN code := ctx.Query("code") - token, err := config.Exchange(context.TODO(), code, oauth2.AccessTypeOffline) + token, err := config.Exchange(context.Background(), code, oauth2.AccessTypeOffline, oauth2.ApprovalForce) if err != nil { _ = ctx.AbortWithError(http.StatusInternalServerError, fmt.Errorf("oauth code-token exchange failed due to %v", err)) @@ -84,7 +91,7 @@ func oAuthCallbackHandler(ctx *gin.Context) { } // make token source for using it in oidc call - tokenSource := config.TokenSource(context.TODO(), token) + tokenSource := config.TokenSource(context.Background(), token) userInfo, err := oidcProvider.UserInfo(context.Background(), tokenSource) if err != nil { _ = ctx.AbortWithError(http.StatusInternalServerError, @@ -103,6 +110,7 @@ func oAuthCallbackHandler(ctx *gin.Context) { return } + flushCache() ctx.Redirect(http.StatusTemporaryRedirect, "/") } diff --git a/src/view.go b/src/view.go new file mode 100644 index 0000000..55c661c --- /dev/null +++ b/src/view.go @@ -0,0 +1,36 @@ +package main + +import ( + "github.com/gin-gonic/contrib/sessions" + "github.com/gin-gonic/gin" + "net/http" + "sort" +) + +func list(ctx *gin.Context) { + _ = sessions.Default(ctx) + flushCache() + + result, err := getAll() + if err != nil { + _ = ctx.AbortWithError(http.StatusInternalServerError, err) + return + } + sort.Sort(allUserInfo(result)) + ctx.IndentedJSON(http.StatusOK, result) +} + +func index(ctx *gin.Context) { + _ = sessions.Default(ctx) + result, err := getAll() + if err != nil { + _ = ctx.AbortWithError(http.StatusInternalServerError, err) + return + } + sort.Sort(allUserInfo(result)) + ctx.HTML( + http.StatusOK, + "index.html", + result, + ) +}