summaryrefslogtreecommitdiff
path: root/internal/api
diff options
context:
space:
mode:
authorLibravatar tobi <31960611+tsmethurst@users.noreply.github.com>2021-10-14 14:26:04 +0200
committerLibravatar GitHub <noreply@github.com>2021-10-14 14:26:04 +0200
commit107685e22e809123a31e6518249d14888767f0fe (patch)
tree3a46ca8a095f7ec1a0ee65845364b498099b6954 /internal/api
parentgo fmt (#278) (diff)
downloadgotosocial-107685e22e809123a31e6518249d14888767f0fe.tar.xz
User password change (#280)
* start passwordChangeHandler * add user scope * add user module / api path * add password change request * make comment clearer * add user to processor * required true * add processor call to handler * don't pass tc or channel * change password func + tests * add some first docs about password management * update swagger docs * add api tests * go fmt * test fixes
Diffstat (limited to 'internal/api')
-rw-r--r--internal/api/client/user/passwordchange.go97
-rw-r--r--internal/api/client/user/passwordchange_test.go157
-rw-r--r--internal/api/client/user/user.go55
-rw-r--r--internal/api/client/user/user_test.go73
-rw-r--r--internal/api/model/user.go37
5 files changed, 419 insertions, 0 deletions
diff --git a/internal/api/client/user/passwordchange.go b/internal/api/client/user/passwordchange.go
new file mode 100644
index 000000000..581abe526
--- /dev/null
+++ b/internal/api/client/user/passwordchange.go
@@ -0,0 +1,97 @@
+/*
+ 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 user
+
+import (
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/sirupsen/logrus"
+ "github.com/superseriousbusiness/gotosocial/internal/api/model"
+ "github.com/superseriousbusiness/gotosocial/internal/oauth"
+)
+
+// PasswordChangePOSTHandler swagger:operation POST /api/v1/user/password_change userPasswordChange
+//
+// Change the password of authenticated user.
+//
+// The parameters can also be given in the body of the request, as JSON, if the content-type is set to 'application/json'.
+// The parameters can also be given in the body of the request, as XML, if the content-type is set to 'application/xml'.
+//
+// ---
+// tags:
+// - user
+//
+// consumes:
+// - application/json
+// - application/xml
+// - application/x-www-form-urlencoded
+//
+// produces:
+// - application/json
+//
+// security:
+// - OAuth2 Bearer:
+// - write:user
+//
+// responses:
+// '200':
+// description: Change successful
+// '401':
+// description: unauthorized
+// '403':
+// description: forbidden
+// '400':
+// description: bad request
+// '500':
+// description: "internal error"
+func (m *Module) PasswordChangePOSTHandler(c *gin.Context) {
+ l := logrus.WithField("func", "PasswordChangePOSTHandler")
+
+ authed, err := oauth.Authed(c, true, true, true, true)
+ if err != nil {
+ l.Debugf("error authing: %s", err)
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
+ return
+ }
+
+ // First check this user/account is active.
+ if authed.User.Disabled || !authed.User.Approved || !authed.Account.SuspendedAt.IsZero() {
+ l.Debugf("couldn't auth: %s", err)
+ c.JSON(http.StatusForbidden, gin.H{"error": "account is disabled, not yet approved, or suspended"})
+ return
+ }
+
+ form := &model.PasswordChangeRequest{}
+ if err := c.ShouldBind(form); err != nil || form == nil || form.NewPassword == "" || form.OldPassword == "" {
+ if err != nil {
+ l.Debugf("could not parse form from request: %s", err)
+ }
+ c.JSON(http.StatusBadRequest, gin.H{"error": "missing one or more required form values"})
+ return
+ }
+
+ if errWithCode := m.processor.UserChangePassword(c.Request.Context(), authed, form); errWithCode != nil {
+ l.Debugf("error changing user password: %s", errWithCode.Error())
+ c.JSON(errWithCode.Code(), gin.H{"error": errWithCode.Safe()})
+ return
+ }
+
+ c.Status(http.StatusOK)
+}
diff --git a/internal/api/client/user/passwordchange_test.go b/internal/api/client/user/passwordchange_test.go
new file mode 100644
index 000000000..bdbeb3e42
--- /dev/null
+++ b/internal/api/client/user/passwordchange_test.go
@@ -0,0 +1,157 @@
+/*
+ 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 user_test
+
+import (
+ "context"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/suite"
+ "github.com/superseriousbusiness/gotosocial/internal/api/client/user"
+ "github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
+ "github.com/superseriousbusiness/gotosocial/internal/oauth"
+ "golang.org/x/crypto/bcrypt"
+)
+
+type PasswordChangeTestSuite struct {
+ UserStandardTestSuite
+}
+
+func (suite *PasswordChangeTestSuite) TestPasswordChangePOST() {
+ t := suite.testTokens["local_account_1"]
+ oauthToken := oauth.DBTokenToToken(t)
+
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"])
+ ctx.Set(oauth.SessionAuthorizedToken, oauthToken)
+ ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"])
+ ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"])
+ ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", user.PasswordChangePath), nil)
+ ctx.Request.Form = url.Values{
+ "old_password": {"password"},
+ "new_password": {"peepeepoopoopassword"},
+ }
+ suite.userModule.PasswordChangePOSTHandler(ctx)
+
+ // check response
+ suite.EqualValues(http.StatusOK, recorder.Code)
+
+ dbUser := &gtsmodel.User{}
+ err := suite.db.GetByID(context.Background(), suite.testUsers["local_account_1"].ID, dbUser)
+ suite.NoError(err)
+
+ // new password should pass
+ err = bcrypt.CompareHashAndPassword([]byte(dbUser.EncryptedPassword), []byte("peepeepoopoopassword"))
+ suite.NoError(err)
+
+ // old password should fail
+ err = bcrypt.CompareHashAndPassword([]byte(dbUser.EncryptedPassword), []byte("password"))
+ suite.EqualError(err, "crypto/bcrypt: hashedPassword is not the hash of the given password")
+}
+
+func (suite *PasswordChangeTestSuite) TestPasswordMissingOldPassword() {
+ t := suite.testTokens["local_account_1"]
+ oauthToken := oauth.DBTokenToToken(t)
+
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"])
+ ctx.Set(oauth.SessionAuthorizedToken, oauthToken)
+ ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"])
+ ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"])
+ ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", user.PasswordChangePath), nil)
+ ctx.Request.Form = url.Values{
+ "new_password": {"peepeepoopoopassword"},
+ }
+ suite.userModule.PasswordChangePOSTHandler(ctx)
+
+ // check response
+ suite.EqualValues(http.StatusBadRequest, recorder.Code)
+
+ result := recorder.Result()
+ defer result.Body.Close()
+ b, err := ioutil.ReadAll(result.Body)
+ suite.NoError(err)
+ suite.Equal(`{"error":"missing one or more required form values"}`, string(b))
+}
+
+func (suite *PasswordChangeTestSuite) TestPasswordIncorrectOldPassword() {
+ t := suite.testTokens["local_account_1"]
+ oauthToken := oauth.DBTokenToToken(t)
+
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"])
+ ctx.Set(oauth.SessionAuthorizedToken, oauthToken)
+ ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"])
+ ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"])
+ ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", user.PasswordChangePath), nil)
+ ctx.Request.Form = url.Values{
+ "old_password": {"notright"},
+ "new_password": {"peepeepoopoopassword"},
+ }
+ suite.userModule.PasswordChangePOSTHandler(ctx)
+
+ // check response
+ suite.EqualValues(http.StatusBadRequest, recorder.Code)
+
+ result := recorder.Result()
+ defer result.Body.Close()
+ b, err := ioutil.ReadAll(result.Body)
+ suite.NoError(err)
+ suite.Equal(`{"error":"bad request: old password did not match"}`, string(b))
+}
+
+func (suite *PasswordChangeTestSuite) TestPasswordWeakNewPassword() {
+ t := suite.testTokens["local_account_1"]
+ oauthToken := oauth.DBTokenToToken(t)
+
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"])
+ ctx.Set(oauth.SessionAuthorizedToken, oauthToken)
+ ctx.Set(oauth.SessionAuthorizedUser, suite.testUsers["local_account_1"])
+ ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccounts["local_account_1"])
+ ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", user.PasswordChangePath), nil)
+ ctx.Request.Form = url.Values{
+ "old_password": {"password"},
+ "new_password": {"peepeepoopoo"},
+ }
+ suite.userModule.PasswordChangePOSTHandler(ctx)
+
+ // check response
+ suite.EqualValues(http.StatusBadRequest, recorder.Code)
+
+ result := recorder.Result()
+ defer result.Body.Close()
+ b, err := ioutil.ReadAll(result.Body)
+ suite.NoError(err)
+ suite.Equal(`{"error":"bad request: insecure password, try including more special characters, using uppercase letters, using numbers or using a longer password"}`, string(b))
+}
+
+func TestPasswordChangeTestSuite(t *testing.T) {
+ suite.Run(t, &PasswordChangeTestSuite{})
+}
diff --git a/internal/api/client/user/user.go b/internal/api/client/user/user.go
new file mode 100644
index 000000000..ff28a197f
--- /dev/null
+++ b/internal/api/client/user/user.go
@@ -0,0 +1,55 @@
+/*
+ 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 user
+
+import (
+ "net/http"
+
+ "github.com/superseriousbusiness/gotosocial/internal/api"
+ "github.com/superseriousbusiness/gotosocial/internal/config"
+ "github.com/superseriousbusiness/gotosocial/internal/processing"
+ "github.com/superseriousbusiness/gotosocial/internal/router"
+)
+
+const (
+ // BasePath is the base URI path for this module
+ BasePath = "/api/v1/user"
+ // PasswordChangePath is the path for POSTing a password change request.
+ PasswordChangePath = BasePath + "/password_change"
+)
+
+// Module implements the ClientAPIModule interface
+type Module struct {
+ config *config.Config
+ processor processing.Processor
+}
+
+// New returns a new user module
+func New(config *config.Config, processor processing.Processor) api.ClientModule {
+ return &Module{
+ config: config,
+ processor: processor,
+ }
+}
+
+// Route attaches all routes from this module to the given router
+func (m *Module) Route(r router.Router) error {
+ r.AttachHandler(http.MethodPost, PasswordChangePath, m.PasswordChangePOSTHandler)
+ return nil
+}
diff --git a/internal/api/client/user/user_test.go b/internal/api/client/user/user_test.go
new file mode 100644
index 000000000..02f10b5ae
--- /dev/null
+++ b/internal/api/client/user/user_test.go
@@ -0,0 +1,73 @@
+/*
+ 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 user_test
+
+import (
+ "git.iim.gay/grufwub/go-store/kv"
+ "github.com/stretchr/testify/suite"
+ "github.com/superseriousbusiness/gotosocial/internal/api/client/user"
+ "github.com/superseriousbusiness/gotosocial/internal/config"
+ "github.com/superseriousbusiness/gotosocial/internal/db"
+ "github.com/superseriousbusiness/gotosocial/internal/federation"
+ "github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
+ "github.com/superseriousbusiness/gotosocial/internal/processing"
+ "github.com/superseriousbusiness/gotosocial/internal/typeutils"
+ "github.com/superseriousbusiness/gotosocial/testrig"
+)
+
+type UserStandardTestSuite struct {
+ suite.Suite
+ config *config.Config
+ db db.DB
+ tc typeutils.TypeConverter
+ federator federation.Federator
+ processor processing.Processor
+ storage *kv.KVStore
+
+ testTokens map[string]*gtsmodel.Token
+ testClients map[string]*gtsmodel.Client
+ testApplications map[string]*gtsmodel.Application
+ testUsers map[string]*gtsmodel.User
+ testAccounts map[string]*gtsmodel.Account
+
+ userModule *user.Module
+}
+
+func (suite *UserStandardTestSuite) SetupTest() {
+ suite.testTokens = testrig.NewTestTokens()
+ suite.testClients = testrig.NewTestClients()
+ suite.testApplications = testrig.NewTestApplications()
+ suite.testUsers = testrig.NewTestUsers()
+ suite.testAccounts = testrig.NewTestAccounts()
+ suite.config = testrig.NewTestConfig()
+ suite.db = testrig.NewTestDB()
+ suite.storage = testrig.NewTestStorage()
+ testrig.InitTestLog()
+ suite.tc = testrig.NewTestTypeConverter(suite.db)
+ suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil), suite.db), suite.storage)
+ suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator)
+ suite.userModule = user.New(suite.config, suite.processor).(*user.Module)
+ testrig.StandardDBSetup(suite.db, suite.testAccounts)
+ testrig.StandardStorageSetup(suite.storage, "../../../../testrig/media")
+}
+
+func (suite *UserStandardTestSuite) TearDownTest() {
+ testrig.StandardDBTeardown(suite.db)
+ testrig.StandardStorageTeardown(suite.storage)
+}
diff --git a/internal/api/model/user.go b/internal/api/model/user.go
new file mode 100644
index 000000000..3f639b5c3
--- /dev/null
+++ b/internal/api/model/user.go
@@ -0,0 +1,37 @@
+/*
+ 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 model
+
+// PasswordChangeRequest models user password change parameters.
+//
+// swagger:parameters userPasswordChange
+type PasswordChangeRequest struct {
+ // User's previous password.
+ //
+ // in: formData
+ // required: true
+ OldPassword string `form:"old_password" json:"old_password" xml:"old_password" validation:"required"`
+ // Desired new password.
+ // If the password does not have high enough entropy, it will be rejected.
+ // See https://github.com/wagslane/go-password-validator
+ //
+ // in: formData
+ // required: true
+ NewPassword string `form:"new_password" json:"new_password" xml:"new_password" validation:"required"`
+}