summaryrefslogtreecommitdiff
path: root/internal
diff options
context:
space:
mode:
Diffstat (limited to 'internal')
-rw-r--r--internal/api/server.go27
-rw-r--r--internal/config/config.go53
-rw-r--r--internal/config/template.go25
-rw-r--r--internal/gtsmodel/account.go158
-rw-r--r--internal/gtsmodel/application.go30
-rw-r--r--internal/gtsmodel/status.go8
-rw-r--r--internal/gtsmodel/user.go113
-rw-r--r--internal/oauth/html.go9
-rw-r--r--internal/oauth/oauth.go367
-rw-r--r--internal/oauth/oauth_test.go130
-rw-r--r--internal/oauth/pgclientstore.go13
-rw-r--r--internal/oauth/pgclientstore_test.go1
-rw-r--r--internal/oauth/pgtokenstore.go33
13 files changed, 843 insertions, 124 deletions
diff --git a/internal/api/server.go b/internal/api/server.go
index 8af9e75fa..8e22742bb 100644
--- a/internal/api/server.go
+++ b/internal/api/server.go
@@ -19,16 +19,19 @@
package api
import (
- "net/http"
+ "fmt"
+ "os"
+ "path/filepath"
+ "github.com/gin-contrib/sessions"
+ "github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
"github.com/gotosocial/gotosocial/internal/config"
"github.com/sirupsen/logrus"
)
type Server interface {
- AttachHTTPHandler(method string, path string, handler http.HandlerFunc)
- AttachGinHandler(method string, path string, handler gin.HandlerFunc)
+ AttachHandler(method string, path string, handler gin.HandlerFunc)
// AttachMiddleware(handler gin.HandlerFunc)
GetAPIGroup() *gin.RouterGroup
Start()
@@ -60,16 +63,22 @@ func (s *server) Stop() {
// todo: shut down gracefully
}
-func (s *server) AttachHTTPHandler(method string, path string, handler http.HandlerFunc) {
- s.engine.Handle(method, path, gin.WrapH(handler))
-}
-
-func (s *server) AttachGinHandler(method string, path string, handler gin.HandlerFunc) {
- s.engine.Handle(method, path, handler)
+func (s *server) AttachHandler(method string, path string, handler gin.HandlerFunc) {
+ if method == "ANY" {
+ s.engine.Any(path, handler)
+ } else {
+ s.engine.Handle(method, path, handler)
+ }
}
func New(config *config.Config, logger *logrus.Logger) Server {
engine := gin.New()
+ store := memstore.NewStore([]byte("authentication-key"), []byte("encryption-keyencryption-key----"))
+ engine.Use(sessions.Sessions("gotosocial-session", store))
+ cwd, _ := os.Getwd()
+ tmPath := filepath.Join(cwd, fmt.Sprintf("%s*", config.TemplateConfig.BaseDir))
+ logger.Debugf("loading templates from %s", tmPath)
+ engine.LoadHTMLGlob(tmPath)
return &server{
APIGroup: engine.Group("/api").Group("/v1"),
logger: logger,
diff --git a/internal/config/config.go b/internal/config/config.go
index 5832ed53f..ce194cd52 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -27,25 +27,38 @@ import (
// Config pulls together all the configuration needed to run gotosocial
type Config struct {
- LogLevel string `yaml:"logLevel"`
- ApplicationName string `yaml:"applicationName"`
- DBConfig *DBConfig `yaml:"db"`
+ LogLevel string `yaml:"logLevel"`
+ ApplicationName string `yaml:"applicationName"`
+ DBConfig *DBConfig `yaml:"db"`
+ TemplateConfig *TemplateConfig `yaml:"template"`
}
-// New returns a new config, or an error if something goes amiss.
-// The path parameter is optional, for loading a configuration json from the given path.
-func New(path string) (*Config, error) {
- config := &Config{
- DBConfig: &DBConfig{},
+// FromFile returns a new config from a file, or an error if something goes amiss.
+func FromFile(path string) (*Config, error) {
+ c, err := loadFromFile(path)
+ if err != nil {
+ return nil, fmt.Errorf("error creating config: %s", err)
}
- if path != "" {
- var err error
- if config, err = loadFromFile(path); err != nil {
- return nil, fmt.Errorf("error creating config: %s", err)
- }
+ return c, nil
+}
+
+// Default returns a new config with default values.
+// Not yet implemented.
+func Default() *Config {
+ // TODO: find a way of doing this without code repetition, because having to
+ // repeat all values here and elsewhere is annoying and gonna be prone to mistakes.
+ return &Config{
+ DBConfig: &DBConfig{},
+ TemplateConfig: &TemplateConfig{},
}
+}
- return config, nil
+// Empty just returns an empty config
+func Empty() *Config {
+ return &Config{
+ DBConfig: &DBConfig{},
+ TemplateConfig: &TemplateConfig{},
+ }
}
// loadFromFile takes a path to a yaml file and attempts to load a Config object from it
@@ -63,8 +76,8 @@ func loadFromFile(path string) (*Config, error) {
return config, nil
}
-// ParseFlags sets flags on the config using the provided Flags object
-func (c *Config) ParseFlags(f KeyedFlags) {
+// ParseCLIFlags sets flags on the config using the provided Flags object
+func (c *Config) ParseCLIFlags(f KeyedFlags) {
fn := GetFlagNames()
// For all of these flags, we only want to set them on the config if:
@@ -108,6 +121,11 @@ func (c *Config) ParseFlags(f KeyedFlags) {
if c.DBConfig.Database == "" || f.IsSet(fn.DbDatabase) {
c.DBConfig.Database = f.String(fn.DbDatabase)
}
+
+ // template flags
+ if c.TemplateConfig.BaseDir == "" || f.IsSet(fn.TemplateBaseDir) {
+ c.TemplateConfig.BaseDir = f.String(fn.TemplateBaseDir)
+ }
}
// KeyedFlags is a wrapper for any type that can store keyed flags and give them back.
@@ -130,6 +148,7 @@ type Flags struct {
DbUser string
DbPassword string
DbDatabase string
+ TemplateBaseDir string
}
// GetFlagNames returns a struct containing the names of the various flags used for
@@ -145,6 +164,7 @@ func GetFlagNames() Flags {
DbUser: "db-user",
DbPassword: "db-password",
DbDatabase: "db-database",
+ TemplateBaseDir: "template-basedir",
}
}
@@ -161,5 +181,6 @@ func GetEnvNames() Flags {
DbUser: "GTS_DB_USER",
DbPassword: "GTS_DB_PASSWORD",
DbDatabase: "GTS_DB_DATABASE",
+ TemplateBaseDir: "GTS_TEMPLATE_BASEDIR",
}
}
diff --git a/internal/config/template.go b/internal/config/template.go
new file mode 100644
index 000000000..eba86f8e6
--- /dev/null
+++ b/internal/config/template.go
@@ -0,0 +1,25 @@
+/*
+ GoToSocial
+ Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+package config
+
+// TemplateConfig pertains to templating of web pages/email notifications and the like
+type TemplateConfig struct {
+ // Directory from which gotosocial will attempt to load html templates (.tmpl files).
+ BaseDir string `yaml:"baseDir"`
+}
diff --git a/internal/gtsmodel/account.go b/internal/gtsmodel/account.go
index 84ba027b2..67860146e 100644
--- a/internal/gtsmodel/account.go
+++ b/internal/gtsmodel/account.go
@@ -26,60 +26,130 @@ import (
"time"
)
-// Account represents a GoToSocial user account
+// Account represents either a local or a remote fediverse account, gotosocial or otherwise (mastodon, pleroma, etc)
type Account struct {
+ /*
+ BASIC INFO
+ */
+
+ // id of this account in the local database; the end-user will never need to know this, it's strictly internal
+ ID string `pg:"type:uuid,default:gen_random_uuid(),pk,notnull,unique"`
+ // Username of the account, should just be a string of [a-z0-9_]. Can be added to domain to create the full username in the form ``[username]@[domain]`` eg., ``user_96@example.org``
+ Username string `pg:",notnull,unique:userdomain"` // username and domain should be unique *with* each other
+ // Domain of the account, will be empty if this is a local account, otherwise something like ``example.org`` or ``mastodon.social``. Should be unique with username.
+ Domain string `pg:",unique:userdomain"` // username and domain
+
+ /*
+ ACCOUNT METADATA
+ */
+
+ // Avatar image for this account
Avatar
+ // Header image for this account
Header
- URI string
- URL string
- ID string `pg:"type:uuid,default:gen_random_uuid(),pk,notnull"`
- Username string
- Domain string
- Secret string
- PrivateKey string
- PublicKey string
- RemoteURL string
- CreatedAt time.Time `pg:"type:timestamp,notnull"`
- UpdatedAt time.Time `pg:"type:timestamp,notnull"`
- Note string
- DisplayName string
+ // DisplayName for this account. Can be empty, then just the Username will be used for display purposes.
+ DisplayName string
+ // a key/value map of fields that this account has added to their profile
+ Fields map[string]string
+ // A note that this account has on their profile (ie., the account's bio/description of themselves)
+ Note string
+ // Is this a memorial account, ie., has the user passed away?
+ Memorial bool
+ // This account has moved this account id in the database
+ MovedToAccountID int
+ // When was this account created?
+ CreatedAt time.Time `pg:"type:timestamp,notnull,default:now()"`
+ // When was this account last updated?
+ UpdatedAt time.Time `pg:"type:timestamp,notnull,default:now()"`
+ // When should this account function until
SubscriptionExpiresAt time.Time `pg:"type:timestamp"`
- Locked bool
- LastWebfingeredAt time.Time `pg:"type:timestamp"`
- InboxURL string
- OutboxURL string
- SharedInboxURL string
- FollowersURL string
- Protocol int
- Memorial bool
- MovedToAccountID int
- FeaturedCollectionURL string
- Fields map[string]string
- ActorType string
- Discoverable bool
- AlsoKnownAs string
- SilencedAt time.Time `pg:"type:timestamp"`
- SuspendedAt time.Time `pg:"type:timestamp"`
- TrustLevel int
- HideCollections bool
- SensitizedAt time.Time `pg:"type:timestamp"`
- SuspensionOrigin int
+
+ /*
+ PRIVACY SETTINGS
+ */
+
+ // Does this account need an approval for new followers?
+ Locked bool
+ // Should this account be shown in the instance's profile directory?
+ Discoverable bool
+
+ /*
+ ACTIVITYPUB THINGS
+ */
+
+ // What is the activitypub URI for this account discovered by webfinger?
+ URI string `pg:",unique"`
+ // At which URL can we see the user account in a web browser?
+ URL string `pg:",unique"`
+ // RemoteURL where this account is located. Will be empty if this is a local account.
+ RemoteURL string `pg:",unique"`
+ // Last time this account was located using the webfinger API.
+ LastWebfingeredAt time.Time `pg:"type:timestamp"`
+ // Address of this account's activitypub inbox, for sending activity to
+ InboxURL string `pg:",unique"`
+ // Address of this account's activitypub outbox
+ OutboxURL string `pg:",unique"`
+ // Don't support shared inbox right now so this is just a stub for a future implementation
+ SharedInboxURL string `pg:",unique"`
+ // URL for getting the followers list of this account
+ FollowersURL string `pg:",unique"`
+ // URL for getting the featured collection list of this account
+ FeaturedCollectionURL string `pg:",unique"`
+ // What type of activitypub actor is this account?
+ ActorType string
+ // This account is associated with x account id
+ AlsoKnownAs string
+
+ /*
+ CRYPTO FIELDS
+ */
+
+ Secret string
+ // Privatekey for validating activitypub requests, will obviously only be defined for local accounts
+ PrivateKey string
+ // Publickey for encoding activitypub requests, will be defined for both local and remote accounts
+ PublicKey string
+
+ /*
+ ADMIN FIELDS
+ */
+
+ // When was this account set to have all its media shown as sensitive?
+ SensitizedAt time.Time `pg:"type:timestamp"`
+ // When was this account silenced (eg., statuses only visible to followers, not public)?
+ SilencedAt time.Time `pg:"type:timestamp"`
+ // When was this account suspended (eg., don't allow it to log in/post, don't accept media/posts from this account)
+ SuspendedAt time.Time `pg:"type:timestamp"`
+ // How much do we trust this account 🤔
+ TrustLevel int
+ // Should we hide this account's collections?
+ HideCollections bool
+ // id of the user that suspended this account through an admin action
+ SuspensionOrigin int
}
+// Avatar represents the avatar for the account for display purposes
type Avatar struct {
- AvatarFileName string
- AvatarContentType string
- AvatarFileSize int
- AvatarUpdatedAt *time.Time `pg:"type:timestamp"`
- AvatarRemoteURL *url.URL `pg:"type:text"`
+ // File name of the avatar on local storage
+ AvatarFileName string
+ // Gif? png? jpeg?
+ AvatarContentType string
+ AvatarFileSize int
+ AvatarUpdatedAt *time.Time `pg:"type:timestamp"`
+ // Where can we retrieve the avatar?
+ AvatarRemoteURL *url.URL `pg:"type:text"`
AvatarStorageSchemaVersion int
}
+// Header represents the header of the account for display purposes
type Header struct {
- HeaderFileName string
- HeaderContentType string
- HeaderFileSize int
- HeaderUpdatedAt *time.Time `pg:"type:timestamp"`
- HeaderRemoteURL *url.URL `pg:"type:text"`
+ // File name of the header on local storage
+ HeaderFileName string
+ // Gif? png? jpeg?
+ HeaderContentType string
+ HeaderFileSize int
+ HeaderUpdatedAt *time.Time `pg:"type:timestamp"`
+ // Where can we retrieve the header?
+ HeaderRemoteURL *url.URL `pg:"type:text"`
HeaderStorageSchemaVersion int
}
diff --git a/internal/gtsmodel/application.go b/internal/gtsmodel/application.go
new file mode 100644
index 000000000..c0d6dddaf
--- /dev/null
+++ b/internal/gtsmodel/application.go
@@ -0,0 +1,30 @@
+/*
+ GoToSocial
+ Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+package gtsmodel
+
+type Application struct {
+ ID string `pg:"type:uuid,default:gen_random_uuid(),pk,notnull"`
+ Name string
+ Website string
+ RedirectURI string `json:"redirect_uri"`
+ ClientID string `json:"client_id"`
+ ClientSecret string `json:"client_secret"`
+ Scopes string `json:"scopes"`
+ VapidKey string `json:"vapid_key"`
+}
diff --git a/internal/gtsmodel/status.go b/internal/gtsmodel/status.go
index 39c450934..22e88c08e 100644
--- a/internal/gtsmodel/status.go
+++ b/internal/gtsmodel/status.go
@@ -22,11 +22,11 @@ import "time"
type Status struct {
ID string `pg:"type:uuid,default:gen_random_uuid(),pk,notnull"`
- URI string
- URL string
+ URI string `pg:",unique"`
+ URL string `pg:",unique"`
Content string
- CreatedAt time.Time `pg:"type:timestamp,notnull"`
- UpdatedAt time.Time `pg:"type:timestamp,notnull"`
+ CreatedAt time.Time `pg:"type:timestamp,notnull,default:now()"`
+ UpdatedAt time.Time `pg:"type:timestamp,notnull,default:now()"`
Local bool
AccountID string
InReplyToID string
diff --git a/internal/gtsmodel/user.go b/internal/gtsmodel/user.go
index 577590ddf..551cbe2a4 100644
--- a/internal/gtsmodel/user.go
+++ b/internal/gtsmodel/user.go
@@ -23,43 +23,98 @@ import (
"time"
)
+// User represents an actual human user of gotosocial. Note, this is a LOCAL gotosocial user, not a remote account.
+// To cross reference this local user with their account (which can be local or remote), use the AccountID field.
type User struct {
- ID string `pg:"type:uuid,default:gen_random_uuid(),pk,notnull"`
- Email string `pg:",notnull"`
- CreatedAt time.Time `pg:"type:timestamp,notnull"`
- UpdatedAt time.Time `pg:"type:timestamp,notnull"`
- EncryptedPassword string `pg:",notnull"`
- ResetPasswordToken string
- ResetPasswordSentAt time.Time `pg:"type:timestamp"`
- SignInCount int
- CurrentSignInAt time.Time `pg:"type:timestamp"`
- LastSignInAt time.Time `pg:"type:timestamp"`
- CurrentSignInIP net.IP
- LastSignInIP net.IP
- Admin bool
- ConfirmationToken string
- ConfirmedAt time.Time `pg:"type:timestamp"`
- ConfirmationSentAt time.Time `pg:"type:timestamp"`
- UnconfirmedEmail string
- Locale string
+ /*
+ BASIC INFO
+ */
+
+ // id of this user in the local database; the end-user will never need to know this, it's strictly internal
+ ID string `pg:"type:uuid,default:gen_random_uuid(),pk,notnull,unique"`
+ // confirmed email address for this user, this should be unique -- only one email address registered per instance, multiple users per email are not supported
+ Email string `pg:",notnull,unique"`
+ // The id of the local gtsmodel.Account entry for this user, if it exists (unconfirmed users don't have an account yet)
+ AccountID string `pg:"default:'',notnull,unique"`
+ // The encrypted password of this user, generated using https://pkg.go.dev/golang.org/x/crypto/bcrypt#GenerateFromPassword. A salt is included so we're safe against 🌈 tables
+ EncryptedPassword string `pg:",notnull"`
+
+ /*
+ USER METADATA
+ */
+
+ // When was this user created?
+ CreatedAt time.Time `pg:"type:timestamp,notnull,default:now()"`
+ // From what IP was this user created?
+ SignUpIP net.IP
+ // When was this user updated (eg., password changed, email address changed)?
+ UpdatedAt time.Time `pg:"type:timestamp,notnull,default:now()"`
+ // When did this user sign in for their current session?
+ CurrentSignInAt time.Time `pg:"type:timestamp"`
+ // What's the most recent IP of this user
+ CurrentSignInIP net.IP
+ // When did this user last sign in?
+ LastSignInAt time.Time `pg:"type:timestamp"`
+ // What's the previous IP of this user?
+ LastSignInIP net.IP
+ // How many times has this user signed in?
+ SignInCount int
+ // id of the user who invited this user (who let this guy in?)
+ InviteID string
+ // What languages does this user want to see?
+ ChosenLanguages []string
+ // What languages does this user not want to see?
+ FilteredLanguages []string
+ // In what timezone/locale is this user located?
+ Locale string
+ // Which application id created this user? See gtsmodel.Application
+ CreatedByApplicationID string
+ // When did we last contact this user
+ LastEmailedAt time.Time `pg:"type:timestamp"`
+
+ /*
+ USER CONFIRMATION
+ */
+
+ // What confirmation token did we send this user/what are we expecting back?
+ ConfirmationToken string
+ // When did the user confirm their email address
+ ConfirmedAt time.Time `pg:"type:timestamp"`
+ // When did we send email confirmation to this user?
+ ConfirmationSentAt time.Time `pg:"type:timestamp"`
+ // Email address that hasn't yet been confirmed
+ UnconfirmedEmail string
+
+ /*
+ ACL FLAGS
+ */
+
+ // Is this user a moderator?
+ Moderator bool
+ // Is this user an admin?
+ Admin bool
+ // Is this user disabled from posting?
+ Disabled bool
+ // Has this user been approved by a moderator?
+ Approved bool
+
+ /*
+ USER SECURITY
+ */
+
+ // The generated token that the user can use to reset their password
+ ResetPasswordToken string
+ // When did we email the user their reset-password email?
+ ResetPasswordSentAt time.Time `pg:"type:timestamp"`
+
EncryptedOTPSecret string
EncryptedOTPSecretIv string
EncryptedOTPSecretSalt string
- ConsumedTimestamp int
OTPRequiredForLogin bool
- LastEmailedAt time.Time `pg:"type:timestamp"`
OTPBackupCodes []string
- FilteredLanguages []string
- AccountID string `pg:",notnull"`
- Disabled bool
- Moderator bool
- InviteID string
+ ConsumedTimestamp int
RememberToken string
- ChosenLanguages []string
- CreatedByApplicationID string
- Approved bool
SignInToken string
SignInTokenSentAt time.Time `pg:"type:timestamp"`
WebauthnID string
- SignUpIP net.IP
}
diff --git a/internal/oauth/html.go b/internal/oauth/html.go
new file mode 100644
index 000000000..a3ae4318a
--- /dev/null
+++ b/internal/oauth/html.go
@@ -0,0 +1,9 @@
+package oauth
+
+const (
+ signInHTML = `
+`
+
+ authorizeHTML = `
+`
+)
diff --git a/internal/oauth/oauth.go b/internal/oauth/oauth.go
index 050c23dab..49e04a905 100644
--- a/internal/oauth/oauth.go
+++ b/internal/oauth/oauth.go
@@ -19,9 +19,17 @@
package oauth
import (
+ "fmt"
+ "net/http"
+ "net/url"
+
+ "github.com/gin-contrib/sessions"
+ "github.com/gin-gonic/gin"
"github.com/go-pg/pg/v10"
+ "github.com/google/uuid"
"github.com/gotosocial/gotosocial/internal/api"
"github.com/gotosocial/gotosocial/internal/gtsmodel"
+ "github.com/gotosocial/gotosocial/pkg/mastotypes"
"github.com/gotosocial/oauth2/v4"
"github.com/gotosocial/oauth2/v4/errors"
"github.com/gotosocial/oauth2/v4/manage"
@@ -37,12 +45,43 @@ type API struct {
log *logrus.Logger
}
+type login struct {
+ Email string `form:"username"`
+ Password string `form:"password"`
+}
+
+type code struct {
+ Code string `form:"code"`
+}
+
func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.Logger) *API {
manager := manage.NewDefaultManager()
manager.MapTokenStorage(ts)
manager.MapClientStorage(cs)
+ manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg)
+ sc := &server.Config{
+ TokenType: "Bearer",
+ // Must follow the spec.
+ AllowGetAccessRequest: false,
+ // Support only the non-implicit flow.
+ AllowedResponseTypes: []oauth2.ResponseType{oauth2.Code},
+ // Allow:
+ // - Authorization Code (for first & third parties)
+ // - Refreshing Tokens
+ //
+ // Deny:
+ // - Resource owner secrets (password grant)
+ // - Client secrets
+ AllowedGrantTypes: []oauth2.GrantType{
+ oauth2.AuthorizationCode,
+ oauth2.Refreshing,
+ },
+ AllowedCodeChallengeMethods: []oauth2.CodeChallengeMethod{
+ oauth2.CodeChallengePlain,
+ },
+ }
- srv := server.NewDefaultServer(manager)
+ srv := server.NewServer(sc, manager)
srv.SetInternalErrorHandler(func(err error) *errors.Response {
log.Errorf("internal oauth error: %s", err)
return nil
@@ -52,15 +91,29 @@ func New(ts oauth2.TokenStore, cs oauth2.ClientStore, conn *pg.DB, log *logrus.L
log.Errorf("internal response error: %s", re.Error)
})
- return &API{
+ api := &API{
manager: manager,
server: srv,
conn: conn,
log: log,
}
+
+ api.server.SetUserAuthorizationHandler(api.UserAuthorizationHandler)
+ api.server.SetClientInfoHandler(server.ClientFormHandler)
+ return api
}
func (a *API) AddRoutes(s api.Server) error {
+ s.AttachHandler(http.MethodPost, "/api/v1/apps", a.AppsPOSTHandler)
+
+ s.AttachHandler(http.MethodGet, "/auth/sign_in", a.SignInGETHandler)
+ s.AttachHandler(http.MethodPost, "/auth/sign_in", a.SignInPOSTHandler)
+
+ s.AttachHandler(http.MethodPost, "/oauth/token", a.TokenPOSTHandler)
+
+ s.AttachHandler(http.MethodGet, "/oauth/authorize", a.AuthorizeGETHandler)
+ s.AttachHandler(http.MethodPost, "/oauth/authorize", a.AuthorizePOSTHandler)
+
return nil
}
@@ -68,28 +121,326 @@ func incorrectPassword() (string, error) {
return "", errors.New("password/email combination was incorrect")
}
-func (a *API) PasswordAuthorizationHandler(email string, password string) (userid string, err error) {
+/*
+ MAIN HANDLERS -- serve these through a server/router
+*/
+
+// AppsPOSTHandler should be served at https://example.org/api/v1/apps
+// It is equivalent to: https://docs.joinmastodon.org/methods/apps/
+func (a *API) AppsPOSTHandler(c *gin.Context) {
+ l := a.log.WithField("func", "AppsPOSTHandler")
+ l.Trace("entering AppsPOSTHandler")
+
+ form := &mastotypes.ApplicationPOSTRequest{}
+ if err := c.ShouldBind(form); err != nil {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
+ return
+ }
+
+ // permitted length for most fields
+ permittedLength := 64
+ // redirect can be a bit bigger because we probably need to encode data in the redirect uri
+ permittedRedirect := 256
+
+ // check lengths of fields before proceeding so the user can't spam huge entries into the database
+ if len(form.ClientName) > permittedLength {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("client_name must be less than %d bytes", permittedLength)})
+ return
+ }
+ if len(form.Website) > permittedLength {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("website must be less than %d bytes", permittedLength)})
+ return
+ }
+ if len(form.RedirectURIs) > permittedRedirect {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("redirect_uris must be less than %d bytes", permittedRedirect)})
+ return
+ }
+ if len(form.Scopes) > permittedLength {
+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("scopes must be less than %d bytes", permittedLength)})
+ return
+ }
+
+ // set default 'read' for scopes if it's not set
+ var scopes string
+ if form.Scopes == "" {
+ scopes = "read"
+ } else {
+ scopes = form.Scopes
+ }
+
+ // generate new IDs for this application and its associated client
+ clientID := uuid.NewString()
+ clientSecret := uuid.NewString()
+ vapidKey := uuid.NewString()
+
+ // generate the application to put in the database
+ app := &gtsmodel.Application{
+ Name: form.ClientName,
+ Website: form.Website,
+ RedirectURI: form.RedirectURIs,
+ ClientID: clientID,
+ ClientSecret: clientSecret,
+ Scopes: scopes,
+ VapidKey: vapidKey,
+ }
+
+ // chuck it in the db
+ if _, err := a.conn.Model(app).Insert(); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+
+ // now we need to model an oauth client from the application that the oauth library can use
+ oc := &oauthClient{
+ ID: clientID,
+ Secret: clientSecret,
+ Domain: form.RedirectURIs,
+ UserID: "", // This client isn't yet associated with a specific user, it's just an app client right now
+ }
+
+ // chuck it in the db
+ if _, err := a.conn.Model(oc).Insert(); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+
+ // done, return the new app information per the spec here: https://docs.joinmastodon.org/methods/apps/
+ c.JSON(http.StatusOK, app)
+}
+
+// SignInGETHandler should be served at https://example.org/auth/sign_in.
+// The idea is to present a sign in page to the user, where they can enter their username and password.
+// The form will then POST to the sign in page, which will be handled by SignInPOSTHandler
+func (a *API) SignInGETHandler(c *gin.Context) {
+ a.log.WithField("func", "SignInGETHandler").Trace("serving sign in html")
+ c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{})
+}
+
+// SignInPOSTHandler should be served at https://example.org/auth/sign_in.
+// The idea is to present a sign in page to the user, where they can enter their username and password.
+// The handler will then redirect to the auth handler served at /auth
+func (a *API) SignInPOSTHandler(c *gin.Context) {
+ l := a.log.WithField("func", "SignInPOSTHandler")
+ s := sessions.Default(c)
+ form := &login{}
+ if err := c.ShouldBind(form); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ l.Tracef("parsed form: %+v", form)
+
+ userid, err := a.ValidatePassword(form.Email, form.Password)
+ if err != nil {
+ c.String(http.StatusForbidden, err.Error())
+ return
+ }
+
+ s.Set("username", userid)
+ if err := s.Save(); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+
+ l.Trace("redirecting to auth page")
+ c.Redirect(http.StatusFound, "/oauth/authorize")
+}
+
+// TokenPOSTHandler should be served as a POST at https://example.org/oauth/token
+// The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs.
+// See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token
+func (a *API) TokenPOSTHandler(c *gin.Context) {
+ l := a.log.WithField("func", "TokenHandler")
+ l.Trace("entered token handler, will now go to server.HandleTokenRequest")
+ if err := a.server.HandleTokenRequest(c.Writer, c.Request); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ }
+}
+
+// AuthorizeGETHandler should be served as GET at https://example.org/oauth/authorize
+// The idea here is to present an oauth authorize page to the user, with a button
+// that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user
+func (a *API) AuthorizeGETHandler(c *gin.Context) {
+ l := a.log.WithField("func", "AuthorizeGETHandler")
+ s := sessions.Default(c)
+
+ // Username will be set in the session by AuthorizePOSTHandler if the caller has already gone through the authentication flow
+ // If it's not set, then we don't know yet who the user is, so we need to redirect them to the sign in page.
+ v := s.Get("username")
+ if username, ok := v.(string); !ok || username == "" {
+ l.Trace("username was empty, parsing form then redirecting to sign in page")
+
+ // first make sure they've filled out the authorize form with the required values
+ form := &mastotypes.OAuthAuthorize{}
+ if err := c.ShouldBind(form); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ l.Tracef("parsed form: %+v", form)
+
+ // these fields are *required* so check 'em
+ if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "missing one of: response_type, client_id or redirect_uri"})
+ return
+ }
+
+ // save these values from the form so we can use them elsewhere in the session
+ s.Set("force_login", form.ForceLogin)
+ s.Set("response_type", form.ResponseType)
+ s.Set("client_id", form.ClientID)
+ s.Set("redirect_uri", form.RedirectURI)
+ s.Set("scope", form.Scope)
+ if err := s.Save(); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+
+ // send them to the sign in page so we can tell who they are
+ c.Redirect(http.StatusFound, "/auth/sign_in")
+ return
+ }
+
+ // Check if we have a code already. If we do, it means the user used urn:ietf:wg:oauth:2.0:oob as their redirect URI
+ // and were sent here, which means they just want the code displayed so they can use it out of band.
+ code := &code{}
+ if err := c.Bind(code); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+
+ // the authorize template will either:
+ // 1. Display the code to the user if they're already authorized and were redirected here because they selected urn:ietf:wg:oauth:2.0:oob.
+ // 2. Display a form where they can get some information about the app that's trying to authorize, and approve it, which will then go to AuthorizePOSTHandler
+ l.Trace("serving authorize html")
+ c.HTML(http.StatusOK, "authorize.tmpl", gin.H{
+ "code": code.Code,
+ })
+}
+
+// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize
+// The idea here is to present an oauth authorize page to the user, with a button
+// that they have to click to accept. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user
+func (a *API) AuthorizePOSTHandler(c *gin.Context) {
+ l := a.log.WithField("func", "AuthorizePOSTHandler")
+ s := sessions.Default(c)
+
+ v := s.Get("username")
+ if username, ok := v.(string); !ok || username == "" {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "you are not signed in"})
+ }
+
+ values := url.Values{}
+
+ if v, ok := s.Get("force_login").(string); !ok {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "session missing force_login"})
+ return
+ } else {
+ values.Add("force_login", v)
+ }
+
+ if v, ok := s.Get("response_type").(string); !ok {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "session missing response_type"})
+ return
+ } else {
+ values.Add("response_type", v)
+ }
+
+ if v, ok := s.Get("client_id").(string); !ok {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "session missing client_id"})
+ return
+ } else {
+ values.Add("client_id", v)
+ }
+
+ if v, ok := s.Get("redirect_uri").(string); !ok {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "session missing redirect_uri"})
+ return
+ } else {
+ // todo: explain this little hack
+ if v == "urn:ietf:wg:oauth:2.0:oob" {
+ v = "http://localhost:8080/oauth/authorize"
+ }
+ values.Add("redirect_uri", v)
+ }
+
+ if v, ok := s.Get("scope").(string); !ok {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "session missing scope"})
+ return
+ } else {
+ values.Add("scope", v)
+ }
+
+ if v, ok := s.Get("username").(string); !ok {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "session missing username"})
+ return
+ } else {
+ values.Add("username", v)
+ }
+
+ c.Request.Form = values
+ l.Tracef("values on request set to %+v", c.Request.Form)
+
+ if err := s.Save(); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ return
+ }
+
+ if err := a.server.HandleAuthorizeRequest(c.Writer, c.Request); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ }
+}
+
+/*
+ SUB-HANDLERS -- don't serve these directly, they should be attached to the oauth2 server
+*/
+
+// PasswordAuthorizationHandler takes a username (in this case, we use an email address)
+// and a password. The goal is to authenticate the password against the one for that email
+// address stored in the database. If OK, we return the userid (a uuid) for that user,
+// so that it can be used in further Oauth flows to generate a token/retreieve an oauth client from the db.
+func (a *API) ValidatePassword(email string, password string) (userid string, err error) {
+ l := a.log.WithField("func", "PasswordAuthorizationHandler")
+
+ // make sure an email/password was provided and bail if not
+ if email == "" || password == "" {
+ l.Debug("email or password was not provided")
+ return incorrectPassword()
+ }
+
// first we select the user from the database based on email address, bail if no user found for that email
gtsUser := &gtsmodel.User{}
if err := a.conn.Model(gtsUser).Where("email = ?", email).Select(); err != nil {
- a.log.Debugf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err)
+ l.Debugf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err)
return incorrectPassword()
}
// make sure a password is actually set and bail if not
if gtsUser.EncryptedPassword == "" {
- a.log.Warnf("encrypted password for user %s was empty for some reason", gtsUser.Email)
+ l.Warnf("encrypted password for user %s was empty for some reason", gtsUser.Email)
return incorrectPassword()
}
// compare the provided password with the encrypted one from the db, bail if they don't match
if err := bcrypt.CompareHashAndPassword([]byte(gtsUser.EncryptedPassword), []byte(password)); err != nil {
- a.log.Debugf("password hash didn't match for user %s during login attempt: %s", gtsUser.Email, err)
+ l.Debugf("password hash didn't match for user %s during login attempt: %s", gtsUser.Email, err)
return incorrectPassword()
}
- // If we've made it this far the email/password is correct so we need the oauth client-id of the user
- // This is, conveniently, the same as the user ID, so we can just return it.
+ // If we've made it this far the email/password is correct, so we can just return the id of the user.
userid = gtsUser.ID
+ l.Tracef("returning (%s, %s)", userid, err)
return
}
+
+// UserAuthorizationHandler gets the user's ID from the 'username' field of the request form,
+// or redirects to the /auth/sign_in page, if this key is not present.
+func (a *API) UserAuthorizationHandler(w http.ResponseWriter, r *http.Request) (userID string, err error) {
+ l := a.log.WithField("func", "UserAuthorizationHandler")
+ userID = r.FormValue("username")
+ if userID == "" {
+ l.Trace("username was empty, redirecting to sign in page")
+ http.Redirect(w, r, "/auth/sign_in", http.StatusFound)
+ return "", nil
+ }
+ l.Tracef("returning (%s, %s)", userID, err)
+ return userID, err
+}
diff --git a/internal/oauth/oauth_test.go b/internal/oauth/oauth_test.go
new file mode 100644
index 000000000..9ee5ac9a8
--- /dev/null
+++ b/internal/oauth/oauth_test.go
@@ -0,0 +1,130 @@
+package oauth
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/go-pg/pg/v10"
+ "github.com/go-pg/pg/v10/orm"
+ "github.com/gotosocial/gotosocial/internal/api"
+ "github.com/gotosocial/gotosocial/internal/config"
+ "github.com/gotosocial/gotosocial/internal/gtsmodel"
+ "github.com/gotosocial/oauth2/v4"
+ "github.com/sirupsen/logrus"
+ "github.com/stretchr/testify/suite"
+ "golang.org/x/crypto/bcrypt"
+)
+
+type OauthTestSuite struct {
+ suite.Suite
+ tokenStore oauth2.TokenStore
+ clientStore oauth2.ClientStore
+ conn *pg.DB
+ testAccount *gtsmodel.Account
+ testUser *gtsmodel.User
+ testClient *oauthClient
+ config *config.Config
+}
+
+const ()
+
+// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout
+func (suite *OauthTestSuite) SetupSuite() {
+ encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("test-password"), bcrypt.DefaultCost)
+ if err != nil {
+ logrus.Panicf("error encrypting user pass: %s", err)
+ }
+
+ suite.testAccount = &gtsmodel.Account{}
+ suite.testUser = &gtsmodel.User{
+ EncryptedPassword: string(encryptedPassword),
+ Email: "user@localhost",
+ AccountID: "some-account-id-it-doesn't-matter-really-since-this-user-doesn't-actually-have-an-account!",
+ }
+ suite.testClient = &oauthClient{
+ ID: "a-known-client-id",
+ Secret: "some-secret",
+ Domain: "http://localhost:8080",
+ }
+
+ // because go tests are run within the test package directory, we need to fiddle with the templateconfig
+ // basedir in a way that we wouldn't normally have to do when running the binary, in order to make
+ // the templates actually load
+ c := config.Empty()
+ c.TemplateConfig.BaseDir = "../../web/template/"
+ suite.config = c
+}
+
+// SetupTest creates a postgres connection and creates the oauth_clients table before each test
+func (suite *OauthTestSuite) SetupTest() {
+ suite.conn = pg.Connect(&pg.Options{})
+ if err := suite.conn.Ping(context.Background()); err != nil {
+ logrus.Panicf("db connection error: %s", err)
+ }
+
+ models := []interface{}{
+ &oauthClient{},
+ &oauthToken{},
+ &gtsmodel.User{},
+ &gtsmodel.Account{},
+ &gtsmodel.Application{},
+ }
+
+ for _, m := range models {
+ if err := suite.conn.Model(m).CreateTable(&orm.CreateTableOptions{
+ IfNotExists: true,
+ }); err != nil {
+ logrus.Panicf("db connection error: %s", err)
+ }
+ }
+
+ suite.tokenStore = NewPGTokenStore(context.Background(), suite.conn, logrus.New())
+ suite.clientStore = NewPGClientStore(suite.conn)
+
+ if _, err := suite.conn.Model(suite.testUser).Insert(); err != nil {
+ logrus.Panicf("could not insert test user into db: %s", err)
+ }
+
+ if _, err := suite.conn.Model(suite.testClient).Insert(); err != nil {
+ logrus.Panicf("could not insert test client into db: %s", err)
+ }
+
+}
+
+// TearDownTest drops the oauth_clients table and closes the pg connection after each test
+func (suite *OauthTestSuite) TearDownTest() {
+ models := []interface{}{
+ &oauthClient{},
+ &oauthToken{},
+ &gtsmodel.User{},
+ &gtsmodel.Account{},
+ &gtsmodel.Application{},
+ }
+ for _, m := range models {
+ if err := suite.conn.Model(m).DropTable(&orm.DropTableOptions{}); err != nil {
+ logrus.Panicf("drop table error: %s", err)
+ }
+ }
+ if err := suite.conn.Close(); err != nil {
+ logrus.Panicf("error closing db connection: %s", err)
+ }
+ suite.conn = nil
+}
+
+func (suite *OauthTestSuite) TestAPIInitialize() {
+ log := logrus.New()
+ log.SetLevel(logrus.TraceLevel)
+
+ r := api.New(suite.config, log)
+ api := New(suite.tokenStore, suite.clientStore, suite.conn, log)
+ api.AddRoutes(r)
+ go r.Start()
+ time.Sleep(30 * time.Second)
+ // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&response_type=code&redirect_uri=https://example.org
+ // http://localhost:8080/oauth/authorize?client_id=a-known-client-id&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob
+}
+
+func TestOauthTestSuite(t *testing.T) {
+ suite.Run(t, new(OauthTestSuite))
+}
diff --git a/internal/oauth/pgclientstore.go b/internal/oauth/pgclientstore.go
index 22bb54f55..1df46fedb 100644
--- a/internal/oauth/pgclientstore.go
+++ b/internal/oauth/pgclientstore.go
@@ -20,6 +20,7 @@ package oauth
import (
"context"
+ "fmt"
"github.com/go-pg/pg/v10"
"github.com/gotosocial/oauth2/v4"
@@ -42,7 +43,7 @@ func (pcs *pgClientStore) GetByID(ctx context.Context, clientID string) (oauth2.
ID: clientID,
}
if err := pcs.conn.WithContext(ctx).Model(poc).Where("id = ?", poc.ID).Select(); err != nil {
- return nil, err
+ return nil, fmt.Errorf("error in clientstore getbyid searching for client %s: %s", clientID, err)
}
return models.New(poc.ID, poc.Secret, poc.Domain, poc.UserID), nil
}
@@ -55,7 +56,10 @@ func (pcs *pgClientStore) Set(ctx context.Context, id string, cli oauth2.ClientI
UserID: cli.GetUserID(),
}
_, err := pcs.conn.WithContext(ctx).Model(poc).OnConflict("(id) DO UPDATE").Insert()
- return err
+ if err != nil {
+ return fmt.Errorf("error in clientstore set: %s", err)
+ }
+ return nil
}
func (pcs *pgClientStore) Delete(ctx context.Context, id string) error {
@@ -63,7 +67,10 @@ func (pcs *pgClientStore) Delete(ctx context.Context, id string) error {
ID: id,
}
_, err := pcs.conn.WithContext(ctx).Model(poc).Where("id = ?", poc.ID).Delete()
- return err
+ if err != nil {
+ return fmt.Errorf("error in clientstore delete: %s", err)
+ }
+ return nil
}
type oauthClient struct {
diff --git a/internal/oauth/pgclientstore_test.go b/internal/oauth/pgclientstore_test.go
index d6a76981f..eb011fe01 100644
--- a/internal/oauth/pgclientstore_test.go
+++ b/internal/oauth/pgclientstore_test.go
@@ -96,7 +96,6 @@ func (suite *PgClientStoreTestSuite) TestClientSetAndDelete() {
deletedClient, err := cs.GetByID(context.Background(), suite.testClientID)
suite.Assert().Nil(deletedClient)
suite.Assert().NotNil(err)
- suite.EqualValues("pg: no rows in result set", err.Error())
}
func TestPgClientStoreTestSuite(t *testing.T) {
diff --git a/internal/oauth/pgtokenstore.go b/internal/oauth/pgtokenstore.go
index a927be862..0271afafb 100644
--- a/internal/oauth/pgtokenstore.go
+++ b/internal/oauth/pgtokenstore.go
@@ -21,6 +21,7 @@ package oauth
import (
"context"
"errors"
+ "fmt"
"time"
"github.com/go-pg/pg/v10"
@@ -98,32 +99,44 @@ func (pts *pgTokenStore) Create(ctx context.Context, info oauth2.TokenInfo) erro
return errors.New("info param was not a models.Token")
}
_, err := pts.conn.WithContext(ctx).Model(oauthTokenToPGToken(t)).Insert()
- return err
+ if err != nil {
+ return fmt.Errorf("error in tokenstore create: %s", err)
+ }
+ return nil
}
// RemoveByCode deletes a token from the DB based on the Code field
func (pts *pgTokenStore) RemoveByCode(ctx context.Context, code string) error {
_, err := pts.conn.Model(&oauthToken{}).Where("code = ?", code).Delete()
- return err
+ if err != nil {
+ return fmt.Errorf("error in tokenstore removebycode: %s", err)
+ }
+ return nil
}
// RemoveByAccess deletes a token from the DB based on the Access field
func (pts *pgTokenStore) RemoveByAccess(ctx context.Context, access string) error {
_, err := pts.conn.Model(&oauthToken{}).Where("access = ?", access).Delete()
- return err
+ if err != nil {
+ return fmt.Errorf("error in tokenstore removebyaccess: %s", err)
+ }
+ return nil
}
// RemoveByRefresh deletes a token from the DB based on the Refresh field
func (pts *pgTokenStore) RemoveByRefresh(ctx context.Context, refresh string) error {
_, err := pts.conn.Model(&oauthToken{}).Where("refresh = ?", refresh).Delete()
- return err
+ if err != nil {
+ return fmt.Errorf("error in tokenstore removebyrefresh: %s", err)
+ }
+ return nil
}
// GetByCode selects a token from the DB based on the Code field
func (pts *pgTokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) {
pgt := &oauthToken{}
if err := pts.conn.Model(pgt).Where("code = ?", code).Select(); err != nil {
- return nil, err
+ return nil, fmt.Errorf("error in tokenstore getbycode: %s", err)
}
return pgTokenToOauthToken(pgt), nil
}
@@ -132,7 +145,7 @@ func (pts *pgTokenStore) GetByCode(ctx context.Context, code string) (oauth2.Tok
func (pts *pgTokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) {
pgt := &oauthToken{}
if err := pts.conn.Model(pgt).Where("access = ?", access).Select(); err != nil {
- return nil, err
+ return nil, fmt.Errorf("error in tokenstore getbyaccess: %s", err)
}
return pgTokenToOauthToken(pgt), nil
}
@@ -141,7 +154,7 @@ func (pts *pgTokenStore) GetByAccess(ctx context.Context, access string) (oauth2
func (pts *pgTokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) {
pgt := &oauthToken{}
if err := pts.conn.Model(pgt).Where("refresh = ?", refresh).Select(); err != nil {
- return nil, err
+ return nil, fmt.Errorf("error in tokenstore getbyrefresh: %s", err)
}
return pgTokenToOauthToken(pgt), nil
}
@@ -165,15 +178,15 @@ type oauthToken struct {
UserID string
RedirectURI string
Scope string
- Code string `pg:",pk"`
+ Code string `pg:"default:'',pk"`
CodeChallenge string
CodeChallengeMethod string
CodeCreateAt time.Time `pg:"type:timestamp"`
CodeExpiresAt time.Time `pg:"type:timestamp"`
- Access string `pg:",pk"`
+ Access string `pg:"default:'',pk"`
AccessCreateAt time.Time `pg:"type:timestamp"`
AccessExpiresAt time.Time `pg:"type:timestamp"`
- Refresh string `pg:",pk"`
+ Refresh string `pg:"default:'',pk"`
RefreshCreateAt time.Time `pg:"type:timestamp"`
RefreshExpiresAt time.Time `pg:"type:timestamp"`
}