chore: add github.com user id association (#14045)

* chore: add github.com user id association

This will eventually be used to show an indicator in the UI
to star the repository if you've been using Coder for a while
and have not starred the repo.

If you have, we'll never show a thing!

* gen

* Fix model query

* Fix linting

* Ignore auditing github.com user id

* Add test

* Fix gh url var name

* Update migration

* Update coderd/database/dbauthz/dbauthz.go

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>

* Fix updating to when the token changes

* Fix migration

---------

Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com>
This commit is contained in:
Kyle Carberry
2024-08-02 11:49:36 -05:00
committed by GitHub
parent 4d4d27c509
commit 6e36082b0f
25 changed files with 222 additions and 37 deletions

View File

@ -154,7 +154,7 @@ func (c *Config) RefreshToken(ctx context.Context, db database.Store, externalAu
retryCtx, retryCtxCancel := context.WithTimeout(ctx, time.Second)
defer retryCtxCancel()
validate:
valid, _, err := c.ValidateToken(ctx, token)
valid, user, err := c.ValidateToken(ctx, token)
if err != nil {
return externalAuthLink, xerrors.Errorf("validate external auth token: %w", err)
}
@ -189,7 +189,22 @@ validate:
return updatedAuthLink, xerrors.Errorf("update external auth link: %w", err)
}
externalAuthLink = updatedAuthLink
// Update the associated users github.com username if the token is for github.com.
if IsGithubDotComURL(c.AuthCodeURL("")) && user != nil {
err = db.UpdateUserGithubComUserID(ctx, database.UpdateUserGithubComUserIDParams{
ID: externalAuthLink.UserID,
GithubComUserID: sql.NullInt64{
Int64: user.ID,
Valid: true,
},
})
if err != nil {
return externalAuthLink, xerrors.Errorf("update user github com user id: %w", err)
}
}
}
return externalAuthLink, nil
}
@ -233,6 +248,7 @@ func (c *Config) ValidateToken(ctx context.Context, link *oauth2.Token) (bool, *
err = json.NewDecoder(res.Body).Decode(&ghUser)
if err == nil {
user = &codersdk.ExternalAuthUser{
ID: ghUser.GetID(),
Login: ghUser.GetLogin(),
AvatarURL: ghUser.GetAvatarURL(),
ProfileURL: ghUser.GetHTMLURL(),
@ -291,6 +307,7 @@ func (c *Config) AppInstallations(ctx context.Context, token string) ([]codersdk
ID: int(installation.GetID()),
ConfigureURL: installation.GetHTMLURL(),
Account: codersdk.ExternalAuthUser{
ID: account.GetID(),
Login: account.GetLogin(),
AvatarURL: account.GetAvatarURL(),
ProfileURL: account.GetHTMLURL(),
@ -947,3 +964,13 @@ type roundTripper func(req *http.Request) (*http.Response, error)
func (r roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
return r(req)
}
// IsGithubDotComURL returns true if the given URL is a github.com URL.
func IsGithubDotComURL(str string) bool {
str = strings.ToLower(str)
ghURL, err := url.Parse(str)
if err != nil {
return false
}
return ghURL.Host == "github.com"
}