[feature] Admin accounts endpoints; approve/reject sign-ups (#2826)

* update settings panels, add pending overview + approve/deny functions

* add admin accounts get, approve, reject

* send approved/rejected emails

* use signup URL

* docs!

* email

* swagger

* web linting

* fix email tests

* wee lil fixerinos

* use new paging logic for GetAccounts() series of admin endpoints, small changes to query building

* shuffle useAccountIDIn check *before* adding to query

* fix parse from toot react error

* use `netip.Addr`

* put valid slices in globals

* optimistic updates for account state

---------

Co-authored-by: kim <grufwub@gmail.com>
This commit is contained in:
tobi
2024-04-13 13:25:10 +02:00
committed by GitHub
parent 1439042104
commit 89e0cfd874
74 changed files with 4102 additions and 545 deletions

View File

@ -0,0 +1,79 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 admin
import (
"context"
"errors"
"fmt"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/messages"
)
func (p *Processor) AccountApprove(
ctx context.Context,
adminAcct *gtsmodel.Account,
accountID string,
) (*apimodel.AdminAccountInfo, gtserror.WithCode) {
user, err := p.state.DB.GetUserByAccountID(ctx, accountID)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err := gtserror.Newf("db error getting user for account id %s: %w", accountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
if user == nil {
err := fmt.Errorf("user for account %s not found", accountID)
return nil, gtserror.NewErrorNotFound(err, err.Error())
}
// Get a lock on the account URI,
// to ensure it's not also being
// rejected at the same time!
unlock := p.state.ClientLocks.Lock(user.Account.URI)
defer unlock()
if !*user.Approved {
// Process approval side effects asynschronously.
p.state.Workers.EnqueueClientAPI(ctx, messages.FromClientAPI{
APObjectType: ap.ActorPerson,
APActivityType: ap.ActivityAccept,
GTSModel: user,
OriginAccount: adminAcct,
TargetAccount: user.Account,
})
}
apiAccount, err := p.converter.AccountToAdminAPIAccount(ctx, user.Account)
if err != nil {
err := gtserror.Newf("error converting account %s to admin api model: %w", accountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
// Optimistically set approved to true and
// clear sign-up IP to reflect state that
// will be produced by side effects.
apiAccount.Approved = true
apiAccount.IP = nil
return apiAccount, nil
}

View File

@ -0,0 +1,75 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 admin_test
import (
"context"
"testing"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/testrig"
)
type AdminApproveTestSuite struct {
AdminStandardTestSuite
}
func (suite *AdminApproveTestSuite) TestApprove() {
var (
ctx = context.Background()
adminAcct = suite.testAccounts["admin_account"]
targetAcct = suite.testAccounts["unconfirmed_account"]
targetUser = new(gtsmodel.User)
)
// Copy user since we're modifying it.
*targetUser = *suite.testUsers["unconfirmed_account"]
// Approve the sign-up.
acct, errWithCode := suite.adminProcessor.AccountApprove(
ctx,
adminAcct,
targetAcct.ID,
)
if errWithCode != nil {
suite.FailNow(errWithCode.Error())
}
// Account should be approved.
suite.NotNil(acct)
suite.True(acct.Approved)
suite.Nil(acct.IP)
// Wait for processor to
// handle side effects.
var (
dbUser *gtsmodel.User
err error
)
if !testrig.WaitFor(func() bool {
dbUser, err = suite.state.DB.GetUserByID(ctx, targetUser.ID)
return err == nil && dbUser != nil && *dbUser.Approved
}) {
suite.FailNow("waiting for approved user")
}
}
func TestAdminApproveTestSuite(t *testing.T) {
suite.Run(t, new(AdminApproveTestSuite))
}

View File

@ -0,0 +1,49 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 admin
import (
"context"
"errors"
"fmt"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
)
func (p *Processor) AccountGet(ctx context.Context, accountID string) (*apimodel.AdminAccountInfo, gtserror.WithCode) {
account, err := p.state.DB.GetAccountByID(ctx, accountID)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err := gtserror.Newf("db error getting account %s: %w", accountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
if account == nil {
err := fmt.Errorf("account %s not found", accountID)
return nil, gtserror.NewErrorNotFound(err, err.Error())
}
apiAccount, err := p.converter.AccountToAdminAPIAccount(ctx, account)
if err != nil {
err := gtserror.Newf("error converting account %s to admin api model: %w", accountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
return apiAccount, nil
}

View File

@ -0,0 +1,113 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 admin
import (
"context"
"errors"
"fmt"
"github.com/superseriousbusiness/gotosocial/internal/ap"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/internal/messages"
)
func (p *Processor) AccountReject(
ctx context.Context,
adminAcct *gtsmodel.Account,
accountID string,
privateComment string,
sendEmail bool,
message string,
) (*apimodel.AdminAccountInfo, gtserror.WithCode) {
user, err := p.state.DB.GetUserByAccountID(ctx, accountID)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err := gtserror.Newf("db error getting user for account id %s: %w", accountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
if user == nil {
err := fmt.Errorf("user for account %s not found", accountID)
return nil, gtserror.NewErrorNotFound(err, err.Error())
}
// Get a lock on the account URI,
// since we're going to be deleting
// it and its associated user.
unlock := p.state.ClientLocks.Lock(user.Account.URI)
defer unlock()
// Can't reject an account with a
// user that's already been approved.
if *user.Approved {
err := fmt.Errorf("account %s has already been approved", accountID)
return nil, gtserror.NewErrorUnprocessableEntity(err, err.Error())
}
// Convert to API account *before* doing the
// rejection, since the rejection will cause
// the user and account to be removed.
apiAccount, err := p.converter.AccountToAdminAPIAccount(ctx, user.Account)
if err != nil {
err := gtserror.Newf("error converting account %s to admin api model: %w", accountID, err)
return nil, gtserror.NewErrorInternalError(err)
}
// Set approved to false on the API model, to
// reflect the changes that will occur
// asynchronously in the processor.
apiAccount.Approved = false
// Ensure we an email address.
var email string
if user.Email != "" {
email = user.Email
} else {
email = user.UnconfirmedEmail
}
// Create a denied user entry for
// the worker to process + store.
deniedUser := &gtsmodel.DeniedUser{
ID: user.ID,
Email: email,
Username: user.Account.Username,
SignUpIP: user.SignUpIP,
InviteID: user.InviteID,
Locale: user.Locale,
CreatedByApplicationID: user.CreatedByApplicationID,
SignUpReason: user.Reason,
PrivateComment: privateComment,
SendEmail: &sendEmail,
Message: message,
}
// Process rejection side effects asynschronously.
p.state.Workers.EnqueueClientAPI(ctx, messages.FromClientAPI{
APObjectType: ap.ActorPerson,
APActivityType: ap.ActivityReject,
GTSModel: deniedUser,
OriginAccount: adminAcct,
TargetAccount: user.Account,
})
return apiAccount, nil
}

View File

@ -0,0 +1,142 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 admin_test
import (
"context"
"testing"
"github.com/stretchr/testify/suite"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
"github.com/superseriousbusiness/gotosocial/testrig"
)
type AdminRejectTestSuite struct {
AdminStandardTestSuite
}
func (suite *AdminRejectTestSuite) TestReject() {
var (
ctx = context.Background()
adminAcct = suite.testAccounts["admin_account"]
targetAcct = suite.testAccounts["unconfirmed_account"]
targetUser = suite.testUsers["unconfirmed_account"]
privateComment = "It's a no from me chief."
sendEmail = true
message = "Too stinky."
)
acct, errWithCode := suite.adminProcessor.AccountReject(
ctx,
adminAcct,
targetAcct.ID,
privateComment,
sendEmail,
message,
)
if errWithCode != nil {
suite.FailNow(errWithCode.Error())
}
suite.NotNil(acct)
suite.False(acct.Approved)
// Wait for processor to
// handle side effects.
var (
deniedUser *gtsmodel.DeniedUser
err error
)
if !testrig.WaitFor(func() bool {
deniedUser, err = suite.state.DB.GetDeniedUserByID(ctx, targetUser.ID)
return deniedUser != nil && err == nil
}) {
suite.FailNow("waiting for denied user")
}
// Ensure fields as expected.
suite.Equal(targetUser.ID, deniedUser.ID)
suite.Equal(targetUser.UnconfirmedEmail, deniedUser.Email)
suite.Equal(targetAcct.Username, deniedUser.Username)
suite.Equal(targetUser.SignUpIP, deniedUser.SignUpIP)
suite.Equal(targetUser.InviteID, deniedUser.InviteID)
suite.Equal(targetUser.Locale, deniedUser.Locale)
suite.Equal(targetUser.CreatedByApplicationID, deniedUser.CreatedByApplicationID)
suite.Equal(targetUser.Reason, deniedUser.SignUpReason)
suite.Equal(privateComment, deniedUser.PrivateComment)
suite.Equal(sendEmail, *deniedUser.SendEmail)
suite.Equal(message, deniedUser.Message)
// Should be no user entry for
// this denied request now.
_, err = suite.state.DB.GetUserByID(ctx, targetUser.ID)
suite.ErrorIs(db.ErrNoEntries, err)
// Should be no account entry for
// this denied request now.
_, err = suite.state.DB.GetAccountByID(ctx, targetAcct.ID)
suite.ErrorIs(db.ErrNoEntries, err)
}
func (suite *AdminRejectTestSuite) TestRejectRemote() {
var (
ctx = context.Background()
adminAcct = suite.testAccounts["admin_account"]
targetAcct = suite.testAccounts["remote_account_1"]
privateComment = "It's a no from me chief."
sendEmail = true
message = "Too stinky."
)
// Try to reject a remote account.
_, err := suite.adminProcessor.AccountReject(
ctx,
adminAcct,
targetAcct.ID,
privateComment,
sendEmail,
message,
)
suite.EqualError(err, "user for account 01F8MH5ZK5VRH73AKHQM6Y9VNX not found")
}
func (suite *AdminRejectTestSuite) TestRejectApproved() {
var (
ctx = context.Background()
adminAcct = suite.testAccounts["admin_account"]
targetAcct = suite.testAccounts["local_account_1"]
privateComment = "It's a no from me chief."
sendEmail = true
message = "Too stinky."
)
// Try to reject an already-approved account.
_, err := suite.adminProcessor.AccountReject(
ctx,
adminAcct,
targetAcct.ID,
privateComment,
sendEmail,
message,
)
suite.EqualError(err, "account 01F8MH1H7YV1Z7D2C8K2730QBF has already been approved")
}
func TestAdminRejectTestSuite(t *testing.T) {
suite.Run(t, new(AdminRejectTestSuite))
}

View File

@ -0,0 +1,272 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 admin
import (
"context"
"errors"
"fmt"
"net/netip"
"net/url"
"slices"
apimodel "github.com/superseriousbusiness/gotosocial/internal/api/model"
apiutil "github.com/superseriousbusiness/gotosocial/internal/api/util"
"github.com/superseriousbusiness/gotosocial/internal/db"
"github.com/superseriousbusiness/gotosocial/internal/gtserror"
"github.com/superseriousbusiness/gotosocial/internal/log"
"github.com/superseriousbusiness/gotosocial/internal/paging"
)
var (
accountsValidOrigins = []string{"local", "remote"}
accountsValidStatuses = []string{"active", "pending", "disabled", "silenced", "suspended"}
accountsValidPermissions = []string{"staff"}
)
func (p *Processor) AccountsGet(
ctx context.Context,
request *apimodel.AdminGetAccountsRequest,
page *paging.Page,
) (
*apimodel.PageableResponse,
gtserror.WithCode,
) {
// Validate "origin".
if v := request.Origin; v != "" {
if !slices.Contains(accountsValidOrigins, v) {
err := fmt.Errorf(
"origin %s not recognized; valid choices are %+v",
v, accountsValidOrigins,
)
return nil, gtserror.NewErrorBadRequest(err, err.Error())
}
}
// Validate "status".
if v := request.Status; v != "" {
if !slices.Contains(accountsValidStatuses, v) {
err := fmt.Errorf(
"status %s not recognized; valid choices are %+v",
v, accountsValidStatuses,
)
return nil, gtserror.NewErrorBadRequest(err, err.Error())
}
}
// Validate "permissions".
if v := request.Permissions; v != "" {
if !slices.Contains(accountsValidPermissions, v) {
err := fmt.Errorf(
"permissions %s not recognized; valid choices are %+v",
v, accountsValidPermissions,
)
return nil, gtserror.NewErrorBadRequest(err, err.Error())
}
}
// Validate/parse IP.
var ip netip.Addr
if v := request.IP; v != "" {
var err error
ip, err = netip.ParseAddr(request.IP)
if err != nil {
err := fmt.Errorf("invalid ip provided: %w", err)
return nil, gtserror.NewErrorBadRequest(err, err.Error())
}
}
// Get accounts with the given params.
accounts, err := p.state.DB.GetAccounts(
ctx,
request.Origin,
request.Status,
func() bool { return request.Permissions == "staff" }(),
request.InvitedBy,
request.Username,
request.DisplayName,
request.ByDomain,
request.Email,
ip,
page,
)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
err = gtserror.Newf("db error getting accounts: %w", err)
return nil, gtserror.NewErrorInternalError(err)
}
count := len(accounts)
if count == 0 {
return paging.EmptyResponse(), nil
}
hi := accounts[count-1].ID
lo := accounts[0].ID
items := make([]interface{}, 0, count)
for _, account := range accounts {
apiAccount, err := p.converter.AccountToAdminAPIAccount(ctx, account)
if err != nil {
log.Errorf(ctx, "error converting to api account: %v", err)
continue
}
items = append(items, apiAccount)
}
// Return packaging + paging appropriate for
// the API version used to call this function.
switch request.APIVersion {
case 1:
return packageAccountsV1(items, lo, hi, request, page)
case 2:
return packageAccountsV2(items, lo, hi, request, page)
default:
log.Panic(ctx, "api version was neither 1 nor 2")
return nil, nil
}
}
func packageAccountsV1(
items []interface{},
loID, hiID string,
request *apimodel.AdminGetAccountsRequest,
page *paging.Page,
) (*apimodel.PageableResponse, gtserror.WithCode) {
queryParams := make(url.Values, 8)
// Translate origin to v1.
if v := request.Origin; v != "" {
var k string
if v == "local" {
k = apiutil.LocalKey
} else {
k = apiutil.AdminRemoteKey
}
queryParams.Add(k, "true")
}
// Translate status to v1.
if v := request.Status; v != "" {
var k string
switch v {
case "active":
k = apiutil.AdminActiveKey
case "pending":
k = apiutil.AdminPendingKey
case "disabled":
k = apiutil.AdminDisabledKey
case "silenced":
k = apiutil.AdminSilencedKey
case "suspended":
k = apiutil.AdminSuspendedKey
}
queryParams.Add(k, "true")
}
if v := request.Username; v != "" {
queryParams.Add(apiutil.UsernameKey, v)
}
if v := request.DisplayName; v != "" {
queryParams.Add(apiutil.AdminDisplayNameKey, v)
}
if v := request.ByDomain; v != "" {
queryParams.Add(apiutil.AdminByDomainKey, v)
}
if v := request.Email; v != "" {
queryParams.Add(apiutil.AdminEmailKey, v)
}
if v := request.IP; v != "" {
queryParams.Add(apiutil.AdminIPKey, v)
}
// Translate permissions to v1.
if v := request.Permissions; v != "" {
queryParams.Add(apiutil.AdminStaffKey, v)
}
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v1/admin/accounts",
Next: page.Next(loID, hiID),
Prev: page.Prev(loID, hiID),
Query: queryParams,
}), nil
}
func packageAccountsV2(
items []interface{},
loID, hiID string,
request *apimodel.AdminGetAccountsRequest,
page *paging.Page,
) (*apimodel.PageableResponse, gtserror.WithCode) {
queryParams := make(url.Values, 9)
if v := request.Origin; v != "" {
queryParams.Add(apiutil.AdminOriginKey, v)
}
if v := request.Status; v != "" {
queryParams.Add(apiutil.AdminStatusKey, v)
}
if v := request.Permissions; v != "" {
queryParams.Add(apiutil.AdminPermissionsKey, v)
}
if v := request.InvitedBy; v != "" {
queryParams.Add(apiutil.AdminInvitedByKey, v)
}
if v := request.Username; v != "" {
queryParams.Add(apiutil.UsernameKey, v)
}
if v := request.DisplayName; v != "" {
queryParams.Add(apiutil.AdminDisplayNameKey, v)
}
if v := request.ByDomain; v != "" {
queryParams.Add(apiutil.AdminByDomainKey, v)
}
if v := request.Email; v != "" {
queryParams.Add(apiutil.AdminEmailKey, v)
}
if v := request.IP; v != "" {
queryParams.Add(apiutil.AdminIPKey, v)
}
return paging.PackageResponse(paging.ResponseParams{
Items: items,
Path: "/api/v2/admin/accounts",
Next: page.Next(loID, hiID),
Prev: page.Prev(loID, hiID),
Query: queryParams,
}), nil
}

View File

@ -33,6 +33,7 @@ import (
"github.com/superseriousbusiness/gotosocial/internal/processing/account"
"github.com/superseriousbusiness/gotosocial/internal/state"
"github.com/superseriousbusiness/gotosocial/internal/typeutils"
"github.com/superseriousbusiness/gotosocial/internal/util"
)
// clientAPI wraps processing functions
@ -141,6 +142,10 @@ func (p *Processor) ProcessFromClientAPI(ctx context.Context, cMsg messages.From
// ACCEPT FOLLOW (request)
case ap.ActivityFollow:
return p.clientAPI.AcceptFollow(ctx, cMsg)
// ACCEPT PROFILE/ACCOUNT (sign-up)
case ap.ObjectProfile, ap.ActorPerson:
return p.clientAPI.AcceptAccount(ctx, cMsg)
}
// REJECT SOMETHING
@ -150,6 +155,10 @@ func (p *Processor) ProcessFromClientAPI(ctx context.Context, cMsg messages.From
// REJECT FOLLOW (request)
case ap.ActivityFollow:
return p.clientAPI.RejectFollowRequest(ctx, cMsg)
// REJECT PROFILE/ACCOUNT (sign-up)
case ap.ObjectProfile, ap.ActorPerson:
return p.clientAPI.RejectAccount(ctx, cMsg)
}
// UNDO SOMETHING
@ -685,3 +694,66 @@ func (p *clientAPI) MoveAccount(ctx context.Context, cMsg messages.FromClientAPI
return nil
}
func (p *clientAPI) AcceptAccount(ctx context.Context, cMsg messages.FromClientAPI) error {
newUser, ok := cMsg.GTSModel.(*gtsmodel.User)
if !ok {
return gtserror.Newf("%T not parseable as *gtsmodel.User", cMsg.GTSModel)
}
// Mark user as approved + clear sign-up IP.
newUser.Approved = util.Ptr(true)
newUser.SignUpIP = nil
if err := p.state.DB.UpdateUser(ctx, newUser, "approved", "sign_up_ip"); err != nil {
// Error now means we should return without
// sending email + let admin try to approve again.
return gtserror.Newf("db error updating user %s: %w", newUser.ID, err)
}
// Send "your sign-up has been approved" email to the new user.
if err := p.surface.emailUserSignupApproved(ctx, newUser); err != nil {
log.Errorf(ctx, "error emailing: %v", err)
}
return nil
}
func (p *clientAPI) RejectAccount(ctx context.Context, cMsg messages.FromClientAPI) error {
deniedUser, ok := cMsg.GTSModel.(*gtsmodel.DeniedUser)
if !ok {
return gtserror.Newf("%T not parseable as *gtsmodel.DeniedUser", cMsg.GTSModel)
}
// Remove the account.
if err := p.state.DB.DeleteAccount(ctx, cMsg.TargetAccount.ID); err != nil {
log.Errorf(ctx,
"db error deleting account %s: %v",
cMsg.TargetAccount.ID, err,
)
}
// Remove the user.
if err := p.state.DB.DeleteUserByID(ctx, deniedUser.ID); err != nil {
log.Errorf(ctx,
"db error deleting user %s: %v",
deniedUser.ID, err,
)
}
// Store the deniedUser entry.
if err := p.state.DB.PutDeniedUser(ctx, deniedUser); err != nil {
log.Errorf(ctx,
"db error putting denied user %s: %v",
deniedUser.ID, err,
)
}
if *deniedUser.SendEmail {
// Send "your sign-up has been rejected" email to the denied user.
if err := p.surface.emailUserSignupRejected(ctx, deniedUser); err != nil {
log.Errorf(ctx, "error emailing: %v", err)
}
}
return nil
}

View File

@ -129,6 +129,69 @@ func (s *surface) emailUserPleaseConfirm(ctx context.Context, user *gtsmodel.Use
return nil
}
// emailUserSignupApproved emails the given user
// to inform them their sign-up has been approved.
func (s *surface) emailUserSignupApproved(ctx context.Context, user *gtsmodel.User) error {
// User may have been approved without
// their email address being confirmed
// yet. Just send to whatever we have.
emailAddr := user.Email
if emailAddr == "" {
emailAddr = user.UnconfirmedEmail
}
instance, err := s.state.DB.GetInstance(ctx, config.GetHost())
if err != nil {
return gtserror.Newf("db error getting instance: %w", err)
}
// Assemble email contents and send the email.
if err := s.emailSender.SendSignupApprovedEmail(
emailAddr,
email.SignupApprovedData{
Username: user.Account.Username,
InstanceURL: instance.URI,
InstanceName: instance.Title,
},
); err != nil {
return err
}
// Email sent, update the user
// entry with the emailed time.
now := time.Now()
user.LastEmailedAt = now
if err := s.state.DB.UpdateUser(
ctx,
user,
"last_emailed_at",
); err != nil {
return gtserror.Newf("error updating user entry after email sent: %w", err)
}
return nil
}
// emailUserSignupApproved emails the given user
// to inform them their sign-up has been approved.
func (s *surface) emailUserSignupRejected(ctx context.Context, deniedUser *gtsmodel.DeniedUser) error {
instance, err := s.state.DB.GetInstance(ctx, config.GetHost())
if err != nil {
return gtserror.Newf("db error getting instance: %w", err)
}
// Assemble email contents and send the email.
return s.emailSender.SendSignupRejectedEmail(
deniedUser.Email,
email.SignupRejectedData{
Message: deniedUser.Message,
InstanceURL: instance.URI,
InstanceName: instance.Title,
},
)
}
// emailAdminReportOpened emails all active moderators/admins
// of this instance that a new report has been created.
func (s *surface) emailAdminReportOpened(ctx context.Context, report *gtsmodel.Report) error {
@ -193,7 +256,7 @@ func (s *surface) emailAdminNewSignup(ctx context.Context, newUser *gtsmodel.Use
SignupEmail: newUser.UnconfirmedEmail,
SignupUsername: newUser.Account.Username,
SignupReason: newUser.Reason,
SignupURL: "TODO",
SignupURL: instance.URI + "/settings/admin/accounts/" + newUser.AccountID,
}
if err := s.emailSender.SendNewSignupEmail(toAddresses, newSignupData); err != nil {