Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Instagram Provider #1725

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ The default group to assign all new users to.

### External Authentication Providers

We support `apple`, `azure`, `bitbucket`, `discord`, `facebook`, `figma`, `github`, `gitlab`, `google`, `keycloak`, `linkedin`, `notion`, `spotify`, `slack`, `twitch`, `twitter` and `workos` for external authentication.
We support `apple`, `azure`, `bitbucket`, `discord`, `facebook`, `figma`, `github`, `gitlab`, `google`, `instagram`, `keycloak`, `linkedin`, `notion`, `spotify`, `slack`, `twitch`, `twitter` and `workos` for external authentication.

Use the names as the keys underneath `external` to configure each separately.

Expand Down Expand Up @@ -742,6 +742,7 @@ Returns the publicly available settings for this auth instance.
"github": true,
"gitlab": true,
"google": true,
"instagram": true,
"keycloak": true,
"linkedin": true,
"notion": true,
Expand Down Expand Up @@ -1184,7 +1185,7 @@ Get access_token from external oauth provider
query params:

```
provider=apple | azure | bitbucket | discord | facebook | figma | github | gitlab | google | keycloak | linkedin | notion | slack | spotify | twitch | twitter | workos
provider=apple | azure | bitbucket | discord | facebook | figma | github | gitlab | google | instagram | keycloak | linkedin | notion | slack | spotify | twitch | twitter | workos

scopes=<optional additional scopes depending on the provider (email and name are requested by default)>
```
Expand Down
7 changes: 7 additions & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ GOTRUE_EXTERNAL_GITHUB_CLIENT_ID=""
GOTRUE_EXTERNAL_GITHUB_SECRET=""
GOTRUE_EXTERNAL_GITHUB_REDIRECT_URI="http://localhost:9999/callback"

# Instagram OAuth config
GOTRUE_EXTERNAL_INSTAGRAM_ENABLED="false"
GOTRUE_EXTERNAL_INSTAGRAM_CLIENT_ID=""
GOTRUE_EXTERNAL_INSTAGRAM_SECRET=""
GOTRUE_EXTERNAL_INSTAGRAM_REDIRECT_URI="http://localhost:9999/callback"
GOTRUE_EXTERNAL_INSTAGRAM_URL="https://api.instagram.com/oauth/authorize"

# Kakao OAuth config
GOTRUE_EXTERNAL_KAKAO_ENABLED="false"
GOTRUE_EXTERNAL_KAKAO_CLIENT_ID=""
Expand Down
2 changes: 2 additions & 0 deletions internal/api/external.go
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,8 @@ func (a *API) Provider(ctx context.Context, name string, scopes string) (provide
return provider.NewGitlabProvider(config.External.Gitlab, scopes)
case "google":
return provider.NewGoogleProvider(ctx, config.External.Google, scopes)
case "instagram":
return provider.NewInstagramProvider(config.External.Instagram, scopes)
case "kakao":
return provider.NewKakaoProvider(config.External.Kakao, scopes)
case "keycloak":
Expand Down
153 changes: 153 additions & 0 deletions internal/api/external_instagram_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package api

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"

jwt "github.com/golang-jwt/jwt/v5"
)

const (
instagramUser string = `{"id":"instagramTestId","username":"instagram_test"}`
instagramUserWrongID string = `{"id":"wrongTestId","username":"instagram_test"}`
)

func (ts *ExternalTestSuite) TestSignupExternalInstagram() {
req := httptest.NewRequest(http.MethodGet, "http://localhost/authorize?provider=instagram", nil)
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
ts.Require().Equal(http.StatusFound, w.Code)
u, err := url.Parse(w.Header().Get("Location"))
ts.Require().NoError(err, "redirect url parse failed")
q := u.Query()
ts.Equal(ts.Config.External.Instagram.RedirectURI, q.Get("redirect_uri"))
ts.Equal(ts.Config.External.Instagram.ClientID, []string{q.Get("client_id")})
ts.Equal("code", q.Get("response_type"))
ts.Equal("user_profile", q.Get("scope"))

claims := ExternalProviderClaims{}
p := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Name}))
_, err = p.ParseWithClaims(q.Get("state"), &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(ts.Config.JWT.Secret), nil
})
ts.Require().NoError(err)

ts.Equal("instagram", claims.Provider)
ts.Equal(ts.Config.SiteURL, claims.SiteURL)
}

func InstagramTestSignupSetup(ts *ExternalTestSuite, tokenCount *int, userCount *int, code string, user string) *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/oauth/access_token":
*tokenCount++
ts.Equal(code, r.FormValue("code"))
ts.Equal("authorization_code", r.FormValue("grant_type"))
ts.Equal(ts.Config.External.Instagram.RedirectURI, r.FormValue("redirect_uri"))

w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, `{"access_token":"instagram_token","user_id":"instagramTestId"}`)
case "/me":
*userCount++
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, user)
default:
w.WriteHeader(500)
ts.Fail("unknown instagram oauth call %s", r.URL.Path)
}
}))

ts.Config.External.Instagram.URL = server.URL

return server
}

func (ts *ExternalTestSuite) TestSignupExternalInstagram_AuthorizationCode() {
ts.Config.DisableSignup = false
tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUser)
defer server.Close()

u := performAuthorization(ts, "instagram", code, "")

assertAuthorizationSuccess(ts, u, tokenCount, userCount, "", "instagram_test", "instagramTestId", "")
}

func (ts *ExternalTestSuite) TestSignupExternalInstagramDisableSignupErrorWhenNoUser() {
ts.Config.DisableSignup = true

tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUser)
defer server.Close()

u := performAuthorization(ts, "instagram", code, "")

assertAuthorizationFailure(ts, u, "Signups not allowed for this instance", "access_denied", "")
}

func (ts *ExternalTestSuite) TestSignupExternalInstagramDisableSignupSuccessWithExistingUser() {
ts.Config.DisableSignup = true

ts.createUser("instagramTestId", "", "instagram_test", "", "")

tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUser)
defer server.Close()

u := performAuthorization(ts, "instagram", code, "")

assertAuthorizationSuccess(ts, u, tokenCount, userCount, "", "instagram_test", "instagramTestId", "")
}

func (ts *ExternalTestSuite) TestInviteTokenExternalInstagramSuccessWhenMatchingToken() {
ts.createUser("instagramTestId", "", "", "", "invite_token")

tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUser)
defer server.Close()

u := performAuthorization(ts, "instagram", code, "invite_token")

assertAuthorizationSuccess(ts, u, tokenCount, userCount, "", "instagram_test", "instagramTestId", "")
}

func (ts *ExternalTestSuite) TestInviteTokenExternalInstagramErrorWhenNoMatchingToken() {
tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUser)
defer server.Close()

w := performAuthorizationRequest(ts, "instagram", "invite_token")
ts.Require().Equal(http.StatusNotFound, w.Code)
}

func (ts *ExternalTestSuite) TestInviteTokenExternalInstagramErrorWhenWrongToken() {
ts.createUser("instagramTestId", "", "", "", "invite_token")

tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUser)
defer server.Close()

w := performAuthorizationRequest(ts, "instagram", "wrong_token")
ts.Require().Equal(http.StatusNotFound, w.Code)
}

func (ts *ExternalTestSuite) TestInviteTokenExternalInstagramErrorWhenIDDoesntMatch() {
ts.createUser("instagramTestId", "", "", "", "invite_token")

tokenCount, userCount := 0, 0
code := "authcode"
server := InstagramTestSignupSetup(ts, &tokenCount, &userCount, code, instagramUserWrongID)
defer server.Close()

u := performAuthorization(ts, "instagram", code, "invite_token")

assertAuthorizationFailure(ts, u, "User ID from external provider doesn't match invited user", "invalid_request", "")
}
106 changes: 106 additions & 0 deletions internal/api/provider/instagram.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package provider

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/utilities"
"golang.org/x/oauth2"
)

const (
defaultInstagramApiBase = "https://graph.instagram.com"
)

type instagramUser struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email,omitempty"`
Picture string `json:"profile_picture,omitempty"`
}

func NewInstagramProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) {
if err := ext.ValidateOAuth(); err != nil {
return nil, err
}

authHost := chooseHost(ext.URL, defaultInstagramApiBase)

return &instagramProvider{
Config: &oauth2.Config{
ClientID: ext.ClientID[0],
ClientSecret: ext.Secret,
Endpoint: oauth2.Endpoint{
AuthURL: "https://api.instagram.com/oauth/authorize",
TokenURL: "https://api.instagram.com/oauth/access_token",
},
RedirectURL: ext.RedirectURI,
Scopes: []string{"user_profile", "user_media"},
},
APIPath: authHost,
}, nil
}

type instagramProvider struct {
*oauth2.Config
APIPath string
}

func (g instagramProvider) GetOAuthToken(code string) (*oauth2.Token, error) {
return g.Exchange(context.Background(), code)
}

func (g instagramProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) {
var u instagramUser

req, err := http.NewRequest("GET", g.APIPath+"/me?fields=id,username,email,profile_picture&access_token="+tok.AccessToken, nil)
if err != nil {
return nil, err
}

client := &http.Client{Timeout: defaultTimeout}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer utilities.SafeClose(resp.Body)

if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
return nil, fmt.Errorf("a %v error occurred while retrieving user from Instagram", resp.StatusCode)
}

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &u)
if err != nil {
return nil, err
}

data := &UserProvidedData{}
if u.Email != "" {
data.Emails = []Email{{
Email: u.Email,
Verified: true,
Primary: true,
}}
}

data.Metadata = &Claims{
Issuer: g.APIPath,
Subject: u.ID,
Name: u.Username,
Picture: u.Picture,

// To be deprecated
AvatarURL: u.Picture,
FullName: u.Username,
ProviderId: u.ID,
}
return data, nil
}
2 changes: 2 additions & 0 deletions internal/api/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type ProviderSettings struct {
GitHub bool `json:"github"`
GitLab bool `json:"gitlab"`
Google bool `json:"google"`
Instagram bool `json:"instagram"`
Keycloak bool `json:"keycloak"`
Kakao bool `json:"kakao"`
Linkedin bool `json:"linkedin"`
Expand Down Expand Up @@ -56,6 +57,7 @@ func (a *API) Settings(w http.ResponseWriter, r *http.Request) error {
GitHub: config.External.Github.Enabled,
GitLab: config.External.Gitlab.Enabled,
Google: config.External.Google.Enabled,
Instagram: config.External.Instagram.Enabled,
Kakao: config.External.Kakao.Enabled,
Keycloak: config.External.Keycloak.Enabled,
Linkedin: config.External.Linkedin.Enabled,
Expand Down
1 change: 1 addition & 0 deletions internal/api/settings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func TestSettings_DefaultProviders(t *testing.T) {
require.True(t, p.Slack)
require.True(t, p.SlackOIDC)
require.True(t, p.Google)
require.True(t, p.Instagram)
require.True(t, p.Kakao)
require.True(t, p.Keycloak)
require.True(t, p.Linkedin)
Expand Down
1 change: 1 addition & 0 deletions internal/conf/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ type ProviderConfiguration struct {
Github OAuthProviderConfiguration `json:"github"`
Gitlab OAuthProviderConfiguration `json:"gitlab"`
Google OAuthProviderConfiguration `json:"google"`
Instagram OAuthProviderConfiguration `json:"instagram"`
Kakao OAuthProviderConfiguration `json:"kakao"`
Notion OAuthProviderConfiguration `json:"notion"`
Keycloak OAuthProviderConfiguration `json:"keycloak"`
Expand Down