Skip to content

Commit

Permalink
refactor and flush cache when new user is registered
Browse files Browse the repository at this point in the history
  • Loading branch information
sedflix committed Oct 3, 2020
1 parent 8656164 commit 820c30c
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 40 deletions.
39 changes: 5 additions & 34 deletions src/fitness.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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),
)
Expand Down Expand Up @@ -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),
)
Expand Down Expand Up @@ -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,
)
}
18 changes: 14 additions & 4 deletions src/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
12 changes: 10 additions & 2 deletions src/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -76,15 +83,15 @@ 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))
return
}

// 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,
Expand All @@ -103,6 +110,7 @@ func oAuthCallbackHandler(ctx *gin.Context) {
return
}

flushCache()
ctx.Redirect(http.StatusTemporaryRedirect, "/")
}

Expand Down
36 changes: 36 additions & 0 deletions src/view.go
Original file line number Diff line number Diff line change
@@ -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,
)
}

0 comments on commit 820c30c

Please sign in to comment.