Skip to content
This repository has been archived by the owner on Mar 20, 2024. It is now read-only.

Commit

Permalink
fix login issue
Browse files Browse the repository at this point in the history
  • Loading branch information
linweiyuan committed Oct 2, 2023
1 parent 7c2f761 commit 2909895
Show file tree
Hide file tree
Showing 10 changed files with 103 additions and 119 deletions.
10 changes: 6 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# API server port
PORT=8080
# Network proxy server address
PROXY=socks5://ip:port
# Imitate access_token
TZ=Asia/Shanghai
PROXY=
OPENAI_EMAIL=
OPENAI_PASSWORD=
CONTINUE_SIGNAL=
ENABLE_HISTORY=
IMITATE_ACCESS_TOKEN=
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.env
go-chatgpt-api
__debug*
__debug*
chat.openai.com.har
62 changes: 2 additions & 60 deletions api/chatgpt/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"

http "github.com/bogdanfinn/fhttp"
"github.com/gin-gonic/gin"
Expand All @@ -17,14 +15,6 @@ import (
"github.com/linweiyuan/go-logger/logger"
)

var (
PUID string
)

func init() {
setupPUID()
}

func CreateConversation(c *gin.Context) {
var request CreateConversationRequest
if err := c.BindJSON(&request); err != nil {
Expand Down Expand Up @@ -66,8 +56,8 @@ func sendConversationRequest(c *gin.Context, request CreateConversationRequest)
req.Header.Set("User-Agent", api.UserAgent)
req.Header.Set(api.AuthorizationHeader, api.GetAccessToken(c))
req.Header.Set("Accept", "text/event-stream")
if PUID != "" {
req.Header.Set("Cookie", "_puid="+PUID)
if api.PUID != "" {
req.Header.Set("Cookie", "_puid="+api.PUID)
}
resp, err := api.Client.Do(req)
if err != nil {
Expand Down Expand Up @@ -189,51 +179,3 @@ func handleConversationResponse(c *gin.Context, resp *http.Response, request Cre
handleConversationResponse(c, resp, continueConversationRequest)
}
}

func setupPUID() {
username := os.Getenv("OPENAI_EMAIL")
password := os.Getenv("OPENAI_PASSWORD")
if username != "" && password != "" {
go func() {
for {
statusCode, errorMessage, accessTokenResponse := GetAccessToken(api.LoginInfo{
Username: username,
Password: password,
})
if statusCode != http.StatusOK {
logger.Error(errorMessage)
return
}

responseMap := make(map[string]string)
json.Unmarshal([]byte(accessTokenResponse), &responseMap)

accessToken, ok := responseMap["accessToken"]
if !ok {
logger.Error(refreshPuidErrorMessage)
return
}

req, _ := http.NewRequest(http.MethodGet, api.ChatGPTApiUrlPrefix+"/backend-api/models?history_and_training_disabled=false", nil)
req.Header.Set("User-Agent", api.UserAgent)
req.Header.Set(api.AuthorizationHeader, accessToken)
resp, err := api.NewHttpClient().Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
logger.Error(refreshPuidErrorMessage)
return
}

resp.Body.Close()
cookies := resp.Cookies()
for _, cookie := range cookies {
if cookie.Name == "_puid" {
PUID = cookie.Value
break
}
}

time.Sleep(time.Hour * 24 * 7)
}
}()
}
}
2 changes: 0 additions & 2 deletions api/chatgpt/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,4 @@ const (
responseTypeMaxTokens = "max_tokens"
responseStatusFinishedSuccessfully = "finished_successfully"
noModelPermissionErrorMessage = "you have no permission to use this model"

refreshPuidErrorMessage = "failed to refresh PUID"
)
7 changes: 1 addition & 6 deletions api/chatgpt/health_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package chatgpt

import (
"fmt"
"log"
"os"
"time"

Expand All @@ -24,11 +23,7 @@ func init() {
proxyUrl := os.Getenv("PROXY")
if proxyUrl != "" {
logger.Info("PROXY: " + proxyUrl)
err1 := api.Client.SetProxy(proxyUrl)
fmt.Println(err1)
if err := api.Client.SetProxy(proxyUrl); err != nil {
log.Fatal(err)
}
api.Client.SetProxy(proxyUrl)

for {
resp, err := healthCheck()
Expand Down
82 changes: 56 additions & 26 deletions api/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"time"

http "github.com/bogdanfinn/fhttp"
tls_client "github.com/bogdanfinn/tls-client"
"github.com/bogdanfinn/tls-client/profiles"
"github.com/gin-gonic/gin"
"github.com/xqdoo00o/OpenAIAuth/auth"
"github.com/xqdoo00o/funcaptcha"

"github.com/linweiyuan/go-logger/logger"
)
Expand All @@ -39,19 +41,21 @@ const (
EmailInvalidErrorMessage = "email is not valid"
EmailOrPasswordInvalidErrorMessage = "email or password is not correct"
GetAccessTokenErrorMessage = "failed to get access token"
GetArkoseTokenErrorMessage = `you must set ARKOSE_TOKEN_URL first to use GPT-4 (https://linweiyuan.github.io/2023/06/24/%E5%A6%82%E4%BD%95%E7%94%9F%E6%88%90-GPT-4-arkose-token.html)`
defaultTimeoutSeconds = 600 // 10 minutes

EmailKey = "email"
AccountDeactivatedErrorMessage = "account %s is deactivated"

ReadyHint = "service go-chatgpt-api is ready"

refreshPuidErrorMessage = "failed to refresh PUID"
)

var (
Client tls_client.HttpClient
arkoseTokenUrl string
ArkoseClient tls_client.HttpClient
Client tls_client.HttpClient
ArkoseClient tls_client.HttpClient
PUID string
proxyUrl string
)

type LoginInfo struct {
Expand All @@ -69,19 +73,20 @@ type AuthLogin interface {
}

func init() {
Client, _ = tls_client.NewHttpClient(tls_client.NewLogger(), []tls_client.HttpClientOption{
Client, _ = tls_client.NewHttpClient(tls_client.NewNoopLogger(), []tls_client.HttpClientOption{
tls_client.WithCookieJar(tls_client.NewCookieJar()),
tls_client.WithTimeoutSeconds(defaultTimeoutSeconds),
tls_client.WithClientProfile(profiles.Chrome_117),
tls_client.WithClientProfile(profiles.Okhttp4Android13),
}...)
arkoseTokenUrl = os.Getenv("ARKOSE_TOKEN_URL")
ArkoseClient = getHttpClient()

setupPUID()
}

func NewHttpClient() tls_client.HttpClient {
client := getHttpClient()

proxyUrl := os.Getenv("PROXY")
proxyUrl = os.Getenv("PROXY")
if proxyUrl != "" {
client.SetProxy(proxyUrl)
}
Expand All @@ -92,7 +97,7 @@ func NewHttpClient() tls_client.HttpClient {
func getHttpClient() tls_client.HttpClient {
client, _ := tls_client.NewHttpClient(tls_client.NewNoopLogger(), []tls_client.HttpClientOption{
tls_client.WithCookieJar(tls_client.NewCookieJar()),
tls_client.WithClientProfile(profiles.Chrome_117),
tls_client.WithClientProfile(profiles.Okhttp4Android13),
}...)
return client
}
Expand Down Expand Up @@ -164,22 +169,47 @@ func GetAccessToken(c *gin.Context) string {
}

func GetArkoseToken() (string, error) {
var arkoseToken string
var err error
if arkoseTokenUrl == "" {
return "", errors.New(GetArkoseTokenErrorMessage)
}
return funcaptcha.GetOpenAIToken(PUID, proxyUrl)
}

req, _ := http.NewRequest(http.MethodGet, arkoseTokenUrl, nil)
resp, err := ArkoseClient.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
return "", err
}
responseMap := make(map[string]interface{})
err = json.NewDecoder(resp.Body).Decode(&responseMap)
if err != nil {
return "", err
func setupPUID() {
username := os.Getenv("OPENAI_EMAIL")
password := os.Getenv("OPENAI_PASSWORD")
if username != "" && password != "" {
go func() {
for {
authenticator := auth.NewAuthenticator(username, password, proxyUrl)
if err := authenticator.Begin(); err != nil {
logger.Warn(fmt.Sprintf("%s: %s", refreshPuidErrorMessage, err.Details))
return
}

accessToken := authenticator.GetAccessToken()
if accessToken == "" {
logger.Error(refreshPuidErrorMessage)
return
}

req, _ := http.NewRequest(http.MethodGet, ChatGPTApiUrlPrefix+"/backend-api/models?history_and_training_disabled=false", nil)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set(AuthorizationHeader, accessToken)
resp, err := NewHttpClient().Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
logger.Error(refreshPuidErrorMessage)
return
}

resp.Body.Close()
cookies := resp.Cookies()
for _, cookie := range cookies {
if cookie.Name == "_puid" {
PUID = cookie.Value
break
}
}

time.Sleep(time.Hour * 24 * 7)
}
}()
}
arkoseToken = responseMap["token"].(string)
return arkoseToken, err
}
4 changes: 2 additions & 2 deletions api/imitate/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ func sendConversationRequest(c *gin.Context, request chatgpt.CreateConversationR
req.Header.Set("User-Agent", api.UserAgent)
req.Header.Set(api.AuthorizationHeader, accessToken)
req.Header.Set("Accept", "text/event-stream")
if chatgpt.PUID != "" {
req.Header.Set("Cookie", "_puid="+chatgpt.PUID)
if api.PUID != "" {
req.Header.Set("Cookie", "_puid="+api.PUID)
}
resp, err := api.Client.Do(req)
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ services:
ports:
- 8080:8080
environment:
- PORT=
- TZ=Asia/Shanghai
- PROXY=
- ARKOSE_TOKEN_URL=
- OPENAI_EMAIL=
- OPENAI_PASSWORD=
- CONTINUE_SIGNAL=
- ENABLE_HISTORY=
- IMITATE_ACCESS_TOKEN=
restart: unless-stopped
14 changes: 8 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ require (
github.com/google/uuid v1.3.1
github.com/joho/godotenv v1.5.1
github.com/linweiyuan/go-logger v0.0.0-20230709142852-da1f090a7d4c
github.com/xqdoo00o/OpenAIAuth v0.0.0-20230928031215-356afd0d7a6b
github.com/xqdoo00o/funcaptcha v0.0.0-20230928030317-87dbaf7079cf
)

require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/bogdanfinn/utls v1.5.16 // indirect
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
Expand All @@ -25,7 +27,7 @@ require (
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.16.7 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
Expand All @@ -37,10 +39,10 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.12.0 // indirect
golang.org/x/net v0.14.0 // indirect
golang.org/x/sys v0.11.0 // indirect
golang.org/x/text v0.12.0 // indirect
golang.org/x/crypto v0.13.0 // indirect
golang.org/x/net v0.15.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Loading

0 comments on commit 2909895

Please sign in to comment.