-
Notifications
You must be signed in to change notification settings - Fork 378
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 TikTok Provider #1807
Open
dhamanutd
wants to merge
6
commits into
supabase:master
Choose a base branch
from
dhamanutd:tiktok-provider
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add TikTok Provider #1807
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
50f8028
add tiktok provider
dhamanutd 05807be
enhance oauth url of tiktok
dhamanutd eba161e
integrate tiktok
dhamanutd b1031d1
oauth access_token to metadata
dhamanutd 7a2ed7b
Merge branch 'supabase:master' into tiktok-provider
dhamanutd 1edc74e
remove access token to identity data custom
dhamanutd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
package api | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"net/url" | ||
|
||
jwt "github.com/golang-jwt/jwt/v5" | ||
) | ||
|
||
func (ts *ExternalTestSuite) TestSignupExternalTikTok() { | ||
req := httptest.NewRequest(http.MethodGet, "http://localhost/authorize?provider=tiktok", 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.TikTok.RedirectURI, q.Get("redirect_uri")) | ||
ts.Equal(ts.Config.External.TikTok.ClientID, q.Get("client_id")) | ||
ts.Equal("code", q.Get("response_type")) | ||
ts.Equal("user.info.basic,video.list", 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("tiktok", claims.Provider) | ||
ts.Equal(ts.Config.SiteURL, claims.SiteURL) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,190 @@ | ||
package provider | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"net/http" | ||
"net/url" | ||
"slices" | ||
"strings" | ||
|
||
"github.com/supabase/auth/internal/conf" | ||
"github.com/supabase/auth/internal/utilities" | ||
"golang.org/x/oauth2" | ||
) | ||
|
||
const ( | ||
defaultTikTokIssuerURL = "https://www.tiktok.com" | ||
) | ||
|
||
type tiktokProvider struct { | ||
*oauth2.Config | ||
Client *http.Client | ||
} | ||
|
||
type tiktokUserResponse struct { | ||
Data tiktokUserData `json:"data"` | ||
Error tiktokErrorData `json:"error"` | ||
} | ||
type tiktokUserData struct { | ||
User tiktokUser `json:"user"` | ||
} | ||
|
||
type tiktokErrorData struct { | ||
Code string `json:"code"` | ||
Message string `json:"message"` | ||
LogID string `json:"log_id"` | ||
} | ||
|
||
type tiktokUser struct { | ||
ID string `json:"open_id"` | ||
UnionID string `json:"union_id"` | ||
DisplayName string `json:"display_name"` | ||
AvatarUrl string `json:"avatar_url"` | ||
AvatarUrlLarge string `json:"avatar_large_url"` | ||
BioDescription string `json:"bio_description"` | ||
ProfileDeepLink string `json:"profile_deep_link"` | ||
Username string `json:"username"` | ||
IsVerified bool `json:"is_verified"` | ||
FollowerCount int64 `json:"follower_count"` | ||
FollowingCount int64 `json:"following_count"` | ||
LikesCount int64 `json:"likes_count"` | ||
VideoCount int64 `json:"video_count"` | ||
} | ||
|
||
// NewTikTokProvider creates a TikTok account provider. | ||
func NewTikTokProvider(ext conf.OAuthProviderConfiguration, scopes string) (OAuthProvider, error) { | ||
if err := ext.ValidateOAuth(); err != nil { | ||
return nil, err | ||
} | ||
|
||
authorizePath := chooseHost(ext.URL, "www.tiktok.com") | ||
tokenPath := chooseHost(ext.URL, "open.tiktokapis.com") | ||
|
||
oauthScopes := []string{ | ||
"user.info.basic", | ||
"video.list", | ||
} | ||
|
||
if scopes != "" { | ||
oauthScopes = append(oauthScopes, strings.Split(scopes, ",")...) | ||
} | ||
|
||
return &tiktokProvider{ | ||
Config: &oauth2.Config{ | ||
ClientID: ext.ClientID[0], | ||
ClientSecret: ext.Secret, | ||
Endpoint: oauth2.Endpoint{ | ||
AuthURL: authorizePath + "/v2/auth/authorize/", | ||
TokenURL: tokenPath + "/v2/oauth/token/", | ||
}, | ||
Scopes: oauthScopes, | ||
RedirectURL: ext.RedirectURI, | ||
}, | ||
}, nil | ||
} | ||
|
||
func (t tiktokProvider) AuthCodeURL(state string, args ...oauth2.AuthCodeOption) string { | ||
opts := make([]oauth2.AuthCodeOption, 0, len(args)+2) | ||
opts = append(opts, oauth2.SetAuthURLParam("client_key", t.Config.ClientID)) | ||
opts = append(opts, oauth2.SetAuthURLParam("scope", strings.Join(t.Config.Scopes, ","))) | ||
opts = append(opts, args...) | ||
|
||
authURL := t.Config.AuthCodeURL(state, opts...) | ||
if authURL != "" { | ||
if u, err := url.Parse(authURL); err != nil { | ||
u.RawQuery = strings.ReplaceAll(u.RawQuery, "+", ",") | ||
authURL = u.String() | ||
} | ||
} | ||
return authURL | ||
} | ||
|
||
func (t tiktokProvider) GetOAuthToken(code string) (*oauth2.Token, error) { | ||
opts := make([]oauth2.AuthCodeOption, 0, 1) | ||
opts = append(opts, oauth2.SetAuthURLParam("client_key", t.Config.ClientID)) | ||
return t.Exchange(context.Background(), code, opts...) | ||
} | ||
|
||
func (t tiktokProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) { | ||
var u tiktokUserResponse | ||
|
||
fields := []string{ | ||
"open_id", | ||
"union_id", | ||
"display_name", | ||
"avatar_url", | ||
"avatar_large_url", | ||
} | ||
if slices.Contains(t.Scopes, "user.info.profile") { | ||
fields = append(fields, []string{ | ||
"bio_description", | ||
"profile_deep_link", | ||
"username", | ||
"is_verified", | ||
}...) | ||
} | ||
if slices.Contains(t.Scopes, "user.info.stats") { | ||
fields = append(fields, []string{ | ||
"follower_count", | ||
"following_count", | ||
"likes_count", | ||
"video_count", | ||
}...) | ||
} | ||
params := url.Values{} | ||
params.Add("fields", strings.Join(fields, ",")) | ||
|
||
req, err := http.NewRequest("GET", "https://open.tiktokapis.com/v2/user/info/?"+params.Encode(), nil) | ||
if err != nil { | ||
return nil, err | ||
} | ||
req.Header.Set("Authorization", "Bearer "+tok.AccessToken) | ||
client := &http.Client{Timeout: defaultTimeout} | ||
resp, err := client.Do(req) | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer utilities.SafeClose(resp.Body) | ||
|
||
if err := json.NewDecoder(resp.Body).Decode(&u); err != nil { | ||
return nil, err | ||
} | ||
if u.Error.Code != "ok" { | ||
return nil, errors.New(u.Error.Message) | ||
} | ||
|
||
return &UserProvidedData{ | ||
Emails: []Email{ | ||
{ | ||
Email: u.Data.User.Username, | ||
Verified: false, | ||
Primary: false, | ||
}, | ||
}, | ||
Metadata: &Claims{ | ||
Issuer: defaultTikTokIssuerURL, | ||
Subject: u.Data.User.ID, | ||
Name: u.Data.User.DisplayName, | ||
Picture: u.Data.User.AvatarUrl, | ||
PreferredUsername: u.Data.User.Username, | ||
UserNameKey: u.Data.User.Username, | ||
Profile: u.Data.User.ProfileDeepLink, | ||
CustomClaims: map[string]interface{}{ | ||
"scopes": strings.Join(t.Scopes, ","), | ||
"is_verified": u.Data.User.IsVerified, | ||
"union_id": u.Data.User.UnionID, | ||
"follower_count": u.Data.User.FollowerCount, | ||
"following_count": u.Data.User.FollowingCount, | ||
"likes_count": u.Data.User.LikesCount, | ||
"video_count": u.Data.User.VideoCount, | ||
}, | ||
|
||
// To be deprecated | ||
AvatarURL: u.Data.User.AvatarUrl, | ||
FullName: u.Data.User.DisplayName, | ||
ProviderId: u.Data.User.ID, | ||
}, | ||
}, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this true by default?