75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package linkedin
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"golang.org/x/oauth2"
|
|
"golang.org/x/oauth2/linkedin"
|
|
"io"
|
|
|
|
"base/internal/pkg/oauth/types"
|
|
)
|
|
|
|
type client struct {
|
|
oauthConfig *oauth2.Config
|
|
}
|
|
|
|
func New(config oauth2.Config) types.Oauth {
|
|
oauthConfig := &oauth2.Config{
|
|
ClientID: config.ClientID,
|
|
ClientSecret: config.ClientSecret,
|
|
Endpoint: linkedin.Endpoint,
|
|
RedirectURL: config.RedirectURL,
|
|
Scopes: config.Scopes,
|
|
}
|
|
return &client{oauthConfig: oauthConfig}
|
|
}
|
|
|
|
func (l client) GetConsentAuthUrl(ctx context.Context, state string) string {
|
|
return l.oauthConfig.AuthCodeURL(state, oauth2.AccessTypeOffline)
|
|
}
|
|
|
|
func (l client) ExchangeCodeWithToken(ctx context.Context, code string) (*types.Token, error) {
|
|
exchange, err := l.oauthConfig.Exchange(ctx, code, oauth2.AccessTypeOffline)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
token, err := l.oauthConfig.TokenSource(ctx, exchange).Token()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &types.Token{
|
|
AccessToken: token.AccessToken,
|
|
TokenType: token.TokenType,
|
|
RefreshToken: token.RefreshToken,
|
|
ExpiresIn: token.ExpiresIn,
|
|
}, nil
|
|
}
|
|
|
|
func (l client) GetUserInfo(
|
|
ctx context.Context,
|
|
accessToken string,
|
|
refreshToken string,
|
|
) (types.UserInfo, error) {
|
|
resp, err := l.oauthConfig.Client(ctx, &oauth2.Token{
|
|
AccessToken: accessToken,
|
|
RefreshToken: refreshToken,
|
|
}).Get("https://api.linkedin.com/v2/me")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
data, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var user UserInfo
|
|
|
|
if err = json.Unmarshal(data, &user); err != nil {
|
|
return nil, err
|
|
}
|
|
return user, nil
|
|
}
|