init: 1.0.0
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Apple 登录</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="appleid-signin"></div>
|
||||
<script type="text/javascript" src="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"></script>
|
||||
<script type="text/javascript">
|
||||
AppleID.auth.init({
|
||||
clientId: 'web.jiashus.com', // 替换为你的服务 ID
|
||||
scope: 'name email', // 可选,授权范围
|
||||
redirectURI: 'https://test.ppanel.dev:8443/auth/apple/callback', // 替换为你的回调 URL
|
||||
state: 'optional-csrf-token', // 可选
|
||||
usePopup: false // 可选,是否使用弹窗方式
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,76 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestAppleLogin(t *testing.T) {
|
||||
t.Skipf("Skip TestAppleLogin test")
|
||||
router := gin.Default()
|
||||
router.LoadHTMLGlob("./*")
|
||||
router.GET("/apple", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "apple.html", gin.H{
|
||||
"title": "Gin HTML Example",
|
||||
"message": "Hello, Gin!",
|
||||
})
|
||||
})
|
||||
router.POST("/auth/apple/callback", func(c *gin.Context) {
|
||||
var req CallbackRequest
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request data"})
|
||||
return
|
||||
}
|
||||
handleAppleCallBack(c, req)
|
||||
})
|
||||
_ = router.RunTLS(":8443", "certificate.crt", "private.key")
|
||||
}
|
||||
|
||||
func handleAppleCallBack(ctx context.Context, request CallbackRequest) {
|
||||
fmt.Printf("request: %+v\n", request)
|
||||
// validate the token
|
||||
client, err := New(Config{
|
||||
TeamID: TeamID,
|
||||
ClientID: ClientID,
|
||||
KeyID: KeyID,
|
||||
ClientSecret: ClientSecret,
|
||||
RedirectURI: "https://test.ppanel.dev:8443/auth/apple/callback",
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println("error creating apple client: " + err.Error())
|
||||
return
|
||||
}
|
||||
resp, err := client.VerifyWebToken(ctx, request.Code)
|
||||
if err != nil {
|
||||
fmt.Println("error verifying token: " + err.Error())
|
||||
return
|
||||
}
|
||||
if resp.Error != "" {
|
||||
fmt.Printf("apple returned an error: %s - %s\n", resp.Error, resp.ErrorDescription)
|
||||
return
|
||||
}
|
||||
|
||||
// Get the unique user ID
|
||||
unique, err := GetUniqueID(resp.IDToken)
|
||||
if err != nil {
|
||||
fmt.Println("error getting unique id: " + err.Error())
|
||||
return
|
||||
}
|
||||
// Get the email
|
||||
claim, err := GetClaims(resp.IDToken)
|
||||
if err != nil {
|
||||
fmt.Println("failed to get claims: " + err.Error())
|
||||
return
|
||||
}
|
||||
email := (*claim)["email"]
|
||||
emailVerified := (*claim)["email_verified"]
|
||||
isPrivateEmail := (*claim)["is_private_email"]
|
||||
|
||||
// Voila!
|
||||
log.Printf("\n unique: %s \n email: %s \n email_verified: %v \n is_private_email: %v", unique, email, emailVerified, isPrivateEmail)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
TeamID string
|
||||
ClientID string
|
||||
KeyID string
|
||||
ClientSecret string
|
||||
RedirectURI string
|
||||
}
|
||||
|
||||
// New creates a Client object with the default URLs and a default http client
|
||||
func New(c Config) (*Client, error) {
|
||||
fmt.Printf("config: %+v\n", c)
|
||||
secret, err := GenerateClientSecret(c.ClientSecret, c.TeamID, c.ClientID, c.KeyID)
|
||||
if err != nil {
|
||||
fmt.Println("error generating secret: " + err.Error())
|
||||
return nil, err
|
||||
}
|
||||
return &Client{
|
||||
config: c,
|
||||
validationURL: ValidationURL,
|
||||
revokeURL: RevokeURL,
|
||||
client: &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
},
|
||||
secret: secret,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package apple
|
||||
|
||||
// WebValidationTokenRequest is based off of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens
|
||||
type WebValidationTokenRequest struct {
|
||||
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
|
||||
ClientID string
|
||||
|
||||
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
|
||||
// It can also be generated using the GenerateClientSecret function provided in this package
|
||||
ClientSecret string
|
||||
|
||||
// Code is the authorization code received from your application’s user agent.
|
||||
// The code is single use only and valid for five minutes.
|
||||
Code string
|
||||
|
||||
// RedirectURI is the destination URI the code was originally sent to.
|
||||
// Redirect URLs must be registered with Apple. You can register up to 10. Apple will throw an error with IP address
|
||||
// URLs on the authorization screen, and will not let you add localhost in the developer portal.
|
||||
RedirectURI string
|
||||
}
|
||||
|
||||
// CallbackRequest Apple Callback Request
|
||||
type CallbackRequest struct {
|
||||
// Code is the authorization code received from your application’s user agent.
|
||||
// The code is single use only and valid for five minutes.
|
||||
Code string `form:"code"`
|
||||
IdToken string `form:"id_token"`
|
||||
State string `form:"state"`
|
||||
}
|
||||
|
||||
// AppValidationTokenRequest is based off of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens
|
||||
type AppValidationTokenRequest struct {
|
||||
// ClientID is the package name of your app
|
||||
ClientID string
|
||||
|
||||
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
|
||||
// It can also be generated using the GenerateClientSecret function provided in this package
|
||||
ClientSecret string
|
||||
|
||||
// The authorization code received in an authorization response sent to your app. The code is single-use only and valid for five minutes.
|
||||
// Authorization code validation requests require this parameter.
|
||||
Code string
|
||||
}
|
||||
|
||||
// ValidationRefreshRequest is based off of https://developer.apple.com/documentation/signinwithapplerestapi/generate_and_validate_tokens
|
||||
type ValidationRefreshRequest struct {
|
||||
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
|
||||
ClientID string
|
||||
|
||||
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
|
||||
// It can also be generated using the GenerateClientSecret function provided in this package
|
||||
ClientSecret string
|
||||
|
||||
// RefreshToken is the refresh token given during a previous validation
|
||||
RefreshToken string
|
||||
}
|
||||
|
||||
// RevokeAccessTokenRequest is based off https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens
|
||||
type RevokeAccessTokenRequest struct {
|
||||
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
|
||||
ClientID string
|
||||
|
||||
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
|
||||
// It can also be generated using the GenerateClientSecret function provided in this package
|
||||
ClientSecret string
|
||||
|
||||
// AccessToken is the auth token given during a previous validation
|
||||
AccessToken string
|
||||
}
|
||||
|
||||
// RevokeRefreshTokenRequest is based off https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens
|
||||
type RevokeRefreshTokenRequest struct {
|
||||
// ClientID is the "Services ID" value that you get when navigating to your "sign in with Apple"-enabled service ID
|
||||
ClientID string
|
||||
|
||||
// ClientSecret is secret generated as a JSON Web Token that uses the secret key generated by the WWDR portal.
|
||||
// It can also be generated using the GenerateClientSecret function provided in this package
|
||||
ClientSecret string
|
||||
|
||||
// RefreshToken is the refresh token given during a previous validation
|
||||
RefreshToken string
|
||||
}
|
||||
|
||||
// ValidationResponse is based off of https://developer.apple.com/documentation/signinwithapplerestapi/tokenresponse
|
||||
type ValidationResponse struct {
|
||||
// (Reserved for future use) A token used to access allowed data. Currently, no data set has been defined for access.
|
||||
AccessToken string `json:"access_token"`
|
||||
|
||||
// The type of access token. It will always be "bearer".
|
||||
TokenType string `json:"token_type"`
|
||||
|
||||
// The amount of time, in seconds, before the access token expires. You can revalidate with the "RefreshToken"
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
|
||||
// The refresh token used to regenerate new access tokens. Store this token securely on your server.
|
||||
// The refresh token isn’t returned when validating an existing refresh token. Please refer to RefreshReponse below
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
|
||||
// A JSON Web Token that contains the user’s identity information.
|
||||
IDToken string `json:"id_token"`
|
||||
|
||||
// Used to capture any error returned by the endpoint. Do not trust the response if this error is not nil
|
||||
Error string `json:"error"`
|
||||
|
||||
// A more detailed precision about the current error.
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
// RefreshResponse is a subset of ValidationResponse returned by Apple
|
||||
type RefreshResponse struct {
|
||||
// (Reserved for future use) A token used to access allowed data. Currently, no data set has been defined for access.
|
||||
AccessToken string `json:"access_token"`
|
||||
|
||||
// The type of access token. It will always be "bearer".
|
||||
TokenType string `json:"token_type"`
|
||||
|
||||
// The amount of time, in seconds, before the access token expires. You can revalidate with this token
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
|
||||
// Used to capture any error returned by the endpoint. Do not trust the response if this error is not nil
|
||||
Error string `json:"error"`
|
||||
|
||||
// A more detailed precision about the current error.
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
// RevokeResponse is based of https://developer.apple.com/documentation/sign_in_with_apple/revoke_tokens
|
||||
type RevokeResponse struct {
|
||||
// Used to capture any error returned by the endpoint
|
||||
Error string `json:"error"`
|
||||
|
||||
// A more detailed precision about the current error.
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
/*
|
||||
GenerateClientSecret generates the client secret used to make requests to the validation server.
|
||||
The secret expires after 6 months
|
||||
|
||||
signingKey - Private key from Apple obtained by going to the keys section of the developer section
|
||||
teamID - Your 10-character Team ID
|
||||
clientID - Your Services ID, e.g. com.aaronparecki.services
|
||||
keyID - Find the 10-char Key ID value from the portal
|
||||
*/
|
||||
func GenerateClientSecret(signingKey, teamID, clientID, keyID string) (string, error) {
|
||||
block, _ := pem.Decode([]byte(signingKey))
|
||||
if block == nil {
|
||||
return "", errors.New("empty block after decoding")
|
||||
}
|
||||
|
||||
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Create the Claims
|
||||
now := time.Now()
|
||||
claims := &jwt.RegisteredClaims{
|
||||
Issuer: teamID,
|
||||
IssuedAt: &jwt.NumericDate{
|
||||
Time: now,
|
||||
},
|
||||
ExpiresAt: &jwt.NumericDate{
|
||||
Time: now.Add(time.Hour*24*180 - time.Second), // 180 days
|
||||
},
|
||||
Audience: jwt.ClaimStrings{
|
||||
"https://appleid.apple.com",
|
||||
},
|
||||
Subject: clientID,
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
|
||||
token.Header["alg"] = "ES256"
|
||||
token.Header["kid"] = keyID
|
||||
|
||||
return token.SignedString(privateKey)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
// ValidationURL is the endpoint for verifying tokens
|
||||
ValidationURL string = "https://appleid.apple.com/auth/token"
|
||||
// RevokeURL is the endpoint for revoking tokens
|
||||
RevokeURL string = "https://appleid.apple.com/auth/revoke"
|
||||
// ContentType is the one expected by Apple
|
||||
ContentType string = "application/x-www-form-urlencoded"
|
||||
// UserAgent is required by Apple or the request will fail
|
||||
UserAgent string = "go-signin-with-apple"
|
||||
// AcceptHeader is the content that we are willing to accept
|
||||
AcceptHeader string = "application/json"
|
||||
)
|
||||
|
||||
// ValidationClient is an interface to call the validation API
|
||||
type ValidationClient interface {
|
||||
VerifyWebToken(ctx context.Context, reqBody WebValidationTokenRequest, result interface{}) error
|
||||
VerifyAppToken(ctx context.Context, reqBody AppValidationTokenRequest, result interface{}) error
|
||||
VerifyRefreshToken(ctx context.Context, reqBody ValidationRefreshRequest, result interface{}) error
|
||||
RevokeAccessToken(ctx context.Context, reqBody RevokeAccessTokenRequest, result interface{}) error
|
||||
RevokeRefreshToken(ctx context.Context, reqBody RevokeRefreshTokenRequest, result interface{}) error
|
||||
}
|
||||
|
||||
// Client implements ValidationClient
|
||||
type Client struct {
|
||||
config Config
|
||||
validationURL string
|
||||
revokeURL string
|
||||
secret string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// ClientOptions is a struct to hold the options for the client
|
||||
type ClientOptions struct {
|
||||
validationURL string
|
||||
revokeURL string
|
||||
//nolint:unused
|
||||
secret string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewWithURL creates a Client object with a custom URL provided
|
||||
//
|
||||
// Deprecated: This function is deprecated and will be removed in a future version. Use NewWithOptions instead.
|
||||
func NewWithURL(validationURL string, revokeURL string) *Client {
|
||||
return NewWithOptions(ClientOptions{
|
||||
validationURL: validationURL,
|
||||
revokeURL: revokeURL,
|
||||
})
|
||||
}
|
||||
|
||||
// NewWithOptions creates a Client object with custom options. It will default to the standard options if not provided
|
||||
func NewWithOptions(options ClientOptions) *Client {
|
||||
if options.client == nil {
|
||||
options.client = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
if options.validationURL == "" {
|
||||
options.validationURL = ValidationURL
|
||||
}
|
||||
if options.revokeURL == "" {
|
||||
options.revokeURL = RevokeURL
|
||||
}
|
||||
client := &Client{
|
||||
validationURL: options.validationURL,
|
||||
revokeURL: options.revokeURL,
|
||||
client: options.client,
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// VerifyWebToken sends the WebValidationTokenRequest and gets validation result
|
||||
func (c *Client) VerifyWebToken(ctx context.Context, code string) (ValidationResponse, error) {
|
||||
data := url.Values{
|
||||
"client_id": {c.config.ClientID},
|
||||
"client_secret": {c.secret},
|
||||
"code": {code},
|
||||
"redirect_uri": {c.config.RedirectURI},
|
||||
"grant_type": {"authorization_code"},
|
||||
}
|
||||
var resp ValidationResponse
|
||||
err := doRequest(ctx, c.client, &resp, c.validationURL, data)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// VerifyAppToken sends the AppValidationTokenRequest and gets validation result
|
||||
func (c *Client) VerifyAppToken(ctx context.Context, reqBody AppValidationTokenRequest, result interface{}) error {
|
||||
data := url.Values{
|
||||
"client_id": {reqBody.ClientID},
|
||||
"client_secret": {reqBody.ClientSecret},
|
||||
"code": {reqBody.Code},
|
||||
"grant_type": {"authorization_code"},
|
||||
}
|
||||
|
||||
return doRequest(ctx, c.client, &result, c.validationURL, data)
|
||||
}
|
||||
|
||||
// VerifyRefreshToken sends the WebValidationTokenRequest and gets validation result
|
||||
func (c *Client) VerifyRefreshToken(ctx context.Context, reqBody ValidationRefreshRequest, result interface{}) error {
|
||||
data := url.Values{
|
||||
"client_id": {reqBody.ClientID},
|
||||
"client_secret": {reqBody.ClientSecret},
|
||||
"refresh_token": {reqBody.RefreshToken},
|
||||
"grant_type": {"refresh_token"},
|
||||
}
|
||||
|
||||
return doRequest(ctx, c.client, &result, c.validationURL, data)
|
||||
}
|
||||
|
||||
// RevokeRefreshToken revokes the Refresh Token and gets the revoke result
|
||||
func (c *Client) RevokeRefreshToken(ctx context.Context, token string, result interface{}) error {
|
||||
data := url.Values{
|
||||
"client_id": {c.config.ClientID},
|
||||
"client_secret": {c.secret},
|
||||
"token": {token},
|
||||
"token_type_hint": {"refresh_token"},
|
||||
}
|
||||
|
||||
return doRequest(ctx, c.client, result, c.revokeURL, data)
|
||||
}
|
||||
|
||||
// RevokeAccessToken revokes the Access Token and gets the revoke result
|
||||
func (c *Client) RevokeAccessToken(ctx context.Context, token string, result interface{}) error {
|
||||
data := url.Values{
|
||||
"client_id": {c.config.ClientID},
|
||||
"client_secret": {c.secret},
|
||||
"token": {token},
|
||||
"token_type_hint": {"access_token"},
|
||||
}
|
||||
log.Printf("revoke access token: %v", data)
|
||||
return doRequest(ctx, c.client, &result, c.revokeURL, data)
|
||||
}
|
||||
|
||||
// GetUniqueID decodes the id_token response and returns the unique subject ID to identify the user
|
||||
func GetUniqueID(idToken string) (string, error) {
|
||||
token, _, err := new(jwt.Parser).ParseUnverified(idToken, jwt.MapClaims{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%v", claims["sub"]), nil
|
||||
}
|
||||
|
||||
// GetClaims decodes the id_token response and returns the JWT claims to identify the user
|
||||
func GetClaims(idToken string) (*jwt.MapClaims, error) {
|
||||
token, _, err := new(jwt.Parser).ParseUnverified(idToken, jwt.MapClaims{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid token claims")
|
||||
}
|
||||
|
||||
return &claims, nil
|
||||
}
|
||||
|
||||
func doRequest(ctx context.Context, client *http.Client, result interface{}, url string, data url.Values) error {
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", url, strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Add("content-type", ContentType)
|
||||
req.Header.Add("accept", AcceptHeader)
|
||||
req.Header.Add("user-agent", UserAgent) // apple requires a user agent
|
||||
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
log.Printf("error response from apple: %s", res.Status)
|
||||
}
|
||||
|
||||
return json.NewDecoder(res.Body).Decode(result)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package google
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/google"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
RedirectURL string
|
||||
}
|
||||
type Client struct {
|
||||
*oauth2.Config
|
||||
}
|
||||
type UserInfo struct {
|
||||
OpenID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Picture string `json:"picture"`
|
||||
VerifiedEmail bool `json:"verified_email"`
|
||||
}
|
||||
|
||||
func New(config *Config) *Client {
|
||||
return &Client{
|
||||
&oauth2.Config{
|
||||
ClientID: config.ClientID,
|
||||
ClientSecret: config.ClientSecret,
|
||||
RedirectURL: config.RedirectURL,
|
||||
Scopes: []string{"openid", "profile", "email", "https://www.googleapis.com/auth/user.phonenumbers.read"},
|
||||
Endpoint: google.Endpoint,
|
||||
},
|
||||
}
|
||||
}
|
||||
func (c *Client) GetUserInfo(token string) (*UserInfo, error) {
|
||||
client := c.Config.Client(context.Background(), &oauth2.Token{AccessToken: token})
|
||||
resp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
|
||||
if err != nil {
|
||||
logger.Error("[Google OAuth 2.0] Get User Info", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var userInfo map[string]interface{}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
|
||||
logger.Error("[Google OAuth 2.0] Decode User Info", logger.Field("error", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &UserInfo{
|
||||
OpenID: userInfo["id"].(string),
|
||||
Email: userInfo["email"].(string),
|
||||
Name: userInfo["name"].(string),
|
||||
Picture: userInfo["picture"].(string),
|
||||
VerifiedEmail: userInfo["verified_email"].(bool),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package google
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
func TestGoogleOAuth(t *testing.T) {
|
||||
t.Skipf("Skip TestGoogleOAuth test")
|
||||
http.HandleFunc("/", handleMain)
|
||||
http.HandleFunc("/login", handleLogin)
|
||||
http.HandleFunc("/auth", handleCallback)
|
||||
http.HandleFunc("/user", handleAuth)
|
||||
|
||||
fmt.Println("Server is running on http://localhost:3001")
|
||||
log.Fatal(http.ListenAndServe(":3001", nil))
|
||||
}
|
||||
|
||||
func handleMain(w http.ResponseWriter, r *http.Request) {
|
||||
html := `<html>
|
||||
<body>
|
||||
<a href="/login">Log in with Google</a>
|
||||
</body>
|
||||
</html>`
|
||||
fmt.Fprint(w, html)
|
||||
}
|
||||
|
||||
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
oauthConfig := New(&Config{
|
||||
ClientID: "",
|
||||
ClientSecret: "",
|
||||
RedirectURL: "http://localhost:3001/auth",
|
||||
})
|
||||
url := oauthConfig.AuthCodeURL("randomstate", oauth2.AccessTypeOffline)
|
||||
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
func handleCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if r.FormValue("state") != "randomstate" {
|
||||
http.Error(w, "State is invalid", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("url: %v", r.URL)
|
||||
|
||||
oauthConfig := New(&Config{
|
||||
ClientID: "",
|
||||
ClientSecret: "Key",
|
||||
RedirectURL: "http://localhost:3001/auth",
|
||||
})
|
||||
code := r.FormValue("code")
|
||||
token, err := oauthConfig.Exchange(context.Background(), code)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/user?token="+token.AccessToken, http.StatusTemporaryRedirect)
|
||||
}
|
||||
|
||||
func handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
token := r.FormValue("token")
|
||||
client := New(&Config{
|
||||
ClientID: "Id",
|
||||
ClientSecret: "Key",
|
||||
RedirectURL: "http://localhost:3001/auth",
|
||||
})
|
||||
userInfo, err := client.GetUserInfo(token)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to get user info", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "Hello, %s", userInfo.Name)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ParseAuthDataJson parses provided json content for AuthData
|
||||
func ParseAuthDataJson(content []byte) (*AuthData, error) {
|
||||
data := &AuthData{}
|
||||
err := json.Unmarshal(content, data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unmarshaling error: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// ParseAuthDataBase64 decodes provided content from base64 and parses result for AuthData
|
||||
func ParseAuthDataBase64(content []byte) (*AuthData, error) {
|
||||
|
||||
decodedBytes, err := base64.RawStdEncoding.DecodeString(string(content))
|
||||
if err != nil && len(decodedBytes) == 0 {
|
||||
return nil, fmt.Errorf("base64 decoding error: %w", err)
|
||||
}
|
||||
return ParseAuthDataJson(decodedBytes)
|
||||
}
|
||||
|
||||
// ParseAndValidateBase64 parses base64 content for AuthData and validates it
|
||||
func ParseAndValidateBase64(content []byte, botToken string) (*AuthData, error) {
|
||||
authData, err := ParseAuthDataBase64(content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = authData.Validate([]byte(botToken))
|
||||
return authData, err
|
||||
}
|
||||
|
||||
// ParseAndValidateJson parses json content for AuthData and validates it
|
||||
func ParseAndValidateJson(content []byte, botToken []byte) (*AuthData, error) {
|
||||
authData, err := ParseAuthDataJson(content)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = authData.Validate(botToken)
|
||||
return authData, err
|
||||
}
|
||||
|
||||
// GenerateTelegramOAuthURL generates a URL for Telegram OAuth
|
||||
func GenerateTelegramOAuthURL(botToken, embed, redirect string) string {
|
||||
bot := strings.Split(botToken, ":")
|
||||
uri := "https://oauth.telegram.org/auth?bot_id=%s&origin=%s&embed=%s&request_access=write&return_to=%s"
|
||||
parsedURL, err := url.Parse(redirect)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf(uri, bot[0], fmt.Sprintf("%s://%s", parsedURL.Scheme, parsedURL.Host), embed, redirect)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// getAuthDataCheckString returns a string ready to calculate validation hash.
|
||||
// Ref: https://core.telegram.org/widgets/login#checking-authorization
|
||||
func getAuthDataCheckString(data *AuthData) string {
|
||||
t := reflect.TypeOf(data).Elem()
|
||||
v := reflect.ValueOf(data).Elem()
|
||||
fields := make([]string, 0)
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
tag, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
if v.Field(i).IsNil() || tag == "hash" {
|
||||
continue
|
||||
}
|
||||
val := v.Field(i).Elem().Interface()
|
||||
if val == nil || val == "null" {
|
||||
continue
|
||||
}
|
||||
fields = append(fields, fmt.Sprintf("%s=%v", tag, val))
|
||||
}
|
||||
sort.Strings(fields)
|
||||
return strings.Join(fields, "\n")
|
||||
}
|
||||
|
||||
// computeHash returns a hash calculated for AuthData
|
||||
// Ref: https://core.telegram.org/widgets/login#checking-authorization
|
||||
func computeHash(data *AuthData, botToken []byte) string {
|
||||
checkString := getAuthDataCheckString(data)
|
||||
key := sha256.Sum256(botToken)
|
||||
h := hmac.New(sha256.New, key[:])
|
||||
h.Write([]byte(checkString))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package telegram
|
||||
|
||||
import "fmt"
|
||||
|
||||
type AuthData struct {
|
||||
Id *int64 `json:"id,omitempty"`
|
||||
FirstName *string `json:"first_name,omitempty"`
|
||||
LastName *string `json:"last_name,omitempty"`
|
||||
Username *string `json:"username,omitempty"`
|
||||
PhotoUrl *string `json:"photo_url,omitempty"`
|
||||
AuthDate *int64 `json:"auth_date,omitempty"`
|
||||
Hash *string `json:"hash,omitempty"`
|
||||
}
|
||||
|
||||
// Validate checks the hash of AuthData with computed one. To compute hash botToken is required.
|
||||
// Ref: https://core.telegram.org/widgets/login#checking-authorization
|
||||
func (d *AuthData) Validate(botToken []byte) error {
|
||||
if d.Hash == nil {
|
||||
return fmt.Errorf("auth data has no 'hash' value")
|
||||
}
|
||||
if len(botToken) == 0 {
|
||||
return fmt.Errorf("telegram bot token is not provided")
|
||||
}
|
||||
hash := *d.Hash
|
||||
computedHash := computeHash(d, botToken)
|
||||
if hash != computedHash {
|
||||
return fmt.Errorf("hash is not valid")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Telegram OAuth Test</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Telegram OAuth Test</h1>
|
||||
<script async src="https://telegram.org/js/telegram-widget.js?22" data-telegram-login="ppanel_dev_bot"
|
||||
data-size="large" data-auth-url="/auth/telegram/callback" data-request-access="write"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestOAuth(t *testing.T) {
|
||||
t.Skipf("Skip TestOAuth test")
|
||||
router := gin.Default()
|
||||
router.LoadHTMLGlob("./*")
|
||||
router.GET("/telegram", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "telegram.html", gin.H{
|
||||
"title": "Gin HTML Example",
|
||||
"message": "Hello, Gin!",
|
||||
})
|
||||
})
|
||||
router.GET("/auth/telegram/callback", func(c *gin.Context) {
|
||||
|
||||
})
|
||||
_ = router.RunTLS(":443", "server.crt", "server.key")
|
||||
}
|
||||
|
||||
func TestBase64(t *testing.T) {
|
||||
text := "eyJpZCI6ODI0NjI2ODAzLCJmaXJzdF9uYW1lIjoiQ2hhbmcgbHVlIiwibGFzdF9uYW1lIjoiVHNlbiIsInVzZXJuYW1lIjoidGVuc2lvbl9jIiwicGhvdG9fdXJsIjoiaHR0cHM6XC9cL3QubWVcL2lcL3VzZXJwaWNcLzMyMFwvYU1LNkhEc0pqc2V1YldRYmt2NGlYOHZCRUF6N0hWU3g3dkFuRDBLZ0tFVS5qcGciLCJhdXRoX2RhdGUiOjE3Mzc4MTkwNzQsImhhc2giOiI5M2I1ZDg3Zjc3NjE2YjBjMTM0OTAxYmYwMDg3MTc4YjJiYmZlYzA1MTlkMWVmMDJhZjFjMGNlOTAzM2ZiNGFlIn0"
|
||||
var token = "7651491571:AAEVQma6niHhtqEYDowAEpPo6Fq69BWvRU8"
|
||||
|
||||
data, err := ParseAndValidateBase64([]byte(text), token)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
t.Log(*data.Id)
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user