user service: initial implementation (#17668)

* conceptual user service: initial commit

* reflect review comments

* fix i18n issues and some tests

* implement get user methods

* add license

* reflect review comments
Этот коммит содержится в:
Ibrahim Serdar Acikgoz
2021-06-01 14:52:55 +03:00
коммит произвёл GitHub
родитель d320b50abb
Коммит ac3bb2e811
21 изменённых файлов: 777 добавлений и 239 удалений

12
services/users/constants.go Обычный файл
Просмотреть файл

@@ -0,0 +1,12 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
const (
TokenTypePasswordRecovery = "password_recovery"
TokenTypeVerifyEmail = "verify_email"
TokenTypeTeamInvitation = "team_invitation"
TokenTypeGuestInvitation = "guest_invitation"
InvitationExpiryTime = 1000 * 60 * 60 * 48 // 48 hours
)

31
services/users/errors.go Обычный файл
Просмотреть файл

@@ -0,0 +1,31 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import "errors"
var (
AcceptedDomainError = errors.New("the email provided does not belong to an accepted domain")
VerifyUserError = errors.New("could not update verify email field")
UserCountError = errors.New("could not get the total number of the users.")
)
// ErrInvalidPassword indicates an error against the password settings
type ErrInvalidPassword struct {
id string
}
func NewErrInvalidPassword(id string) *ErrInvalidPassword {
return &ErrInvalidPassword{
id: id,
}
}
func (e *ErrInvalidPassword) Error() string {
return "invalid password"
}
func (e *ErrInvalidPassword) Id() string {
return e.id
}

142
services/users/helper_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,142 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"sync"
"testing"
"github.com/mattermost/mattermost-server/v5/app/request"
"github.com/mattermost/mattermost-server/v5/config"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/store"
)
var initBasicOnce sync.Once
type TestHelper struct {
service *UserService
configStore *config.Store
dbStore store.Store
workspace string
Context *request.Context
BasicUser *model.User
BasicUser2 *model.User
SystemAdminUser *model.User
LogBuffer *bytes.Buffer
}
func Setup(tb testing.TB) *TestHelper {
if testing.Short() {
tb.SkipNow()
}
dbStore := mainHelper.GetStore()
dbStore.DropAllTables()
dbStore.MarkSystemRanUnitTests()
mainHelper.PreloadMigrations()
return setupTestHelper(dbStore, false, tb)
}
func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *TestHelper {
tempWorkspace, err := ioutil.TempDir("", "userservicetest")
if err != nil {
panic(err)
}
configStore := config.NewTestMemoryStore()
config := configStore.Get()
*config.PluginSettings.Directory = filepath.Join(tempWorkspace, "plugins")
*config.PluginSettings.ClientDirectory = filepath.Join(tempWorkspace, "webapp")
*config.PluginSettings.AutomaticPrepackagedPlugins = false
*config.LogSettings.EnableSentry = false // disable error reporting during tests
*config.AnnouncementSettings.AdminNoticesEnabled = false
*config.AnnouncementSettings.UserNoticesEnabled = false
*config.TeamSettings.MaxUsersPerTeam = 50
*config.RateLimitSettings.Enable = false
*config.TeamSettings.EnableOpenServer = true
// Disable strict password requirements for test
*config.PasswordSettings.MinimumLength = 5
*config.PasswordSettings.Lowercase = false
*config.PasswordSettings.Uppercase = false
*config.PasswordSettings.Symbol = false
*config.PasswordSettings.Number = false
configStore.Set(config)
buffer := &bytes.Buffer{}
return &TestHelper{
service: &UserService{store: s.User(), config: configStore.Get},
Context: &request.Context{},
configStore: configStore,
dbStore: s,
LogBuffer: buffer,
workspace: tempWorkspace,
}
}
func (th *TestHelper) InitBasic() *TestHelper {
// create users once and cache them because password hashing is slow
initBasicOnce.Do(func() {
th.SystemAdminUser = th.CreateUser()
th.SystemAdminUser, _ = th.service.GetUser(th.SystemAdminUser.Id)
th.BasicUser = th.CreateUser()
th.BasicUser, _ = th.service.GetUser(th.BasicUser.Id)
th.BasicUser2 = th.CreateUser()
th.BasicUser2, _ = th.service.GetUser(th.BasicUser2.Id)
})
return th
}
func (th *TestHelper) CreateUser() *model.User {
return th.CreateUserOrGuest(false)
}
func (th *TestHelper) CreateGuest() *model.User {
return th.CreateUserOrGuest(true)
}
func (th *TestHelper) CreateUserOrGuest(guest bool) *model.User {
id := model.NewId()
user := &model.User{
Email: "success+" + id + "@simulator.amazonses.com",
Username: "un_" + id,
Nickname: "nn_" + id,
Password: "Password1",
EmailVerified: true,
}
var err error
if guest {
if user, err = th.service.CreateUser(user, UserCreateOptions{Guest: true}); err != nil {
panic(err)
}
} else {
if user, err = th.service.CreateUser(user, UserCreateOptions{}); err != nil {
panic(err)
}
}
return user
}
func (th *TestHelper) TearDown() {
th.configStore.Close()
th.dbStore.Close()
if th.workspace != "" {
os.RemoveAll(th.workspace)
}
}

35
services/users/main_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,35 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"flag"
"testing"
"github.com/mattermost/mattermost-server/v5/shared/mlog"
"github.com/mattermost/mattermost-server/v5/testlib"
)
var mainHelper *testlib.MainHelper
var replicaFlag bool
func TestMain(m *testing.M) {
if f := flag.Lookup("mysql-replica"); f == nil {
flag.BoolVar(&replicaFlag, "mysql-replica", false, "")
flag.Parse()
}
var options = testlib.HelperOptions{
EnableStore: true,
EnableResources: true,
WithReadReplica: replicaFlag,
}
mlog.DisableZap()
mainHelper = testlib.NewMainHelperWithOptions(&options)
defer mainHelper.Close()
mainHelper.Main(m)
}

96
services/users/password.go Обычный файл
Просмотреть файл

@@ -0,0 +1,96 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"errors"
"strings"
"github.com/mattermost/mattermost-server/v5/model"
"golang.org/x/crypto/bcrypt"
)
func CheckUserPassword(user *model.User, password string) error {
if err := ComparePassword(user.Password, password); err != nil {
return NewErrInvalidPassword("")
}
return nil
}
// HashPassword generates a hash using the bcrypt.GenerateFromPassword
func HashPassword(password string) string {
hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
panic(err)
}
return string(hash)
}
func ComparePassword(hash string, password string) error {
if password == "" || hash == "" {
return errors.New("empty password or hash")
}
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
func (us *UserService) isPasswordValid(password string) error {
if *us.config().ServiceSettings.EnableDeveloper {
return nil
}
return IsPasswordValidWithSettings(password, &us.config().PasswordSettings)
}
// IsPasswordValidWithSettings is a utility functions that checks if the given password
// comforms to the password settings. It returns the error id as error value.
func IsPasswordValidWithSettings(password string, settings *model.PasswordSettings) error {
id := "model.user.is_valid.pwd"
isError := false
if len(password) < *settings.MinimumLength || len(password) > model.PASSWORD_MAXIMUM_LENGTH {
isError = true
}
if *settings.Lowercase {
if !strings.ContainsAny(password, model.LOWERCASE_LETTERS) {
isError = true
}
id = id + "_lowercase"
}
if *settings.Uppercase {
if !strings.ContainsAny(password, model.UPPERCASE_LETTERS) {
isError = true
}
id = id + "_uppercase"
}
if *settings.Number {
if !strings.ContainsAny(password, model.NUMBERS) {
isError = true
}
id = id + "_number"
}
if *settings.Symbol {
if !strings.ContainsAny(password, model.SYMBOLS) {
isError = true
}
id = id + "_symbol"
}
if isError {
return NewErrInvalidPassword(id + ".app_error")
}
return nil
}

140
services/users/password_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,140 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v5/model"
)
func TestComparePassword(t *testing.T) {
hash := HashPassword("Test")
assert.NoError(t, ComparePassword(hash, "Test"), "Passwords don't match")
assert.Error(t, ComparePassword(hash, "Test2"), "Passwords should not have matched")
}
func TestIsPasswordValidWithSettings(t *testing.T) {
for name, tc := range map[string]struct {
Password string
Settings *model.PasswordSettings
ExpectedError string
}{
"Short": {
Password: strings.Repeat("x", 3),
Settings: &model.PasswordSettings{
MinimumLength: model.NewInt(3),
Lowercase: model.NewBool(false),
Uppercase: model.NewBool(false),
Number: model.NewBool(false),
Symbol: model.NewBool(false),
},
},
"Long": {
Password: strings.Repeat("x", model.PASSWORD_MAXIMUM_LENGTH),
Settings: &model.PasswordSettings{
Lowercase: model.NewBool(false),
Uppercase: model.NewBool(false),
Number: model.NewBool(false),
Symbol: model.NewBool(false),
},
},
"TooShort": {
Password: strings.Repeat("x", 2),
Settings: &model.PasswordSettings{
MinimumLength: model.NewInt(3),
Lowercase: model.NewBool(false),
Uppercase: model.NewBool(false),
Number: model.NewBool(false),
Symbol: model.NewBool(false),
},
ExpectedError: "model.user.is_valid.pwd.app_error",
},
"TooLong": {
Password: strings.Repeat("x", model.PASSWORD_MAXIMUM_LENGTH+1),
Settings: &model.PasswordSettings{
Lowercase: model.NewBool(false),
Uppercase: model.NewBool(false),
Number: model.NewBool(false),
Symbol: model.NewBool(false),
},
ExpectedError: "model.user.is_valid.pwd.app_error",
},
"MissingLower": {
Password: "AAAAAAAAAAASD123!@#",
Settings: &model.PasswordSettings{
Lowercase: model.NewBool(true),
Uppercase: model.NewBool(false),
Number: model.NewBool(false),
Symbol: model.NewBool(false),
},
ExpectedError: "model.user.is_valid.pwd_lowercase.app_error",
},
"MissingUpper": {
Password: "aaaaaaaaaaaaasd123!@#",
Settings: &model.PasswordSettings{
Uppercase: model.NewBool(true),
Lowercase: model.NewBool(false),
Number: model.NewBool(false),
Symbol: model.NewBool(false),
},
ExpectedError: "model.user.is_valid.pwd_uppercase.app_error",
},
"MissingNumber": {
Password: "asasdasdsadASD!@#",
Settings: &model.PasswordSettings{
Number: model.NewBool(true),
Lowercase: model.NewBool(false),
Uppercase: model.NewBool(false),
Symbol: model.NewBool(false),
},
ExpectedError: "model.user.is_valid.pwd_number.app_error",
},
"MissingSymbol": {
Password: "asdasdasdasdasdASD123",
Settings: &model.PasswordSettings{
Symbol: model.NewBool(true),
Lowercase: model.NewBool(false),
Uppercase: model.NewBool(false),
Number: model.NewBool(false),
},
ExpectedError: "model.user.is_valid.pwd_symbol.app_error",
},
"MissingMultiple": {
Password: "asdasdasdasdasdasd",
Settings: &model.PasswordSettings{
Lowercase: model.NewBool(true),
Uppercase: model.NewBool(true),
Number: model.NewBool(true),
Symbol: model.NewBool(true),
},
ExpectedError: "model.user.is_valid.pwd_lowercase_uppercase_number_symbol.app_error",
},
"Everything": {
Password: "asdASD!@#123",
Settings: &model.PasswordSettings{
Lowercase: model.NewBool(true),
Uppercase: model.NewBool(true),
Number: model.NewBool(true),
Symbol: model.NewBool(true),
},
},
} {
tc.Settings.SetDefaults()
t.Run(name, func(t *testing.T) {
if err := IsPasswordValidWithSettings(tc.Password, tc.Settings); tc.ExpectedError == "" {
assert.NoError(t, err)
} else {
invErr, ok := err.(*ErrInvalidPassword)
require.True(t, ok)
assert.Equal(t, tc.ExpectedError, invErr.Id())
}
})
}
}

197
services/users/users.go Обычный файл
Просмотреть файл

@@ -0,0 +1,197 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"context"
"fmt"
"github.com/mattermost/mattermost-server/v5/model"
"github.com/mattermost/mattermost-server/v5/shared/i18n"
"github.com/mattermost/mattermost-server/v5/shared/mlog"
"github.com/mattermost/mattermost-server/v5/store"
)
type UserService struct {
store store.UserStore
config func() *model.Config
}
type UserCreateOptions struct {
Guest bool
FromImport bool
}
func New(s store.UserStore, cfgFn func() *model.Config) *UserService {
return &UserService{
store: s,
config: cfgFn,
}
}
// CreateUser creates a user
func (us *UserService) CreateUser(user *model.User, opts UserCreateOptions) (*model.User, error) {
user.Roles = model.SYSTEM_USER_ROLE_ID
if opts.Guest {
user.Roles = model.SYSTEM_GUEST_ROLE_ID
}
if !user.IsLDAPUser() && !user.IsSAMLUser() && !user.IsGuest() && !checkUserDomain(user, *us.config().TeamSettings.RestrictCreationToDomains) {
return nil, AcceptedDomainError
}
if !user.IsLDAPUser() && !user.IsSAMLUser() && user.IsGuest() && !checkUserDomain(user, *us.config().GuestAccountsSettings.RestrictCreationToDomains) {
return nil, AcceptedDomainError
}
// Below is a special case where the first user in the entire
// system is granted the system_admin role
count, err := us.store.Count(model.UserCountOptions{IncludeDeleted: true})
if err != nil {
return nil, UserCountError
}
if count <= 0 && !opts.FromImport {
user.Roles = model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID
}
if _, ok := i18n.GetSupportedLocales()[user.Locale]; !ok {
user.Locale = *us.config().LocalizationSettings.DefaultClientLocale
}
ruser, err := us.createUser(user)
if err != nil {
return nil, err
}
return ruser, nil
}
func (us *UserService) createUser(user *model.User) (*model.User, error) {
user.MakeNonNil()
if err := us.isPasswordValid(user.Password); user.AuthService == "" && err != nil {
return nil, err
}
ruser, err := us.store.Save(user)
if err != nil {
return nil, err
}
if user.EmailVerified {
if err := us.verifyUserEmail(ruser.Id, user.Email); err != nil {
mlog.Warn("Failed to set email verified", mlog.Err(err))
}
}
// Determine whether to send the created user a welcome email
ruser.DisableWelcomeEmail = user.DisableWelcomeEmail
ruser.Sanitize(map[string]bool{})
return ruser, nil
}
func (us *UserService) verifyUserEmail(userID, email string) error {
if _, err := us.store.VerifyEmail(userID, email); err != nil {
return VerifyUserError
}
return nil
}
func (us *UserService) GetUser(userID string) (*model.User, error) {
return us.store.Get(context.Background(), userID)
}
func (us *UserService) GetUserByUsername(username string) (*model.User, error) {
return us.store.GetByUsername(username)
}
func (us *UserService) GetUserByEmail(email string) (*model.User, error) {
return us.store.GetByEmail(email)
}
func (us *UserService) GetUserByAuth(authData *string, authService string) (*model.User, error) {
return us.store.GetByAuth(authData, authService)
}
func (us *UserService) GetUsers(options *model.UserGetOptions) ([]*model.User, error) {
return us.store.GetAllProfiles(options)
}
func (us *UserService) GetUsersPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, error) {
users, err := us.GetUsers(options)
if err != nil {
return nil, err
}
return us.sanitizeProfiles(users, asAdmin), nil
}
func (us *UserService) GetUsersEtag(restrictionsHash string) string {
return fmt.Sprintf("%v.%v.%v.%v", us.store.GetEtagForAllProfiles(), us.config().PrivacySettings.ShowFullName, us.config().PrivacySettings.ShowEmailAddress, restrictionsHash)
}
func (us *UserService) GetUsersByIds(userIDs []string, options *store.UserGetByIdsOpts) ([]*model.User, error) {
allowFromCache := options.ViewRestrictions == nil
users, err := us.store.GetProfileByIds(context.Background(), userIDs, options, allowFromCache)
if err != nil {
return nil, err
}
return us.sanitizeProfiles(users, options.IsAdmin), nil
}
func (us *UserService) GetUsersInTeam(options *model.UserGetOptions) ([]*model.User, error) {
return us.store.GetProfiles(options)
}
func (us *UserService) GetUsersNotInTeam(teamID string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, error) {
return us.store.GetProfilesNotInTeam(teamID, groupConstrained, offset, limit, viewRestrictions)
}
func (us *UserService) GetUsersInTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, error) {
users, err := us.GetUsersInTeam(options)
if err != nil {
return nil, err
}
return us.sanitizeProfiles(users, asAdmin), nil
}
func (us *UserService) GetUsersNotInTeamPage(teamID string, groupConstrained bool, page int, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, error) {
users, err := us.GetUsersNotInTeam(teamID, groupConstrained, page*perPage, perPage, viewRestrictions)
if err != nil {
return nil, err
}
return us.sanitizeProfiles(users, asAdmin), nil
}
func (us *UserService) GetUsersInTeamEtag(teamID string, restrictionsHash string) string {
return fmt.Sprintf("%v.%v.%v.%v", us.store.GetEtagForProfiles(teamID), us.config().PrivacySettings.ShowFullName, us.config().PrivacySettings.ShowEmailAddress, restrictionsHash)
}
func (us *UserService) GetUsersNotInTeamEtag(teamID string, restrictionsHash string) string {
return fmt.Sprintf("%v.%v.%v.%v", us.store.GetEtagForProfilesNotInTeam(teamID), us.config().PrivacySettings.ShowFullName, us.config().PrivacySettings.ShowEmailAddress, restrictionsHash)
}
func (us *UserService) GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, error) {
users, err := us.GetUsersWithoutTeam(options)
if err != nil {
return nil, err
}
return us.sanitizeProfiles(users, asAdmin), nil
}
func (us *UserService) GetUsersWithoutTeam(options *model.UserGetOptions) ([]*model.User, error) {
users, err := us.store.GetProfilesWithoutTeam(options)
if err != nil {
return nil, err
}
return users, nil
}

29
services/users/users_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,29 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"testing"
)
func TestIsUsernameTaken(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
user := th.BasicUser
taken := th.service.IsUsernameTaken(user.Username)
if !taken {
t.Logf("the username '%v' should be taken", user.Username)
t.FailNow()
}
newUsername := "randomUsername"
taken = th.service.IsUsernameTaken(newUsername)
if taken {
t.Logf("the username '%v' should not be taken", newUsername)
t.FailNow()
}
}

69
services/users/utils.go Обычный файл
Просмотреть файл

@@ -0,0 +1,69 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package users
import (
"strings"
"github.com/mattermost/mattermost-server/v5/model"
)
// checkUserDomain checks that a user's email domain matches a list of space-delimited domains as a string.
func checkUserDomain(user *model.User, domains string) bool {
return checkEmailDomain(user.Email, domains)
}
// checkEmailDomain checks that an email domain matches a list of space-delimited domains as a string.
func checkEmailDomain(email string, domains string) bool {
if domains == "" {
return true
}
domainArray := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(domains, "@", " ", -1), ",", " ", -1))))
for _, d := range domainArray {
if strings.HasSuffix(strings.ToLower(email), "@"+d) {
return true
}
}
return false
}
func (us *UserService) sanitizeProfiles(users []*model.User, asAdmin bool) []*model.User {
for _, u := range users {
us.SanitizeProfile(u, asAdmin)
}
return users
}
func (us *UserService) SanitizeProfile(user *model.User, asAdmin bool) {
options := us.GetSanitizeOptions(asAdmin)
user.SanitizeProfile(options)
}
func (us *UserService) GetSanitizeOptions(asAdmin bool) map[string]bool {
options := us.config().GetSanitizeOptions()
if asAdmin {
options["email"] = true
options["fullname"] = true
options["authservice"] = true
}
return options
}
// IsUsernameTaken checks if the username is already used by another user. Return false if the username is invalid.
func (us *UserService) IsUsernameTaken(name string) bool {
if !model.IsValidUsername(name) {
return false
}
if _, err := us.store.GetByUsername(name); err != nil {
return false
}
return true
}