Skip to content

Commit

Permalink
twitter login
Browse files Browse the repository at this point in the history
  • Loading branch information
lyricat committed Apr 17, 2023
1 parent bbf22bf commit 2aa1f25
Show file tree
Hide file tree
Showing 12 changed files with 307 additions and 91 deletions.
16 changes: 10 additions & 6 deletions cmd/httpd/httpd.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/pandodao/botastic/worker/rotater"
"github.com/pandodao/lemon-checkout-go"
"github.com/pandodao/mixpay-go"
"github.com/pandodao/twitter-login-go"
"github.com/rs/cors"
"golang.org/x/sync/errgroup"

Expand All @@ -62,6 +63,8 @@ func NewCmdHttpd() *cobra.Command {
return err
}

twitterClient := twitter.New(cfg.Twitter.ApiKey, cfg.Twitter.ApiSecret)

h := store.MustInit(store.Config{
Driver: cfg.DB.Driver,
DSN: cfg.DB.DSN,
Expand Down Expand Up @@ -98,7 +101,7 @@ func NewCmdHttpd() *cobra.Command {
userz := userServ.New(userServ.Config{
ExtraRate: cfg.Sys.ExtraRate,
InitUserCredits: cfg.Sys.InitUserCredits,
}, client, users)
}, client, twitterClient, users)
indexService := indexServ.NewService(ctx, gptHandler, indexes, userz, models, tiktokenHandler)
appz := appServ.New(appServ.Config{
SecretKey: cfg.Sys.SecretKey,
Expand Down Expand Up @@ -160,11 +163,12 @@ func NewCmdHttpd() *cobra.Command {

{
svr := handler.New(handler.Config{
ClientID: client.ClientID,
TrustDomains: cfg.Auth.TrustDomains,
Lemon: cfg.Lemon,
Variants: cfg.TopupVariants,
}, s, apps, indexes, users, convs, models, appz, botz, indexService, userz, convz, orderz, hub)
ClientID: client.ClientID,
TrustDomains: cfg.Auth.TrustDomains,
Lemon: cfg.Lemon,
Variants: cfg.TopupVariants,
TwitterCallbackUrl: cfg.Twitter.CallbackUrl,
}, s, twitterClient, apps, indexes, users, convs, models, appz, botz, indexService, userz, convz, orderz, hub)

// api v1
restHandler := svr.HandleRest()
Expand Down
5 changes: 5 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ topup_variants:
amount: 10.00
lemon_id: 123456

twitter:
api_key: ""
api_secret: ""
callback_url: "https://"

order_syncer:
interval: 1s
check_interval: 10s
Expand Down
7 changes: 7 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Config struct {
Mixpay Mixpay `yaml:"mixpay"`
Lemon Lemonsqueezy `yaml:"lemonsqueezy"`
TopupVariants []TopupVariant `yaml:"topup_variants"`
Twitter Twitter `yaml:"twitter"`
OrderSyncer OrderSyncerConfig `yaml:"order_syncer"`
}

Expand Down Expand Up @@ -69,6 +70,12 @@ type Lemonsqueezy struct {
StoreID int64 `yaml:"store_id"`
}

type Twitter struct {
ApiKey string `yaml:"api_key"`
ApiSecret string `yaml:"api_secret"`
CallbackUrl string `yaml:"callback_url"`
}

type TopupVariant struct {
Name string `yaml:"name" json:"name"`
Amount float64 `yaml:"amount" json:"amount"`
Expand Down
35 changes: 21 additions & 14 deletions core/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type (
FullName string `json:"full_name"`
AvatarURL string `json:"avatar_url"`
MvmPublicKey string `json:"mvm_public_key"`
Email string `json:"email"`
TwitterID string `json:"twitter_id"`
TwitterScreenName string `json:"twitter_screen_name"`
Lang string `json:"-"`
Credits decimal.Decimal `json:"credits"`

Expand All @@ -27,43 +30,46 @@ type (
UserStore interface {

// SELECT
// "id", "mixin_user_id", "mixin_identity_number", "full_name", "avatar_url",
// "mvm_public_key",
// "lang", "credits",
// "created_at", "updated_at"
// *
// FROM @@table WHERE
// "id"=@id AND "deleted_at" IS NULL
// LIMIT 1
GetUser(ctx context.Context, id uint64) (*User, error)

// SELECT
// "id", "mixin_user_id", "mixin_identity_number", "full_name", "avatar_url",
// "mvm_public_key",
// "lang", "credits",
// "created_at", "updated_at"
// *
// FROM @@table WHERE
// "mixin_user_id"=@mixinUserID AND "deleted_at" IS NULL
// LIMIT 1
GetUserByMixinID(ctx context.Context, mixinUserID string) (*User, error)

// SELECT
// *
// FROM @@table WHERE
// "twitter_id"=@twitterID AND "deleted_at" IS NULL
// LIMIT 1
GetUserByTwitterID(ctx context.Context, twitterID string) (*User, error)

// INSERT INTO @@table
// (
// "full_name", "avatar_url",
// "mixin_user_id", "mixin_identity_number",
// "lang", "credits",
// "mvm_public_key",
// "email", "twitter_id", "twitter_screen_name",
// "lang", "credits",
// "created_at", "updated_at"
// )
// VALUES
// (
// @fullName, @avatarURL,
// @mixinUserID, @mixinIdentityNumber,
// @lang, @credits,
// @mvmPublicKey,
// @user.FullName, @user.AvatarURL,
// @user.MixinUserID, @user.MixinIdentityNumber,
// @user.MvmPublicKey,
// @user.Email, @user.TwitterID, @user.TwitterScreenName,
// @user.Lang, @user.Credits,
// NOW(), NOW()
// )
// RETURNING "id"
CreateUser(ctx context.Context, fullName, avatarURL, mixinUserID, mixinIdentityNumber, lang, mvmPublicKey string, credits decimal.Decimal) (uint64, error)
CreateUser(ctx context.Context, user *User) (uint64, error)

// UPDATE @@table
// {{set}}
Expand All @@ -88,6 +94,7 @@ type (

UserService interface {
LoginWithMixin(ctx context.Context, authUser *auth.User, lang string) (*User, error)
LoginWithTwitter(ctx context.Context, oauthToken, oauthVerifier, lang string) (*User, error)
Topup(ctx context.Context, user *User, amount decimal.Decimal) error
ConsumeCredits(ctx context.Context, userID uint64, amount decimal.Decimal) error
ConsumeCreditsByModel(ctx context.Context, userID uint64, model Model, promptTokenCount, completionTokenCount int64) error
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ require (
github.com/go-resty/resty/v2 v2.7.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/gomodule/oauth1 v0.2.0 // indirect
github.com/gorilla/schema v1.2.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect
Expand Down Expand Up @@ -115,6 +116,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pandodao/lemon-checkout-go v0.0.0-20230328015639-cf8cd76dd06e
github.com/pandodao/passport-go v1.0.8
github.com/pandodao/twitter-login-go v0.0.1
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/shopspring/decimal v1.3.1
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,8 @@ github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiu
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/gomodule/oauth1 v0.2.0 h1:/nNHAD99yipOEspQFbAnNmwGTZ1UNXiD/+JLxwx79fo=
github.com/gomodule/oauth1 v0.2.0/go.mod h1:4r/a8/3RkhMBxJQWL5qzbOEcaQmNPIkNoI7P8sXeI08=
github.com/gomodule/redigo v1.7.1-0.20190724094224-574c33c3df38/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
Expand Down Expand Up @@ -472,6 +474,8 @@ github.com/pandodao/mixpay-go v0.0.0-20230405103808-9f656bd75b03 h1:TOcnjRJI0OCi
github.com/pandodao/mixpay-go v0.0.0-20230405103808-9f656bd75b03/go.mod h1:PYFFg5bTeuZAnqZu3oXUDPIUCdrOZ+Hv1FrbJzBw5LA=
github.com/pandodao/passport-go v1.0.8 h1:TpX1rmQh2Mian1z1/2ah94e6gYUjOJD1Q0sTrM1jwTM=
github.com/pandodao/passport-go v1.0.8/go.mod h1:wDXFINRWI/mhckKb2jmWFbx9WFm8PyFPH4Zv9jlxd6s=
github.com/pandodao/twitter-login-go v0.0.1 h1:BR3N0DjnmYvp+aSN/mJqpIzSlqH3YPv7lDH0TK/uFo8=
github.com/pandodao/twitter-login-go v0.0.1/go.mod h1:xhxK+MgCCy4yT4OYcsjHE9kKzmjpH5rwWWmlQ6Wl/mQ=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
Expand Down
59 changes: 52 additions & 7 deletions handler/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,18 @@ import (
"github.com/pandodao/botastic/session"
"github.com/pandodao/botastic/util"
"github.com/pandodao/passport-go/auth"
"github.com/pandodao/twitter-login-go"
"gorm.io/gorm"
)

type LoginPayload struct {
Method string `json:"method"`
MixinToken string `json:"mixin_token"`
Signature string `json:"signature"`
SignedMessage string `json:"signed_message"`
Lang string `json:"lang"`
Method string `json:"method"`
MixinToken string `json:"mixin_token"`
Signature string `json:"signature"`
SignedMessage string `json:"signed_message"`
TwitterOAuthToken string `json:"twitter_oauth_token"`
TwitterOAuthVerifier string `json:"twitter_oauth_verifier"`
Lang string `json:"lang"`
}

func Login(s *session.Session, userz core.UserService, clientID string, domains []string) http.HandlerFunc {
Expand Down Expand Up @@ -49,7 +52,12 @@ func Login(s *session.Session, userz core.UserService, clientID string, domains
render.Error(w, http.StatusUnauthorized, err)
return
}
user, token, err := s.LoginWithMixin(ctx, userz, authUser, body.Lang)
user, err := userz.LoginWithMixin(ctx, authUser, body.Lang)
if err != nil {
render.Error(w, http.StatusUnauthorized, err)
return
}
token, err := s.GetAccessToken(ctx, user.ID)
if err != nil {
render.Error(w, http.StatusUnauthorized, err)
return
Expand All @@ -71,7 +79,30 @@ func Login(s *session.Session, userz core.UserService, clientID string, domains
render.Error(w, http.StatusUnauthorized, err)
return
}
user, token, err := s.LoginWithMixin(ctx, userz, authUser, body.Lang)
user, err := userz.LoginWithMixin(ctx, authUser, body.Lang)
if err != nil {
render.Error(w, http.StatusUnauthorized, err)
return
}
token, err := s.GetAccessToken(ctx, user.ID)
if err != nil {
render.Error(w, http.StatusUnauthorized, err)
return
}
render.JSON(w, map[string]interface{}{
"user": user,
"access_token": token,
})
return
}
case "twitter":
{
user, err := userz.LoginWithTwitter(ctx, body.TwitterOAuthToken, body.TwitterOAuthVerifier, body.Lang)
if err != nil {
render.Error(w, http.StatusUnauthorized, err)
return
}
token, err := s.GetAccessToken(ctx, user.ID)
if err != nil {
render.Error(w, http.StatusUnauthorized, err)
return
Expand All @@ -89,6 +120,20 @@ func Login(s *session.Session, userz core.UserService, clientID string, domains
}
}

func GetTwitterURL(twitterClient *twitter.Client, callbackURL string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestUrl, err := twitterClient.GetAuthURL(callbackURL)
if err != nil {
render.Error(w, http.StatusInternalServerError, err)
return
}

render.JSON(w, map[string]interface{}{
"url": requestUrl,
})
}
}

func HandleAuthentication(s *session.Session, users core.UserStore) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
Expand Down
45 changes: 26 additions & 19 deletions handler/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ import (
"github.com/pandodao/botastic/handler/user"
"github.com/pandodao/botastic/internal/chanhub"
"github.com/pandodao/botastic/session"
"github.com/pandodao/twitter-login-go"
)

func New(cfg Config, s *session.Session,
twitterClient *twitter.Client,
apps core.AppStore,
indexs core.IndexStore,
users core.UserStore,
Expand All @@ -35,35 +37,39 @@ func New(cfg Config, s *session.Session,
hub *chanhub.Hub,
) Server {
return Server{
cfg: cfg,
apps: apps,
indexes: indexs,
users: users,
appz: appz,
models: models,
indexz: indexz,
botz: botz,
convz: convz,
userz: userz,
session: s,
convs: convs,
orderz: orderz,
hub: hub,
cfg: cfg,
apps: apps,
indexes: indexs,
users: users,
appz: appz,
models: models,
indexz: indexz,
botz: botz,
convz: convz,
userz: userz,
convs: convs,
orderz: orderz,
hub: hub,
session: s,
twitterClient: twitterClient,
}
}

type (
Config struct {
ClientID string
TrustDomains []string
Lemon config.Lemonsqueezy
Variants []config.TopupVariant
ClientID string
TrustDomains []string
Lemon config.Lemonsqueezy
Variants []config.TopupVariant
TwitterCallbackUrl string
}

Server struct {
cfg Config

session *session.Session
session *session.Session
twitterClient *twitter.Client

apps core.AppStore
indexes core.IndexStore
users core.UserStore
Expand Down Expand Up @@ -111,6 +117,7 @@ func (s Server) HandleRest() http.Handler {

r.Route("/auth", func(r chi.Router) {
r.Post("/login", auth.Login(s.session, s.userz, s.cfg.ClientID, s.cfg.TrustDomains))
r.Get("/twitter/url", auth.GetTwitterURL(s.twitterClient, s.cfg.TwitterCallbackUrl))
})

r.Route("/bots", func(r chi.Router) {
Expand Down

0 comments on commit 2aa1f25

Please sign in to comment.