Skip to content

Commit

Permalink
Add ApprovalForce to AuthCodeOptions
Browse files Browse the repository at this point in the history
* Extract access token validity check to a function
  • Loading branch information
mgyongyosi committed Nov 15, 2022
1 parent 2055d92 commit f916aa2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
4 changes: 3 additions & 1 deletion pkg/api/login_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
code := ctx.Query("code")
if code == "" {
// FIXME: access_type is a Google OAuth2 specific thing, consider refactoring this and moving to google_oauth.go
opts := []oauth2.AuthCodeOption{oauth2.AccessTypeOffline}
// ApprovalForce is required to get the refresh token every time the user logs in with Google OAuth (without this the
// refresh token is only provided when the user first gives consent)
opts := []oauth2.AuthCodeOption{oauth2.AccessTypeOffline, oauth2.ApprovalForce}

if provider.UsePKCE {
ascii, pkce, err := genPKCECode()
Expand Down
15 changes: 14 additions & 1 deletion pkg/services/contexthandler/contexthandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ func (h *ContextHandler) initContextWithToken(reqContext *models.ReqContext, org
oauthToken, exists, _ := h.oauthTokenService.HasOAuthEntry(ctx, queryResult)
if exists {
// Skip where the OAuthExpiry is default/zero/unset
if !oauthToken.OAuthExpiry.IsZero() && oauthToken.OAuthExpiry.Round(0).Add(-oauthtoken.ExpiryDelta).Before(getTime()) {
if h.hasAccessTokenExpired(oauthToken) {
reqContext.Logger.Info("access token expired", "userId", query.UserID, "expiry", fmt.Sprintf("%v", oauthToken.OAuthExpiry))

// If the User doesn't have a refresh_token or refreshing the token was unsuccessful then log out the User and Invalidate the OAuth tokens
Expand Down Expand Up @@ -726,3 +726,16 @@ func AuthHTTPHeaderListFromContext(c context.Context) *AuthHTTPHeaderList {
}
return nil
}

func (h *ContextHandler) hasAccessTokenExpired(token *models.UserAuth) bool {
if token.OAuthExpiry.IsZero() {
return false
}

getTime := h.GetTime
if getTime == nil {
getTime = time.Now
}

return token.OAuthExpiry.Round(0).Add(-oauthtoken.ExpiryDelta).Before(getTime())
}

0 comments on commit f916aa2

Please sign in to comment.