@@ -2,6 +2,7 @@ package auth
22
33import (
44 "context"
5+ "errors"
56 "fmt"
67 "os"
78 "path/filepath"
@@ -15,6 +16,8 @@ import (
1516 "go.jetpack.io/pkg/sandbox/auth/internal/tokenstore"
1617)
1718
19+ var ErrNotLoggedIn = fmt .Errorf ("not logged in" )
20+
1821type Client struct {
1922 issuer string
2023 clientID string
@@ -58,40 +61,37 @@ func (c *Client) LogoutFlow() error {
5861 return c .RevokeSession ()
5962}
6063
61- // GetSession returns the current valid session token, if any. If token is expired,
62- // it will attempt to refresh it. If no token is found, or is unable to be refreshed,
63- // it will return nil and false.
64- // TODO: automatically refresh token as needed
65- func (c * Client ) GetSession (ctx context.Context ) (* session.Token , bool ) {
66- tok := c .store .ReadToken (c .issuer , c .clientID )
67- if tok == nil {
68- return nil , false
64+ // GetSession returns the current valid session token, if any. If token is
65+ // expired, it will attempt to refresh it. If no token is found, or is unable
66+ // to be refreshed, it will return error.
67+ func (c * Client ) GetSession (ctx context.Context ) (* session.Token , error ) {
68+ tok , err := c .store .ReadToken (c .issuer , c .clientID )
69+ if errors .Is (err , os .ErrNotExist ) {
70+ return nil , ErrNotLoggedIn
71+ } else if err != nil {
72+ return nil , err
6973 }
7074
7175 // Refresh if the token is no longer valid:
7276 if ! tok .Valid () {
73- tok = c .refresh (ctx , tok )
74- if ! tok . Valid () {
75- return nil , false
77+ tok , err = c .refresh (ctx , tok )
78+ if err != nil {
79+ return nil , err
7680 }
7781 }
7882
79- return tok , true
83+ return tok , nil
8084}
8185
8286func (c * Client ) refresh (
8387 ctx context.Context ,
8488 tok * session.Token ,
85- ) * session.Token {
86- if tok == nil {
87- return nil
88- }
89-
89+ ) (* session.Token , error ) {
9090 // TODO: figure out how to share oidc provider and oauth2 client
9191 // with auth flow:
9292 provider , err := oidc .NewProvider (ctx , c .issuer )
9393 if err != nil {
94- return tok
94+ return tok , err
9595 }
9696
9797 conf := oauth2.Config {
@@ -104,18 +104,19 @@ func (c *Client) refresh(
104104 tokenSource := conf .TokenSource (ctx , & tok .Token )
105105 newToken , err := tokenSource .Token ()
106106 if err != nil {
107- return tok
107+ return tok , err
108108 }
109109
110110 if newToken .AccessToken != tok .AccessToken {
111111 tok .Token = * newToken
112+ tok .IDToken = newToken .Extra ("id_token" ).(string )
112113 err = c .store .WriteToken (c .issuer , c .clientID , tok )
113114 if err != nil {
114- return tok
115+ return tok , err
115116 }
116117 }
117118
118- return tok
119+ return tok , nil
119120}
120121
121122func (c * Client ) RevokeSession () error {
0 commit comments