account registration flow working

This commit is contained in:
tsmethurst 2021-03-31 23:59:48 +02:00
commit bcfa4b8881
8 changed files with 82 additions and 13 deletions

View file

@ -99,16 +99,16 @@ func (m *accountModule) accountCreate(form *mastotypes.AccountCreateRequest, sig
} }
l.Tracef("generating a token for user %s with account %s and application %s", user.ID, user.AccountID, app.ID) l.Tracef("generating a token for user %s with account %s and application %s", user.ID, user.AccountID, app.ID)
ti, err := m.oauthServer.GenerateUserAccessToken(token, app.ClientSecret, user.ID) accessToken, err := m.oauthServer.GenerateUserAccessToken(token, app.ClientSecret, user.ID)
if err != nil { if err != nil {
return nil, fmt.Errorf("error creating new access token for user %s: %s", user.ID, err) return nil, fmt.Errorf("error creating new access token for user %s: %s", user.ID, err)
} }
return &mastotypes.Token{ return &mastotypes.Token{
AccessToken: ti.GetCode(), AccessToken: accessToken.GetAccess(),
TokenType: "Bearer", TokenType: "Bearer",
Scope: ti.GetScope(), Scope: accessToken.GetScope(),
CreatedAt: ti.GetCodeCreateAt().Unix(), CreatedAt: accessToken.GetAccessCreateAt().Unix(),
}, nil }, nil
} }

View file

@ -7,6 +7,7 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/apimodule" "github.com/superseriousbusiness/gotosocial/internal/apimodule"
"github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/config"
"github.com/superseriousbusiness/gotosocial/internal/db" "github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/db/model"
"github.com/superseriousbusiness/gotosocial/internal/router" "github.com/superseriousbusiness/gotosocial/internal/router"
"github.com/superseriousbusiness/gotosocial/internal/storage" "github.com/superseriousbusiness/gotosocial/internal/storage"
) )
@ -40,3 +41,23 @@ func (m *fileServer) Route(s router.Router) error {
// s.AttachHandler(http.MethodPost, appsPath, m.appsPOSTHandler) // s.AttachHandler(http.MethodPost, appsPath, m.appsPOSTHandler)
return nil return nil
} }
func (m *fileServer) CreateTables(db db.DB) error {
models := []interface{}{
&model.User{},
&model.Account{},
&model.Follow{},
&model.FollowRequest{},
&model.Status{},
&model.Application{},
&model.EmailDomainBlock{},
&model.MediaAttachment{},
}
for _, m := range models {
if err := db.CreateTable(m); err != nil {
return fmt.Errorf("error creating table: %s", err)
}
}
return nil
}

View file

@ -33,7 +33,7 @@ type User struct {
// id of this user in the local database; the end-user will never need to know this, it's strictly internal // 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"` 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 // 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:"default:'',notnull,unique"` Email string `pg:"default:null,unique"`
// The id of the local gtsmodel.Account entry for this user, if it exists (unconfirmed users don't have an account yet) // 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"` 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 // 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

View file

@ -77,6 +77,9 @@ var Run action.GTSAction = func(ctx context.Context, c *config.Config, log *logr
if err := m.Route(router); err != nil { if err := m.Route(router); err != nil {
return fmt.Errorf("routing error: %s", err) return fmt.Errorf("routing error: %s", err)
} }
if err := m.CreateTables(dbService); err != nil {
return fmt.Errorf("table creation error: %s", err)
}
} }
gts, err := New(dbService, &cache.MockCache{}, router, federation.New(dbService), c) gts, err := New(dbService, &cache.MockCache{}, router, federation.New(dbService), c)

View file

@ -20,6 +20,7 @@ package oauth
import ( import (
"context" "context"
"fmt"
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -169,19 +170,40 @@ func (s *s) ValidationBearerToken(r *http.Request) (oauth2.TokenInfo, error) {
// //
// The ti parameter refers to an existing Application token that was used to make the upstream // The ti parameter refers to an existing Application token that was used to make the upstream
// request. This token needs to be validated and exist in database in order to create a new token. // request. This token needs to be validated and exist in database in order to create a new token.
func (s *s) GenerateUserAccessToken(ti oauth2.TokenInfo, clientSecret string, userID string) (accessToken oauth2.TokenInfo, err error) { func (s *s) GenerateUserAccessToken(ti oauth2.TokenInfo, clientSecret string, userID string) (oauth2.TokenInfo, error) {
tgr := &oauth2.TokenGenerateRequest{
authToken, err := s.server.Manager.GenerateAuthToken(context.Background(), oauth2.Code, &oauth2.TokenGenerateRequest{
ClientID: ti.GetClientID(), ClientID: ti.GetClientID(),
ClientSecret: clientSecret, ClientSecret: clientSecret,
UserID: userID, UserID: userID,
RedirectURI: ti.GetRedirectURI(), RedirectURI: ti.GetRedirectURI(),
Scope: ti.GetScope(), Scope: ti.GetScope(),
Code: ti.GetCode(), })
// CodeChallenge: ti.GetCodeChallenge(), if err != nil {
// CodeChallengeMethod: ti.GetCodeChallengeMethod(), return nil, fmt.Errorf("error generating first auth token: %s", err)
} }
if authToken == nil {
return nil, errors.New("generated auth token was empty")
}
s.log.Tracef("obtained auth token: %+v", authToken)
return s.server.Manager.GenerateAccessToken(context.Background(), oauth2.AuthorizationCode, tgr) accessToken, err := s.server.Manager.GenerateAccessToken(context.Background(), oauth2.AuthorizationCode, &oauth2.TokenGenerateRequest{
ClientID: authToken.GetClientID(),
ClientSecret: clientSecret,
// UserID: userID,
RedirectURI: authToken.GetRedirectURI(),
Scope: authToken.GetScope(),
Code: authToken.GetCode(),
})
if err != nil {
return nil, fmt.Errorf("error generating first auth token: %s", err)
}
if accessToken == nil {
return nil, errors.New("generated access token was empty")
}
s.log.Tracef("obtained access token: %+v", accessToken)
return accessToken, nil
} }
func New(database db.DB, log *logrus.Logger) Server { func New(database db.DB, log *logrus.Logger) Server {
@ -228,5 +250,6 @@ func New(database db.DB, log *logrus.Logger) Server {
srv.SetClientInfoHandler(server.ClientFormHandler) srv.SetClientInfoHandler(server.ClientFormHandler)
return &s{ return &s{
server: srv, server: srv,
log: log,
} }
} }

View file

@ -121,6 +121,9 @@ func (pts *tokenStore) RemoveByRefresh(ctx context.Context, refresh string) erro
// GetByCode selects a token from the DB based on the Code field // GetByCode selects a token from the DB based on the Code field
func (pts *tokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) { func (pts *tokenStore) GetByCode(ctx context.Context, code string) (oauth2.TokenInfo, error) {
if code == "" {
return nil, nil
}
pgt := &Token{ pgt := &Token{
Code: code, Code: code,
} }
@ -132,6 +135,9 @@ func (pts *tokenStore) GetByCode(ctx context.Context, code string) (oauth2.Token
// GetByAccess selects a token from the DB based on the Access field // GetByAccess selects a token from the DB based on the Access field
func (pts *tokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) { func (pts *tokenStore) GetByAccess(ctx context.Context, access string) (oauth2.TokenInfo, error) {
if access == "" {
return nil, nil
}
pgt := &Token{ pgt := &Token{
Access: access, Access: access,
} }
@ -143,6 +149,9 @@ func (pts *tokenStore) GetByAccess(ctx context.Context, access string) (oauth2.T
// GetByRefresh selects a token from the DB based on the Refresh field // GetByRefresh selects a token from the DB based on the Refresh field
func (pts *tokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) { func (pts *tokenStore) GetByRefresh(ctx context.Context, refresh string) (oauth2.TokenInfo, error) {
if refresh == "" {
return nil, nil
}
pgt := &Token{ pgt := &Token{
Refresh: refresh, Refresh: refresh,
} }

View file

@ -43,11 +43,11 @@ type Application struct {
// And here: https://docs.joinmastodon.org/client/token/ // And here: https://docs.joinmastodon.org/client/token/
type ApplicationPOSTRequest struct { type ApplicationPOSTRequest struct {
// A name for your application // A name for your application
ClientName string `form:"client_name"` ClientName string `form:"client_name" binding:"required"`
// Where the user should be redirected after authorization. // Where the user should be redirected after authorization.
// To display the authorization code to the user instead of redirecting // To display the authorization code to the user instead of redirecting
// to a web page, use urn:ietf:wg:oauth:2.0:oob in this parameter. // to a web page, use urn:ietf:wg:oauth:2.0:oob in this parameter.
RedirectURIs string `form:"redirect_uris"` RedirectURIs string `form:"redirect_uris" binding:"required"`
// Space separated list of scopes. If none is provided, defaults to read. // Space separated list of scopes. If none is provided, defaults to read.
Scopes string `form:"scopes"` Scopes string `form:"scopes"`
// A URL to the homepage of your app // A URL to the homepage of your app

13
scripts/auth_flow.sh Normal file
View file

@ -0,0 +1,13 @@
#!/bin/sh
# Step 1: create the app to register the new account
curl -X POST -F "client_name=ahhhhhh" -F "redirect_uris=http://localhost:8080" localhost:8080/api/v1/apps
# Step 2: obtain a code for that app
curl -X POST -F "scope=read" -F "grant_type=client_credentials" -F "client_id=bbec8b67-b389-49fb-ad9c-4a990e95d75a" -F "client_secret=da21d8b1-0705-4a1c-a38e-96060ab5553d" -F "redirect_uri=http://localhost:8080" localhost:8080/oauth/token
# Step 3: use the code to register a new account
curl -H "Authorization: Bearer MGVHMZQYYMYTNJK4OC0ZN2I3LTGWNWETMGE3ZTY2NTJKYZE4" -F "reason=seems like a good time my dude" -F "email=user7@example.org" -F "username=test_user7" -F "password=this is a big long password" -F "agreement=true" -F "locale=en" localhost:8080/api/v1/accounts
# Step 4: verify the returned access token
curl -H "Authorization: Bearer ODGYODAWNTUTZJUZZI0ZMJK3LWEXMJYTYZA5NMVKZDYWMGQY" localhost:8080/api/v1/accounts/verify_credentials