github.com/coincircle/mattermost-server@v4.8.1-0.20180321182714-9d701c704416+incompatible/app/user.go (about)

     1  // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"bytes"
     8  	b64 "encoding/base64"
     9  	"fmt"
    10  	"hash/fnv"
    11  	"image"
    12  	"image/color"
    13  	"image/draw"
    14  	_ "image/gif"
    15  	_ "image/jpeg"
    16  	"image/png"
    17  	"io"
    18  	"io/ioutil"
    19  	"mime/multipart"
    20  	"net/http"
    21  	"path/filepath"
    22  	"strconv"
    23  	"strings"
    24  
    25  	l4g "github.com/alecthomas/log4go"
    26  	"github.com/disintegration/imaging"
    27  	"github.com/golang/freetype"
    28  	"github.com/mattermost/mattermost-server/einterfaces"
    29  	"github.com/mattermost/mattermost-server/model"
    30  	"github.com/mattermost/mattermost-server/store"
    31  	"github.com/mattermost/mattermost-server/utils"
    32  )
    33  
    34  const (
    35  	TOKEN_TYPE_PASSWORD_RECOVERY  = "password_recovery"
    36  	TOKEN_TYPE_VERIFY_EMAIL       = "verify_email"
    37  	PASSWORD_RECOVER_EXPIRY_TIME  = 1000 * 60 * 60 // 1 hour
    38  	IMAGE_PROFILE_PIXEL_DIMENSION = 128
    39  )
    40  
    41  func (a *App) CreateUserWithHash(user *model.User, hash string, data string) (*model.User, *model.AppError) {
    42  	if err := a.IsUserSignUpAllowed(); err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	props := model.MapFromJson(strings.NewReader(data))
    47  
    48  	if hash != utils.HashSha256(fmt.Sprintf("%v:%v", data, a.Config().EmailSettings.InviteSalt)) {
    49  		return nil, model.NewAppError("CreateUserWithHash", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusInternalServerError)
    50  	}
    51  
    52  	if t, err := strconv.ParseInt(props["time"], 10, 64); err != nil || model.GetMillis()-t > 1000*60*60*48 { // 48 hours
    53  		return nil, model.NewAppError("CreateUserWithHash", "api.user.create_user.signup_link_expired.app_error", nil, "", http.StatusInternalServerError)
    54  	}
    55  
    56  	teamId := props["id"]
    57  
    58  	var team *model.Team
    59  	if result := <-a.Srv.Store.Team().Get(teamId); result.Err != nil {
    60  		return nil, result.Err
    61  	} else {
    62  		team = result.Data.(*model.Team)
    63  	}
    64  
    65  	user.Email = props["email"]
    66  	user.EmailVerified = true
    67  
    68  	var ruser *model.User
    69  	var err *model.AppError
    70  	if ruser, err = a.CreateUser(user); err != nil {
    71  		return nil, err
    72  	}
    73  
    74  	if err := a.JoinUserToTeam(team, ruser, ""); err != nil {
    75  		return nil, err
    76  	}
    77  
    78  	a.AddDirectChannels(team.Id, ruser)
    79  
    80  	return ruser, nil
    81  }
    82  
    83  func (a *App) CreateUserWithInviteId(user *model.User, inviteId string) (*model.User, *model.AppError) {
    84  	if err := a.IsUserSignUpAllowed(); err != nil {
    85  		return nil, err
    86  	}
    87  
    88  	var team *model.Team
    89  	if result := <-a.Srv.Store.Team().GetByInviteId(inviteId); result.Err != nil {
    90  		return nil, result.Err
    91  	} else {
    92  		team = result.Data.(*model.Team)
    93  	}
    94  
    95  	user.EmailVerified = false
    96  
    97  	var ruser *model.User
    98  	var err *model.AppError
    99  	if ruser, err = a.CreateUser(user); err != nil {
   100  		return nil, err
   101  	}
   102  
   103  	if err := a.JoinUserToTeam(team, ruser, ""); err != nil {
   104  		return nil, err
   105  	}
   106  
   107  	a.AddDirectChannels(team.Id, ruser)
   108  
   109  	if err := a.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, a.GetSiteURL()); err != nil {
   110  		l4g.Error(err.Error())
   111  	}
   112  
   113  	return ruser, nil
   114  }
   115  
   116  func (a *App) CreateUserAsAdmin(user *model.User) (*model.User, *model.AppError) {
   117  	ruser, err := a.CreateUser(user)
   118  	if err != nil {
   119  		return nil, err
   120  	}
   121  
   122  	if err := a.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, a.GetSiteURL()); err != nil {
   123  		l4g.Error(err.Error())
   124  	}
   125  
   126  	return ruser, nil
   127  }
   128  
   129  func (a *App) CreateUserFromSignup(user *model.User) (*model.User, *model.AppError) {
   130  	if err := a.IsUserSignUpAllowed(); err != nil {
   131  		return nil, err
   132  	}
   133  
   134  	if !a.IsFirstUserAccount() && !*a.Config().TeamSettings.EnableOpenServer {
   135  		err := model.NewAppError("CreateUserFromSignup", "api.user.create_user.no_open_server", nil, "email="+user.Email, http.StatusForbidden)
   136  		return nil, err
   137  	}
   138  
   139  	user.EmailVerified = false
   140  
   141  	ruser, err := a.CreateUser(user)
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  
   146  	if err := a.SendWelcomeEmail(ruser.Id, ruser.Email, ruser.EmailVerified, ruser.Locale, a.GetSiteURL()); err != nil {
   147  		l4g.Error(err.Error())
   148  	}
   149  
   150  	return ruser, nil
   151  }
   152  
   153  func (a *App) IsUserSignUpAllowed() *model.AppError {
   154  	if !a.Config().EmailSettings.EnableSignUpWithEmail || !a.Config().TeamSettings.EnableUserCreation {
   155  		err := model.NewAppError("IsUserSignUpAllowed", "api.user.create_user.signup_email_disabled.app_error", nil, "", http.StatusNotImplemented)
   156  		return err
   157  	}
   158  	return nil
   159  }
   160  
   161  func (a *App) IsFirstUserAccount() bool {
   162  	if a.SessionCacheLength() == 0 {
   163  		if cr := <-a.Srv.Store.User().GetTotalUsersCount(); cr.Err != nil {
   164  			l4g.Error(cr.Err)
   165  			return false
   166  		} else {
   167  			count := cr.Data.(int64)
   168  			if count <= 0 {
   169  				return true
   170  			}
   171  		}
   172  	}
   173  
   174  	return false
   175  }
   176  
   177  func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) {
   178  	if !user.IsLDAPUser() && !user.IsSAMLUser() && !CheckUserDomain(user, a.Config().TeamSettings.RestrictCreationToDomains) {
   179  		return nil, model.NewAppError("CreateUser", "api.user.create_user.accepted_domain.app_error", nil, "", http.StatusBadRequest)
   180  	}
   181  
   182  	user.Roles = model.SYSTEM_USER_ROLE_ID
   183  
   184  	// Below is a special case where the first user in the entire
   185  	// system is granted the system_admin role
   186  	if result := <-a.Srv.Store.User().GetTotalUsersCount(); result.Err != nil {
   187  		return nil, result.Err
   188  	} else {
   189  		count := result.Data.(int64)
   190  		if count <= 0 {
   191  			user.Roles = model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID
   192  		}
   193  	}
   194  
   195  	if _, ok := utils.GetSupportedLocales()[user.Locale]; !ok {
   196  		user.Locale = *a.Config().LocalizationSettings.DefaultClientLocale
   197  	}
   198  
   199  	if ruser, err := a.createUser(user); err != nil {
   200  		return nil, err
   201  	} else {
   202  		// This message goes to everyone, so the teamId, channelId and userId are irrelevant
   203  		message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_NEW_USER, "", "", "", nil)
   204  		message.Add("user_id", ruser.Id)
   205  		a.Publish(message)
   206  
   207  		return ruser, nil
   208  	}
   209  }
   210  
   211  func (a *App) createUser(user *model.User) (*model.User, *model.AppError) {
   212  	user.MakeNonNil()
   213  
   214  	if err := a.IsPasswordValid(user.Password); user.AuthService == "" && err != nil {
   215  		return nil, err
   216  	}
   217  
   218  	if result := <-a.Srv.Store.User().Save(user); result.Err != nil {
   219  		l4g.Error(utils.T("api.user.create_user.save.error"), result.Err)
   220  		return nil, result.Err
   221  	} else {
   222  		ruser := result.Data.(*model.User)
   223  
   224  		if user.EmailVerified {
   225  			if err := a.VerifyUserEmail(ruser.Id); err != nil {
   226  				l4g.Error(utils.T("api.user.create_user.verified.error"), err)
   227  			}
   228  		}
   229  
   230  		pref := model.Preference{UserId: ruser.Id, Category: model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, Name: ruser.Id, Value: "0"}
   231  		if presult := <-a.Srv.Store.Preference().Save(&model.Preferences{pref}); presult.Err != nil {
   232  			l4g.Error(utils.T("api.user.create_user.tutorial.error"), presult.Err.Message)
   233  		}
   234  
   235  		ruser.Sanitize(map[string]bool{})
   236  
   237  		return ruser, nil
   238  	}
   239  }
   240  
   241  func (a *App) CreateOAuthUser(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) {
   242  	if !a.Config().TeamSettings.EnableUserCreation {
   243  		return nil, model.NewAppError("CreateOAuthUser", "api.user.create_user.disabled.app_error", nil, "", http.StatusNotImplemented)
   244  	}
   245  
   246  	var user *model.User
   247  	provider := einterfaces.GetOauthProvider(service)
   248  	if provider == nil {
   249  		return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.not_available.app_error", map[string]interface{}{"Service": strings.Title(service)}, "", http.StatusNotImplemented)
   250  	} else {
   251  		user = provider.GetUserFromJson(userData)
   252  	}
   253  
   254  	if user == nil {
   255  		return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.create.app_error", map[string]interface{}{"Service": service}, "", http.StatusInternalServerError)
   256  	}
   257  
   258  	suchan := a.Srv.Store.User().GetByAuth(user.AuthData, service)
   259  	euchan := a.Srv.Store.User().GetByEmail(user.Email)
   260  
   261  	found := true
   262  	count := 0
   263  	for found {
   264  		if found = a.IsUsernameTaken(user.Username); found {
   265  			user.Username = user.Username + strconv.Itoa(count)
   266  			count += 1
   267  		}
   268  	}
   269  
   270  	if result := <-suchan; result.Err == nil {
   271  		return result.Data.(*model.User), nil
   272  	}
   273  
   274  	if result := <-euchan; result.Err == nil {
   275  		authService := result.Data.(*model.User).AuthService
   276  		if authService == "" {
   277  			return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": model.USER_AUTH_SERVICE_EMAIL}, "email="+user.Email, http.StatusBadRequest)
   278  		} else {
   279  			return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]interface{}{"Service": service, "Auth": authService}, "email="+user.Email, http.StatusBadRequest)
   280  		}
   281  	}
   282  
   283  	user.EmailVerified = true
   284  
   285  	ruser, err := a.CreateUser(user)
   286  	if err != nil {
   287  		return nil, err
   288  	}
   289  
   290  	if len(teamId) > 0 {
   291  		err = a.AddUserToTeamByTeamId(teamId, user)
   292  		if err != nil {
   293  			return nil, err
   294  		}
   295  
   296  		err = a.AddDirectChannels(teamId, user)
   297  		if err != nil {
   298  			l4g.Error(err.Error())
   299  		}
   300  	}
   301  
   302  	return ruser, nil
   303  }
   304  
   305  // Check that a user's email domain matches a list of space-delimited domains as a string.
   306  func CheckUserDomain(user *model.User, domains string) bool {
   307  	if len(domains) == 0 {
   308  		return true
   309  	}
   310  
   311  	domainArray := strings.Fields(strings.TrimSpace(strings.ToLower(strings.Replace(strings.Replace(domains, "@", " ", -1), ",", " ", -1))))
   312  
   313  	for _, d := range domainArray {
   314  		if strings.HasSuffix(strings.ToLower(user.Email), "@"+d) {
   315  			return true
   316  		}
   317  	}
   318  
   319  	return false
   320  }
   321  
   322  // Check if the username is already used by another user. Return false if the username is invalid.
   323  func (a *App) IsUsernameTaken(name string) bool {
   324  
   325  	if !model.IsValidUsername(name) {
   326  		return false
   327  	}
   328  
   329  	if result := <-a.Srv.Store.User().GetByUsername(name); result.Err != nil {
   330  		return false
   331  	}
   332  
   333  	return true
   334  }
   335  
   336  func (a *App) GetUser(userId string) (*model.User, *model.AppError) {
   337  	if result := <-a.Srv.Store.User().Get(userId); result.Err != nil {
   338  		return nil, result.Err
   339  	} else {
   340  		return result.Data.(*model.User), nil
   341  	}
   342  }
   343  
   344  func (a *App) GetUserByUsername(username string) (*model.User, *model.AppError) {
   345  	if result := <-a.Srv.Store.User().GetByUsername(username); result.Err != nil && result.Err.Id == "store.sql_user.get_by_username.app_error" {
   346  		result.Err.StatusCode = http.StatusNotFound
   347  		return nil, result.Err
   348  	} else {
   349  		return result.Data.(*model.User), nil
   350  	}
   351  }
   352  
   353  func (a *App) GetUserByEmail(email string) (*model.User, *model.AppError) {
   354  
   355  	if result := <-a.Srv.Store.User().GetByEmail(email); result.Err != nil && result.Err.Id == "store.sql_user.missing_account.const" {
   356  		result.Err.StatusCode = http.StatusNotFound
   357  		return nil, result.Err
   358  	} else if result.Err != nil {
   359  		result.Err.StatusCode = http.StatusBadRequest
   360  		return nil, result.Err
   361  	} else {
   362  		return result.Data.(*model.User), nil
   363  	}
   364  }
   365  
   366  func (a *App) GetUserByAuth(authData *string, authService string) (*model.User, *model.AppError) {
   367  	if result := <-a.Srv.Store.User().GetByAuth(authData, authService); result.Err != nil {
   368  		return nil, result.Err
   369  	} else {
   370  		return result.Data.(*model.User), nil
   371  	}
   372  }
   373  
   374  func (a *App) GetUserForLogin(loginId string, onlyLdap bool) (*model.User, *model.AppError) {
   375  	license := a.License()
   376  	ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap != nil && license != nil && *license.Features.LDAP
   377  
   378  	if result := <-a.Srv.Store.User().GetForLogin(
   379  		loginId,
   380  		*a.Config().EmailSettings.EnableSignInWithUsername && !onlyLdap,
   381  		*a.Config().EmailSettings.EnableSignInWithEmail && !onlyLdap,
   382  		ldapAvailable,
   383  	); result.Err != nil && result.Err.Id == "store.sql_user.get_for_login.multiple_users" {
   384  		// don't fall back to LDAP in this case since we already know there's an LDAP user, but that it shouldn't work
   385  		result.Err.StatusCode = http.StatusBadRequest
   386  		return nil, result.Err
   387  	} else if result.Err != nil {
   388  		if !ldapAvailable {
   389  			// failed to find user and no LDAP server to fall back on
   390  			result.Err.StatusCode = http.StatusBadRequest
   391  			return nil, result.Err
   392  		}
   393  
   394  		// fall back to LDAP server to see if we can find a user
   395  		if ldapUser, ldapErr := a.Ldap.GetUser(loginId); ldapErr != nil {
   396  			ldapErr.StatusCode = http.StatusBadRequest
   397  			return nil, ldapErr
   398  		} else {
   399  			return ldapUser, nil
   400  		}
   401  	} else {
   402  		return result.Data.(*model.User), nil
   403  	}
   404  }
   405  
   406  func (a *App) GetUsers(offset int, limit int) ([]*model.User, *model.AppError) {
   407  	if result := <-a.Srv.Store.User().GetAllProfiles(offset, limit); result.Err != nil {
   408  		return nil, result.Err
   409  	} else {
   410  		return result.Data.([]*model.User), nil
   411  	}
   412  }
   413  
   414  func (a *App) GetUsersMap(offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) {
   415  	users, err := a.GetUsers(offset, limit)
   416  	if err != nil {
   417  		return nil, err
   418  	}
   419  
   420  	userMap := make(map[string]*model.User, len(users))
   421  
   422  	for _, user := range users {
   423  		a.SanitizeProfile(user, asAdmin)
   424  		userMap[user.Id] = user
   425  	}
   426  
   427  	return userMap, nil
   428  }
   429  
   430  func (a *App) GetUsersPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   431  	users, err := a.GetUsers(page*perPage, perPage)
   432  	if err != nil {
   433  		return nil, err
   434  	}
   435  
   436  	return a.sanitizeProfiles(users, asAdmin), nil
   437  }
   438  
   439  func (a *App) GetUsersEtag() string {
   440  	return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForAllProfiles()).Data.(string), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress)
   441  }
   442  
   443  func (a *App) GetUsersInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) {
   444  	if result := <-a.Srv.Store.User().GetProfiles(teamId, offset, limit); result.Err != nil {
   445  		return nil, result.Err
   446  	} else {
   447  		return result.Data.([]*model.User), nil
   448  	}
   449  }
   450  
   451  func (a *App) GetUsersNotInTeam(teamId string, offset int, limit int) ([]*model.User, *model.AppError) {
   452  	if result := <-a.Srv.Store.User().GetProfilesNotInTeam(teamId, offset, limit); result.Err != nil {
   453  		return nil, result.Err
   454  	} else {
   455  		return result.Data.([]*model.User), nil
   456  	}
   457  }
   458  
   459  func (a *App) GetUsersInTeamMap(teamId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) {
   460  	users, err := a.GetUsersInTeam(teamId, offset, limit)
   461  	if err != nil {
   462  		return nil, err
   463  	}
   464  
   465  	userMap := make(map[string]*model.User, len(users))
   466  
   467  	for _, user := range users {
   468  		a.SanitizeProfile(user, asAdmin)
   469  		userMap[user.Id] = user
   470  	}
   471  
   472  	return userMap, nil
   473  }
   474  
   475  func (a *App) GetUsersInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   476  	users, err := a.GetUsersInTeam(teamId, page*perPage, perPage)
   477  	if err != nil {
   478  		return nil, err
   479  	}
   480  
   481  	return a.sanitizeProfiles(users, asAdmin), nil
   482  }
   483  
   484  func (a *App) GetUsersNotInTeamPage(teamId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   485  	users, err := a.GetUsersNotInTeam(teamId, page*perPage, perPage)
   486  	if err != nil {
   487  		return nil, err
   488  	}
   489  
   490  	return a.sanitizeProfiles(users, asAdmin), nil
   491  }
   492  
   493  func (a *App) GetUsersInTeamEtag(teamId string) string {
   494  	return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForProfiles(teamId)).Data.(string), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress)
   495  }
   496  
   497  func (a *App) GetUsersNotInTeamEtag(teamId string) string {
   498  	return fmt.Sprintf("%v.%v.%v", (<-a.Srv.Store.User().GetEtagForProfilesNotInTeam(teamId)).Data.(string), a.Config().PrivacySettings.ShowFullName, a.Config().PrivacySettings.ShowEmailAddress)
   499  }
   500  
   501  func (a *App) GetUsersInChannel(channelId string, offset int, limit int) ([]*model.User, *model.AppError) {
   502  	if result := <-a.Srv.Store.User().GetProfilesInChannel(channelId, offset, limit); result.Err != nil {
   503  		return nil, result.Err
   504  	} else {
   505  		return result.Data.([]*model.User), nil
   506  	}
   507  }
   508  
   509  func (a *App) GetUsersInChannelByStatus(channelId string, offset int, limit int) ([]*model.User, *model.AppError) {
   510  	if result := <-a.Srv.Store.User().GetProfilesInChannelByStatus(channelId, offset, limit); result.Err != nil {
   511  		return nil, result.Err
   512  	} else {
   513  		return result.Data.([]*model.User), nil
   514  	}
   515  }
   516  
   517  func (a *App) GetUsersInChannelMap(channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) {
   518  	users, err := a.GetUsersInChannel(channelId, offset, limit)
   519  	if err != nil {
   520  		return nil, err
   521  	}
   522  
   523  	userMap := make(map[string]*model.User, len(users))
   524  
   525  	for _, user := range users {
   526  		a.SanitizeProfile(user, asAdmin)
   527  		userMap[user.Id] = user
   528  	}
   529  
   530  	return userMap, nil
   531  }
   532  
   533  func (a *App) GetUsersInChannelPage(channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   534  	users, err := a.GetUsersInChannel(channelId, page*perPage, perPage)
   535  	if err != nil {
   536  		return nil, err
   537  	}
   538  
   539  	return a.sanitizeProfiles(users, asAdmin), nil
   540  }
   541  
   542  func (a *App) GetUsersInChannelPageByStatus(channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   543  	users, err := a.GetUsersInChannelByStatus(channelId, page*perPage, perPage)
   544  	if err != nil {
   545  		return nil, err
   546  	}
   547  
   548  	return a.sanitizeProfiles(users, asAdmin), nil
   549  }
   550  
   551  func (a *App) GetUsersNotInChannel(teamId string, channelId string, offset int, limit int) ([]*model.User, *model.AppError) {
   552  	if result := <-a.Srv.Store.User().GetProfilesNotInChannel(teamId, channelId, offset, limit); result.Err != nil {
   553  		return nil, result.Err
   554  	} else {
   555  		return result.Data.([]*model.User), nil
   556  	}
   557  }
   558  
   559  func (a *App) GetUsersNotInChannelMap(teamId string, channelId string, offset int, limit int, asAdmin bool) (map[string]*model.User, *model.AppError) {
   560  	users, err := a.GetUsersNotInChannel(teamId, channelId, offset, limit)
   561  	if err != nil {
   562  		return nil, err
   563  	}
   564  
   565  	userMap := make(map[string]*model.User, len(users))
   566  
   567  	for _, user := range users {
   568  		a.SanitizeProfile(user, asAdmin)
   569  		userMap[user.Id] = user
   570  	}
   571  
   572  	return userMap, nil
   573  }
   574  
   575  func (a *App) GetUsersNotInChannelPage(teamId string, channelId string, page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   576  	users, err := a.GetUsersNotInChannel(teamId, channelId, page*perPage, perPage)
   577  	if err != nil {
   578  		return nil, err
   579  	}
   580  
   581  	return a.sanitizeProfiles(users, asAdmin), nil
   582  }
   583  
   584  func (a *App) GetUsersWithoutTeamPage(page int, perPage int, asAdmin bool) ([]*model.User, *model.AppError) {
   585  	users, err := a.GetUsersWithoutTeam(page*perPage, perPage)
   586  	if err != nil {
   587  		return nil, err
   588  	}
   589  
   590  	return a.sanitizeProfiles(users, asAdmin), nil
   591  }
   592  
   593  func (a *App) GetUsersWithoutTeam(offset int, limit int) ([]*model.User, *model.AppError) {
   594  	if result := <-a.Srv.Store.User().GetProfilesWithoutTeam(offset, limit); result.Err != nil {
   595  		return nil, result.Err
   596  	} else {
   597  		return result.Data.([]*model.User), nil
   598  	}
   599  }
   600  
   601  func (a *App) GetUsersByIds(userIds []string, asAdmin bool) ([]*model.User, *model.AppError) {
   602  	if result := <-a.Srv.Store.User().GetProfileByIds(userIds, true); result.Err != nil {
   603  		return nil, result.Err
   604  	} else {
   605  		users := result.Data.([]*model.User)
   606  		return a.sanitizeProfiles(users, asAdmin), nil
   607  	}
   608  }
   609  
   610  func (a *App) GetUsersByUsernames(usernames []string, asAdmin bool) ([]*model.User, *model.AppError) {
   611  	if result := <-a.Srv.Store.User().GetProfilesByUsernames(usernames, ""); result.Err != nil {
   612  		return nil, result.Err
   613  	} else {
   614  		users := result.Data.([]*model.User)
   615  		return a.sanitizeProfiles(users, asAdmin), nil
   616  	}
   617  }
   618  
   619  func (a *App) sanitizeProfiles(users []*model.User, asAdmin bool) []*model.User {
   620  	for _, u := range users {
   621  		a.SanitizeProfile(u, asAdmin)
   622  	}
   623  
   624  	return users
   625  }
   626  
   627  func (a *App) GenerateMfaSecret(userId string) (*model.MfaSecret, *model.AppError) {
   628  	if a.Mfa == nil {
   629  		return nil, model.NewAppError("generateMfaSecret", "api.user.generate_mfa_qr.not_available.app_error", nil, "", http.StatusNotImplemented)
   630  	}
   631  
   632  	var user *model.User
   633  	var err *model.AppError
   634  	if user, err = a.GetUser(userId); err != nil {
   635  		return nil, err
   636  	}
   637  
   638  	secret, img, err := a.Mfa.GenerateSecret(user)
   639  	if err != nil {
   640  		return nil, err
   641  	}
   642  
   643  	mfaSecret := &model.MfaSecret{Secret: secret, QRCode: b64.StdEncoding.EncodeToString(img)}
   644  	return mfaSecret, nil
   645  }
   646  
   647  func (a *App) ActivateMfa(userId, token string) *model.AppError {
   648  	if a.Mfa == nil {
   649  		err := model.NewAppError("ActivateMfa", "api.user.update_mfa.not_available.app_error", nil, "", http.StatusNotImplemented)
   650  		return err
   651  	}
   652  
   653  	var user *model.User
   654  	if result := <-a.Srv.Store.User().Get(userId); result.Err != nil {
   655  		return result.Err
   656  	} else {
   657  		user = result.Data.(*model.User)
   658  	}
   659  
   660  	if len(user.AuthService) > 0 && user.AuthService != model.USER_AUTH_SERVICE_LDAP {
   661  		return model.NewAppError("ActivateMfa", "api.user.activate_mfa.email_and_ldap_only.app_error", nil, "", http.StatusBadRequest)
   662  	}
   663  
   664  	if err := a.Mfa.Activate(user, token); err != nil {
   665  		return err
   666  	}
   667  
   668  	return nil
   669  }
   670  
   671  func (a *App) DeactivateMfa(userId string) *model.AppError {
   672  	if a.Mfa == nil {
   673  		err := model.NewAppError("DeactivateMfa", "api.user.update_mfa.not_available.app_error", nil, "", http.StatusNotImplemented)
   674  		return err
   675  	}
   676  
   677  	if err := a.Mfa.Deactivate(userId); err != nil {
   678  		return err
   679  	}
   680  
   681  	return nil
   682  }
   683  
   684  func CreateProfileImage(username string, userId string, initialFont string) ([]byte, *model.AppError) {
   685  	colors := []color.NRGBA{
   686  		{197, 8, 126, 255},
   687  		{227, 207, 18, 255},
   688  		{28, 181, 105, 255},
   689  		{35, 188, 224, 255},
   690  		{116, 49, 196, 255},
   691  		{197, 8, 126, 255},
   692  		{197, 19, 19, 255},
   693  		{250, 134, 6, 255},
   694  		{227, 207, 18, 255},
   695  		{123, 201, 71, 255},
   696  		{28, 181, 105, 255},
   697  		{35, 188, 224, 255},
   698  		{116, 49, 196, 255},
   699  		{197, 8, 126, 255},
   700  		{197, 19, 19, 255},
   701  		{250, 134, 6, 255},
   702  		{227, 207, 18, 255},
   703  		{123, 201, 71, 255},
   704  		{28, 181, 105, 255},
   705  		{35, 188, 224, 255},
   706  		{116, 49, 196, 255},
   707  		{197, 8, 126, 255},
   708  		{197, 19, 19, 255},
   709  		{250, 134, 6, 255},
   710  		{227, 207, 18, 255},
   711  		{123, 201, 71, 255},
   712  	}
   713  
   714  	h := fnv.New32a()
   715  	h.Write([]byte(userId))
   716  	seed := h.Sum32()
   717  
   718  	initial := string(strings.ToUpper(username)[0])
   719  
   720  	fontDir, _ := utils.FindDir("fonts")
   721  	fontBytes, err := ioutil.ReadFile(filepath.Join(fontDir, initialFont))
   722  	if err != nil {
   723  		return nil, model.NewAppError("CreateProfileImage", "api.user.create_profile_image.default_font.app_error", nil, err.Error(), http.StatusInternalServerError)
   724  	}
   725  	font, err := freetype.ParseFont(fontBytes)
   726  	if err != nil {
   727  		return nil, model.NewAppError("CreateProfileImage", "api.user.create_profile_image.default_font.app_error", nil, err.Error(), http.StatusInternalServerError)
   728  	}
   729  
   730  	color := colors[int64(seed)%int64(len(colors))]
   731  	dstImg := image.NewRGBA(image.Rect(0, 0, IMAGE_PROFILE_PIXEL_DIMENSION, IMAGE_PROFILE_PIXEL_DIMENSION))
   732  	srcImg := image.White
   733  	draw.Draw(dstImg, dstImg.Bounds(), &image.Uniform{color}, image.ZP, draw.Src)
   734  	size := float64(IMAGE_PROFILE_PIXEL_DIMENSION / 2)
   735  
   736  	c := freetype.NewContext()
   737  	c.SetFont(font)
   738  	c.SetFontSize(size)
   739  	c.SetClip(dstImg.Bounds())
   740  	c.SetDst(dstImg)
   741  	c.SetSrc(srcImg)
   742  
   743  	pt := freetype.Pt(IMAGE_PROFILE_PIXEL_DIMENSION/6, IMAGE_PROFILE_PIXEL_DIMENSION*2/3)
   744  	_, err = c.DrawString(initial, pt)
   745  	if err != nil {
   746  		return nil, model.NewAppError("CreateProfileImage", "api.user.create_profile_image.initial.app_error", nil, err.Error(), http.StatusInternalServerError)
   747  	}
   748  
   749  	buf := new(bytes.Buffer)
   750  
   751  	if imgErr := png.Encode(buf, dstImg); imgErr != nil {
   752  		return nil, model.NewAppError("CreateProfileImage", "api.user.create_profile_image.encode.app_error", nil, imgErr.Error(), http.StatusInternalServerError)
   753  	} else {
   754  		return buf.Bytes(), nil
   755  	}
   756  }
   757  
   758  func (a *App) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) {
   759  	var img []byte
   760  	readFailed := false
   761  
   762  	if len(*a.Config().FileSettings.DriverName) == 0 {
   763  		var err *model.AppError
   764  		if img, err = CreateProfileImage(user.Username, user.Id, a.Config().FileSettings.InitialFont); err != nil {
   765  			return nil, false, err
   766  		}
   767  	} else {
   768  		path := "users/" + user.Id + "/profile.png"
   769  
   770  		if data, err := a.ReadFile(path); err != nil {
   771  			readFailed = true
   772  
   773  			if img, err = CreateProfileImage(user.Username, user.Id, a.Config().FileSettings.InitialFont); err != nil {
   774  				return nil, false, err
   775  			}
   776  
   777  			if user.LastPictureUpdate == 0 {
   778  				if err := a.WriteFile(img, path); err != nil {
   779  					return nil, false, err
   780  				}
   781  			}
   782  
   783  		} else {
   784  			img = data
   785  		}
   786  	}
   787  
   788  	return img, readFailed, nil
   789  }
   790  
   791  func (a *App) SetProfileImage(userId string, imageData *multipart.FileHeader) *model.AppError {
   792  	file, err := imageData.Open()
   793  	if err != nil {
   794  		return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.open.app_error", nil, err.Error(), http.StatusBadRequest)
   795  	}
   796  	defer file.Close()
   797  	return a.SetProfileImageFromFile(userId, file)
   798  }
   799  
   800  func (a *App) SetProfileImageFromFile(userId string, file multipart.File) *model.AppError {
   801  	// Decode image config first to check dimensions before loading the whole thing into memory later on
   802  	config, _, err := image.DecodeConfig(file)
   803  	if err != nil {
   804  		return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.decode_config.app_error", nil, err.Error(), http.StatusBadRequest)
   805  	} else if config.Width*config.Height > model.MaxImageSize {
   806  		return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.too_large.app_error", nil, err.Error(), http.StatusBadRequest)
   807  	}
   808  
   809  	file.Seek(0, 0)
   810  
   811  	// Decode image into Image object
   812  	img, _, err := image.Decode(file)
   813  	if err != nil {
   814  		return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.decode.app_error", nil, err.Error(), http.StatusBadRequest)
   815  	}
   816  
   817  	file.Seek(0, 0)
   818  
   819  	orientation, _ := getImageOrientation(file)
   820  	img = makeImageUpright(img, orientation)
   821  
   822  	// Scale profile image
   823  	profileWidthAndHeight := 128
   824  	img = imaging.Fill(img, profileWidthAndHeight, profileWidthAndHeight, imaging.Center, imaging.Lanczos)
   825  
   826  	buf := new(bytes.Buffer)
   827  	err = png.Encode(buf, img)
   828  	if err != nil {
   829  		return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.encode.app_error", nil, err.Error(), http.StatusInternalServerError)
   830  	}
   831  
   832  	path := "users/" + userId + "/profile.png"
   833  
   834  	if err := a.WriteFile(buf.Bytes(), path); err != nil {
   835  		return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.upload_profile.app_error", nil, "", http.StatusInternalServerError)
   836  	}
   837  
   838  	<-a.Srv.Store.User().UpdateLastPictureUpdate(userId)
   839  
   840  	a.InvalidateCacheForUser(userId)
   841  
   842  	if user, err := a.GetUser(userId); err != nil {
   843  		l4g.Error(utils.T("api.user.get_me.getting.error"), userId)
   844  	} else {
   845  		options := a.Config().GetSanitizeOptions()
   846  		user.SanitizeProfile(options)
   847  
   848  		message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", nil)
   849  		message.Add("user", user)
   850  		a.Publish(message)
   851  	}
   852  
   853  	return nil
   854  }
   855  
   856  func (a *App) UpdatePasswordAsUser(userId, currentPassword, newPassword string) *model.AppError {
   857  	var user *model.User
   858  	var err *model.AppError
   859  
   860  	if user, err = a.GetUser(userId); err != nil {
   861  		return err
   862  	}
   863  
   864  	if user == nil {
   865  		err = model.NewAppError("updatePassword", "api.user.update_password.valid_account.app_error", nil, "", http.StatusBadRequest)
   866  		return err
   867  	}
   868  
   869  	if user.AuthData != nil && *user.AuthData != "" {
   870  		err = model.NewAppError("updatePassword", "api.user.update_password.oauth.app_error", nil, "auth_service="+user.AuthService, http.StatusBadRequest)
   871  		return err
   872  	}
   873  
   874  	if err := a.doubleCheckPassword(user, currentPassword); err != nil {
   875  		if err.Id == "api.user.check_user_password.invalid.app_error" {
   876  			err = model.NewAppError("updatePassword", "api.user.update_password.incorrect.app_error", nil, "", http.StatusBadRequest)
   877  		}
   878  		return err
   879  	}
   880  
   881  	T := utils.GetUserTranslations(user.Locale)
   882  
   883  	return a.UpdatePasswordSendEmail(user, newPassword, T("api.user.update_password.menu"))
   884  }
   885  
   886  func (a *App) UpdateNonSSOUserActive(userId string, active bool) (*model.User, *model.AppError) {
   887  	var user *model.User
   888  	var err *model.AppError
   889  	if user, err = a.GetUser(userId); err != nil {
   890  		return nil, err
   891  	}
   892  
   893  	if user.IsSSOUser() {
   894  		err := model.NewAppError("UpdateActive", "api.user.update_active.no_deactivate_sso.app_error", nil, "userId="+user.Id, http.StatusBadRequest)
   895  		err.StatusCode = http.StatusBadRequest
   896  		return nil, err
   897  	}
   898  
   899  	return a.UpdateActive(user, active)
   900  }
   901  
   902  func (a *App) UpdateActive(user *model.User, active bool) (*model.User, *model.AppError) {
   903  	if active {
   904  		user.DeleteAt = 0
   905  	} else {
   906  		user.DeleteAt = model.GetMillis()
   907  	}
   908  
   909  	if result := <-a.Srv.Store.User().Update(user, true); result.Err != nil {
   910  		return nil, result.Err
   911  	} else {
   912  		if user.DeleteAt > 0 {
   913  			if err := a.RevokeAllSessions(user.Id); err != nil {
   914  				return nil, err
   915  			}
   916  		}
   917  
   918  		ruser := result.Data.([2]*model.User)[0]
   919  		options := a.Config().GetSanitizeOptions()
   920  		options["passwordupdate"] = false
   921  		ruser.Sanitize(options)
   922  
   923  		if !active {
   924  			a.SetStatusOffline(ruser.Id, false)
   925  		}
   926  
   927  		teamsForUser, err := a.GetTeamsForUser(user.Id)
   928  		if err != nil {
   929  			return nil, err
   930  		}
   931  
   932  		for _, team := range teamsForUser {
   933  			channelsForUser, err := a.GetChannelsForUser(team.Id, user.Id)
   934  			if err != nil {
   935  				return nil, err
   936  			}
   937  
   938  			for _, channel := range *channelsForUser {
   939  				a.InvalidateCacheForChannelMembers(channel.Id)
   940  			}
   941  		}
   942  
   943  		return ruser, nil
   944  	}
   945  }
   946  
   947  func (a *App) SanitizeProfile(user *model.User, asAdmin bool) {
   948  	options := a.Config().GetSanitizeOptions()
   949  	if asAdmin {
   950  		options["email"] = true
   951  		options["fullname"] = true
   952  		options["authservice"] = true
   953  	}
   954  	user.SanitizeProfile(options)
   955  }
   956  
   957  func (a *App) UpdateUserAsUser(user *model.User, asAdmin bool) (*model.User, *model.AppError) {
   958  	updatedUser, err := a.UpdateUser(user, true)
   959  	if err != nil {
   960  		return nil, err
   961  	}
   962  
   963  	a.sendUpdatedUserEvent(*updatedUser, asAdmin)
   964  
   965  	return updatedUser, nil
   966  }
   967  
   968  func (a *App) PatchUser(userId string, patch *model.UserPatch, asAdmin bool) (*model.User, *model.AppError) {
   969  	user, err := a.GetUser(userId)
   970  	if err != nil {
   971  		return nil, err
   972  	}
   973  
   974  	user.Patch(patch)
   975  
   976  	updatedUser, err := a.UpdateUser(user, true)
   977  	if err != nil {
   978  		return nil, err
   979  	}
   980  
   981  	a.sendUpdatedUserEvent(*updatedUser, asAdmin)
   982  
   983  	return updatedUser, nil
   984  }
   985  
   986  func (a *App) UpdateUserAuth(userId string, userAuth *model.UserAuth) (*model.UserAuth, *model.AppError) {
   987  	if userAuth.AuthData == nil || *userAuth.AuthData == "" || userAuth.AuthService == "" {
   988  		userAuth.AuthData = nil
   989  		userAuth.AuthService = ""
   990  
   991  		if err := a.IsPasswordValid(userAuth.Password); err != nil {
   992  			return nil, err
   993  		}
   994  		password := model.HashPassword(userAuth.Password)
   995  
   996  		if result := <-a.Srv.Store.User().UpdatePassword(userId, password); result.Err != nil {
   997  			return nil, result.Err
   998  		}
   999  	} else {
  1000  		userAuth.Password = ""
  1001  
  1002  		if result := <-a.Srv.Store.User().UpdateAuthData(userId, userAuth.AuthService, userAuth.AuthData, "", false); result.Err != nil {
  1003  			return nil, result.Err
  1004  		}
  1005  	}
  1006  
  1007  	return userAuth, nil
  1008  }
  1009  
  1010  func (a *App) sendUpdatedUserEvent(user model.User, asAdmin bool) {
  1011  	a.SanitizeProfile(&user, asAdmin)
  1012  
  1013  	message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_UPDATED, "", "", "", nil)
  1014  	message.Add("user", user)
  1015  	a.Publish(message)
  1016  }
  1017  
  1018  func (a *App) UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError) {
  1019  	if !CheckUserDomain(user, a.Config().TeamSettings.RestrictCreationToDomains) {
  1020  		result := <-a.Srv.Store.User().Get(user.Id)
  1021  		if result.Err != nil {
  1022  			return nil, result.Err
  1023  		}
  1024  		prev := result.Data.(*model.User)
  1025  		if !prev.IsLDAPUser() && !prev.IsSAMLUser() && user.Email != prev.Email {
  1026  			return nil, model.NewAppError("UpdateUser", "api.user.create_user.accepted_domain.app_error", nil, "", http.StatusBadRequest)
  1027  		}
  1028  	}
  1029  
  1030  	if result := <-a.Srv.Store.User().Update(user, false); result.Err != nil {
  1031  		return nil, result.Err
  1032  	} else {
  1033  		rusers := result.Data.([2]*model.User)
  1034  
  1035  		if sendNotifications {
  1036  			if rusers[0].Email != rusers[1].Email {
  1037  				a.Go(func() {
  1038  					if err := a.SendEmailChangeEmail(rusers[1].Email, rusers[0].Email, rusers[0].Locale, a.GetSiteURL()); err != nil {
  1039  						l4g.Error(err.Error())
  1040  					}
  1041  				})
  1042  
  1043  				if a.Config().EmailSettings.RequireEmailVerification {
  1044  					if err := a.SendEmailVerification(rusers[0]); err != nil {
  1045  						l4g.Error(err.Error())
  1046  					}
  1047  				}
  1048  			}
  1049  
  1050  			if rusers[0].Username != rusers[1].Username {
  1051  				a.Go(func() {
  1052  					if err := a.SendChangeUsernameEmail(rusers[1].Username, rusers[0].Username, rusers[0].Email, rusers[0].Locale, a.GetSiteURL()); err != nil {
  1053  						l4g.Error(err.Error())
  1054  					}
  1055  				})
  1056  			}
  1057  		}
  1058  
  1059  		a.InvalidateCacheForUser(user.Id)
  1060  
  1061  		return rusers[0], nil
  1062  	}
  1063  }
  1064  
  1065  func (a *App) UpdateUserNotifyProps(userId string, props map[string]string) (*model.User, *model.AppError) {
  1066  	var user *model.User
  1067  	var err *model.AppError
  1068  	if user, err = a.GetUser(userId); err != nil {
  1069  		return nil, err
  1070  	}
  1071  
  1072  	user.NotifyProps = props
  1073  
  1074  	var ruser *model.User
  1075  	if ruser, err = a.UpdateUser(user, true); err != nil {
  1076  		return nil, err
  1077  	}
  1078  
  1079  	return ruser, nil
  1080  }
  1081  
  1082  func (a *App) UpdateMfa(activate bool, userId, token string) *model.AppError {
  1083  	if activate {
  1084  		if err := a.ActivateMfa(userId, token); err != nil {
  1085  			return err
  1086  		}
  1087  	} else {
  1088  		if err := a.DeactivateMfa(userId); err != nil {
  1089  			return err
  1090  		}
  1091  	}
  1092  
  1093  	a.Go(func() {
  1094  		var user *model.User
  1095  		var err *model.AppError
  1096  
  1097  		if user, err = a.GetUser(userId); err != nil {
  1098  			l4g.Error(err.Error())
  1099  			return
  1100  		}
  1101  
  1102  		if err := a.SendMfaChangeEmail(user.Email, activate, user.Locale, a.GetSiteURL()); err != nil {
  1103  			l4g.Error(err.Error())
  1104  		}
  1105  	})
  1106  
  1107  	return nil
  1108  }
  1109  
  1110  func (a *App) UpdatePasswordByUserIdSendEmail(userId, newPassword, method string) *model.AppError {
  1111  	var user *model.User
  1112  	var err *model.AppError
  1113  	if user, err = a.GetUser(userId); err != nil {
  1114  		return err
  1115  	}
  1116  
  1117  	return a.UpdatePasswordSendEmail(user, newPassword, method)
  1118  }
  1119  
  1120  func (a *App) UpdatePassword(user *model.User, newPassword string) *model.AppError {
  1121  	if err := a.IsPasswordValid(newPassword); err != nil {
  1122  		return err
  1123  	}
  1124  
  1125  	hashedPassword := model.HashPassword(newPassword)
  1126  
  1127  	if result := <-a.Srv.Store.User().UpdatePassword(user.Id, hashedPassword); result.Err != nil {
  1128  		return model.NewAppError("UpdatePassword", "api.user.update_password.failed.app_error", nil, result.Err.Error(), http.StatusInternalServerError)
  1129  	}
  1130  
  1131  	return nil
  1132  }
  1133  
  1134  func (a *App) UpdatePasswordSendEmail(user *model.User, newPassword, method string) *model.AppError {
  1135  	if err := a.UpdatePassword(user, newPassword); err != nil {
  1136  		return err
  1137  	}
  1138  
  1139  	a.Go(func() {
  1140  		if err := a.SendPasswordChangeEmail(user.Email, method, user.Locale, a.GetSiteURL()); err != nil {
  1141  			l4g.Error(err.Error())
  1142  		}
  1143  	})
  1144  
  1145  	return nil
  1146  }
  1147  
  1148  func (a *App) ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError {
  1149  	var token *model.Token
  1150  	var err *model.AppError
  1151  	if token, err = a.GetPasswordRecoveryToken(userSuppliedTokenString); err != nil {
  1152  		return err
  1153  	} else {
  1154  		if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME {
  1155  			return model.NewAppError("resetPassword", "api.user.reset_password.link_expired.app_error", nil, "", http.StatusBadRequest)
  1156  		}
  1157  	}
  1158  
  1159  	var user *model.User
  1160  	if user, err = a.GetUser(token.Extra); err != nil {
  1161  		return err
  1162  	}
  1163  
  1164  	if user.IsSSOUser() {
  1165  		return model.NewAppError("ResetPasswordFromCode", "api.user.reset_password.sso.app_error", nil, "userId="+user.Id, http.StatusBadRequest)
  1166  	}
  1167  
  1168  	T := utils.GetUserTranslations(user.Locale)
  1169  
  1170  	if err := a.UpdatePasswordSendEmail(user, newPassword, T("api.user.reset_password.method")); err != nil {
  1171  		return err
  1172  	}
  1173  
  1174  	if err := a.DeleteToken(token); err != nil {
  1175  		l4g.Error(err.Error())
  1176  	}
  1177  
  1178  	return nil
  1179  }
  1180  
  1181  func (a *App) SendPasswordReset(email string, siteURL string) (bool, *model.AppError) {
  1182  	var user *model.User
  1183  	var err *model.AppError
  1184  	if user, err = a.GetUserByEmail(email); err != nil {
  1185  		return false, nil
  1186  	}
  1187  
  1188  	if user.AuthData != nil && len(*user.AuthData) != 0 {
  1189  		return false, model.NewAppError("SendPasswordReset", "api.user.send_password_reset.sso.app_error", nil, "userId="+user.Id, http.StatusBadRequest)
  1190  	}
  1191  
  1192  	var token *model.Token
  1193  	if token, err = a.CreatePasswordRecoveryToken(user.Id); err != nil {
  1194  		return false, err
  1195  	}
  1196  
  1197  	if _, err := a.SendPasswordResetEmail(user.Email, token, user.Locale, siteURL); err != nil {
  1198  		return false, model.NewAppError("SendPasswordReset", "api.user.send_password_reset.send.app_error", nil, "err="+err.Message, http.StatusInternalServerError)
  1199  	}
  1200  
  1201  	return true, nil
  1202  }
  1203  
  1204  func (a *App) CreatePasswordRecoveryToken(userId string) (*model.Token, *model.AppError) {
  1205  	token := model.NewToken(TOKEN_TYPE_PASSWORD_RECOVERY, userId)
  1206  
  1207  	if result := <-a.Srv.Store.Token().Save(token); result.Err != nil {
  1208  		return nil, result.Err
  1209  	}
  1210  
  1211  	return token, nil
  1212  }
  1213  
  1214  func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) {
  1215  	if result := <-a.Srv.Store.Token().GetByToken(token); result.Err != nil {
  1216  		return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.invalid_link.app_error", nil, result.Err.Error(), http.StatusBadRequest)
  1217  	} else {
  1218  		token := result.Data.(*model.Token)
  1219  		if token.Type != TOKEN_TYPE_PASSWORD_RECOVERY {
  1220  			return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.broken_token.app_error", nil, "", http.StatusBadRequest)
  1221  		}
  1222  		return token, nil
  1223  	}
  1224  }
  1225  
  1226  func (a *App) DeleteToken(token *model.Token) *model.AppError {
  1227  	if result := <-a.Srv.Store.Token().Delete(token.Token); result.Err != nil {
  1228  		return result.Err
  1229  	}
  1230  
  1231  	return nil
  1232  }
  1233  
  1234  func (a *App) UpdateUserRoles(userId string, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError) {
  1235  	var user *model.User
  1236  	var err *model.AppError
  1237  	if user, err = a.GetUser(userId); err != nil {
  1238  		err.StatusCode = http.StatusBadRequest
  1239  		return nil, err
  1240  	}
  1241  
  1242  	user.Roles = newRoles
  1243  	uchan := a.Srv.Store.User().Update(user, true)
  1244  	schan := a.Srv.Store.Session().UpdateRoles(user.Id, newRoles)
  1245  
  1246  	var ruser *model.User
  1247  	if result := <-uchan; result.Err != nil {
  1248  		return nil, result.Err
  1249  	} else {
  1250  		ruser = result.Data.([2]*model.User)[0]
  1251  	}
  1252  
  1253  	if result := <-schan; result.Err != nil {
  1254  		// soft error since the user roles were still updated
  1255  		l4g.Error(result.Err)
  1256  	}
  1257  
  1258  	a.ClearSessionCacheForUser(user.Id)
  1259  
  1260  	if sendWebSocketEvent {
  1261  		message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_USER_ROLE_UPDATED, "", "", user.Id, nil)
  1262  		message.Add("user_id", user.Id)
  1263  		message.Add("roles", newRoles)
  1264  		a.Publish(message)
  1265  	}
  1266  
  1267  	return ruser, nil
  1268  }
  1269  
  1270  func (a *App) PermanentDeleteUser(user *model.User) *model.AppError {
  1271  	l4g.Warn(utils.T("api.user.permanent_delete_user.attempting.warn"), user.Email, user.Id)
  1272  	if user.IsInRole(model.SYSTEM_ADMIN_ROLE_ID) {
  1273  		l4g.Warn(utils.T("api.user.permanent_delete_user.system_admin.warn"), user.Email)
  1274  	}
  1275  
  1276  	if _, err := a.UpdateActive(user, false); err != nil {
  1277  		return err
  1278  	}
  1279  
  1280  	if result := <-a.Srv.Store.Session().PermanentDeleteSessionsByUser(user.Id); result.Err != nil {
  1281  		return result.Err
  1282  	}
  1283  
  1284  	if result := <-a.Srv.Store.UserAccessToken().DeleteAllForUser(user.Id); result.Err != nil {
  1285  		return result.Err
  1286  	}
  1287  
  1288  	if result := <-a.Srv.Store.OAuth().PermanentDeleteAuthDataByUser(user.Id); result.Err != nil {
  1289  		return result.Err
  1290  	}
  1291  
  1292  	if result := <-a.Srv.Store.Webhook().PermanentDeleteIncomingByUser(user.Id); result.Err != nil {
  1293  		return result.Err
  1294  	}
  1295  
  1296  	if result := <-a.Srv.Store.Webhook().PermanentDeleteOutgoingByUser(user.Id); result.Err != nil {
  1297  		return result.Err
  1298  	}
  1299  
  1300  	if result := <-a.Srv.Store.Command().PermanentDeleteByUser(user.Id); result.Err != nil {
  1301  		return result.Err
  1302  	}
  1303  
  1304  	if result := <-a.Srv.Store.Preference().PermanentDeleteByUser(user.Id); result.Err != nil {
  1305  		return result.Err
  1306  	}
  1307  
  1308  	if result := <-a.Srv.Store.Channel().PermanentDeleteMembersByUser(user.Id); result.Err != nil {
  1309  		return result.Err
  1310  	}
  1311  
  1312  	if result := <-a.Srv.Store.Post().PermanentDeleteByUser(user.Id); result.Err != nil {
  1313  		return result.Err
  1314  	}
  1315  
  1316  	if result := <-a.Srv.Store.User().PermanentDelete(user.Id); result.Err != nil {
  1317  		return result.Err
  1318  	}
  1319  
  1320  	if result := <-a.Srv.Store.Audit().PermanentDeleteByUser(user.Id); result.Err != nil {
  1321  		return result.Err
  1322  	}
  1323  
  1324  	if result := <-a.Srv.Store.Team().RemoveAllMembersByUser(user.Id); result.Err != nil {
  1325  		return result.Err
  1326  	}
  1327  
  1328  	l4g.Warn(utils.T("api.user.permanent_delete_user.deleted.warn"), user.Email, user.Id)
  1329  
  1330  	return nil
  1331  }
  1332  
  1333  func (a *App) PermanentDeleteAllUsers() *model.AppError {
  1334  	if result := <-a.Srv.Store.User().GetAll(); result.Err != nil {
  1335  		return result.Err
  1336  	} else {
  1337  		users := result.Data.([]*model.User)
  1338  		for _, user := range users {
  1339  			a.PermanentDeleteUser(user)
  1340  		}
  1341  	}
  1342  
  1343  	return nil
  1344  }
  1345  
  1346  func (a *App) SendEmailVerification(user *model.User) *model.AppError {
  1347  	token, err := a.CreateVerifyEmailToken(user.Id)
  1348  	if err != nil {
  1349  		return err
  1350  	}
  1351  
  1352  	if _, err := a.GetStatus(user.Id); err != nil {
  1353  		return a.SendVerifyEmail(user.Email, user.Locale, a.GetSiteURL(), token.Token)
  1354  	} else {
  1355  		return a.SendEmailChangeVerifyEmail(user.Email, user.Locale, a.GetSiteURL(), token.Token)
  1356  	}
  1357  }
  1358  
  1359  func (a *App) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError {
  1360  	var token *model.Token
  1361  	var err *model.AppError
  1362  	if token, err = a.GetVerifyEmailToken(userSuppliedTokenString); err != nil {
  1363  		return err
  1364  	} else {
  1365  		if model.GetMillis()-token.CreateAt >= PASSWORD_RECOVER_EXPIRY_TIME {
  1366  			return model.NewAppError("resetPassword", "api.user.reset_password.link_expired.app_error", nil, "", http.StatusBadRequest)
  1367  		}
  1368  		if err := a.VerifyUserEmail(token.Extra); err != nil {
  1369  			return err
  1370  		}
  1371  		if err := a.DeleteToken(token); err != nil {
  1372  			l4g.Error(err.Error())
  1373  		}
  1374  	}
  1375  
  1376  	return nil
  1377  }
  1378  
  1379  func (a *App) CreateVerifyEmailToken(userId string) (*model.Token, *model.AppError) {
  1380  	token := model.NewToken(TOKEN_TYPE_VERIFY_EMAIL, userId)
  1381  
  1382  	if result := <-a.Srv.Store.Token().Save(token); result.Err != nil {
  1383  		return nil, result.Err
  1384  	}
  1385  
  1386  	return token, nil
  1387  }
  1388  
  1389  func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) {
  1390  	if result := <-a.Srv.Store.Token().GetByToken(token); result.Err != nil {
  1391  		return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.bad_link.app_error", nil, result.Err.Error(), http.StatusBadRequest)
  1392  	} else {
  1393  		token := result.Data.(*model.Token)
  1394  		if token.Type != TOKEN_TYPE_VERIFY_EMAIL {
  1395  			return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.broken_token.app_error", nil, "", http.StatusBadRequest)
  1396  		}
  1397  		return token, nil
  1398  	}
  1399  }
  1400  
  1401  func (a *App) VerifyUserEmail(userId string) *model.AppError {
  1402  	return (<-a.Srv.Store.User().VerifyEmail(userId)).Err
  1403  }
  1404  
  1405  func (a *App) SearchUsers(props *model.UserSearch, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) {
  1406  	if props.WithoutTeam {
  1407  		return a.SearchUsersWithoutTeam(props.Term, searchOptions, asAdmin)
  1408  	} else if props.InChannelId != "" {
  1409  		return a.SearchUsersInChannel(props.InChannelId, props.Term, searchOptions, asAdmin)
  1410  	} else if props.NotInChannelId != "" {
  1411  		return a.SearchUsersNotInChannel(props.TeamId, props.NotInChannelId, props.Term, searchOptions, asAdmin)
  1412  	} else if props.NotInTeamId != "" {
  1413  		return a.SearchUsersNotInTeam(props.NotInTeamId, props.Term, searchOptions, asAdmin)
  1414  	} else {
  1415  		return a.SearchUsersInTeam(props.TeamId, props.Term, searchOptions, asAdmin)
  1416  	}
  1417  }
  1418  
  1419  func (a *App) SearchUsersInChannel(channelId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) {
  1420  	if result := <-a.Srv.Store.User().SearchInChannel(channelId, term, searchOptions); result.Err != nil {
  1421  		return nil, result.Err
  1422  	} else {
  1423  		users := result.Data.([]*model.User)
  1424  
  1425  		for _, user := range users {
  1426  			a.SanitizeProfile(user, asAdmin)
  1427  		}
  1428  
  1429  		return users, nil
  1430  	}
  1431  }
  1432  
  1433  func (a *App) SearchUsersNotInChannel(teamId string, channelId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) {
  1434  	if result := <-a.Srv.Store.User().SearchNotInChannel(teamId, channelId, term, searchOptions); result.Err != nil {
  1435  		return nil, result.Err
  1436  	} else {
  1437  		users := result.Data.([]*model.User)
  1438  
  1439  		for _, user := range users {
  1440  			a.SanitizeProfile(user, asAdmin)
  1441  		}
  1442  
  1443  		return users, nil
  1444  	}
  1445  }
  1446  
  1447  func (a *App) SearchUsersInTeam(teamId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) {
  1448  	if result := <-a.Srv.Store.User().Search(teamId, term, searchOptions); result.Err != nil {
  1449  		return nil, result.Err
  1450  	} else {
  1451  		users := result.Data.([]*model.User)
  1452  
  1453  		for _, user := range users {
  1454  			a.SanitizeProfile(user, asAdmin)
  1455  		}
  1456  
  1457  		return users, nil
  1458  	}
  1459  }
  1460  
  1461  func (a *App) SearchUsersNotInTeam(notInTeamId string, term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) {
  1462  	if result := <-a.Srv.Store.User().SearchNotInTeam(notInTeamId, term, searchOptions); result.Err != nil {
  1463  		return nil, result.Err
  1464  	} else {
  1465  		users := result.Data.([]*model.User)
  1466  
  1467  		for _, user := range users {
  1468  			a.SanitizeProfile(user, asAdmin)
  1469  		}
  1470  
  1471  		return users, nil
  1472  	}
  1473  }
  1474  
  1475  func (a *App) SearchUsersWithoutTeam(term string, searchOptions map[string]bool, asAdmin bool) ([]*model.User, *model.AppError) {
  1476  	if result := <-a.Srv.Store.User().SearchWithoutTeam(term, searchOptions); result.Err != nil {
  1477  		return nil, result.Err
  1478  	} else {
  1479  		users := result.Data.([]*model.User)
  1480  
  1481  		for _, user := range users {
  1482  			a.SanitizeProfile(user, asAdmin)
  1483  		}
  1484  
  1485  		return users, nil
  1486  	}
  1487  }
  1488  
  1489  func (a *App) AutocompleteUsersInChannel(teamId string, channelId string, term string, searchOptions map[string]bool, asAdmin bool) (*model.UserAutocompleteInChannel, *model.AppError) {
  1490  	uchan := a.Srv.Store.User().SearchInChannel(channelId, term, searchOptions)
  1491  	nuchan := a.Srv.Store.User().SearchNotInChannel(teamId, channelId, term, searchOptions)
  1492  
  1493  	autocomplete := &model.UserAutocompleteInChannel{}
  1494  
  1495  	if result := <-uchan; result.Err != nil {
  1496  		return nil, result.Err
  1497  	} else {
  1498  		users := result.Data.([]*model.User)
  1499  
  1500  		for _, user := range users {
  1501  			a.SanitizeProfile(user, asAdmin)
  1502  		}
  1503  
  1504  		autocomplete.InChannel = users
  1505  	}
  1506  
  1507  	if result := <-nuchan; result.Err != nil {
  1508  		return nil, result.Err
  1509  	} else {
  1510  		users := result.Data.([]*model.User)
  1511  
  1512  		for _, user := range users {
  1513  			a.SanitizeProfile(user, asAdmin)
  1514  		}
  1515  
  1516  		autocomplete.OutOfChannel = users
  1517  	}
  1518  
  1519  	return autocomplete, nil
  1520  }
  1521  
  1522  func (a *App) AutocompleteUsersInTeam(teamId string, term string, searchOptions map[string]bool, asAdmin bool) (*model.UserAutocompleteInTeam, *model.AppError) {
  1523  	autocomplete := &model.UserAutocompleteInTeam{}
  1524  
  1525  	if result := <-a.Srv.Store.User().Search(teamId, term, searchOptions); result.Err != nil {
  1526  		return nil, result.Err
  1527  	} else {
  1528  		users := result.Data.([]*model.User)
  1529  
  1530  		for _, user := range users {
  1531  			a.SanitizeProfile(user, asAdmin)
  1532  		}
  1533  
  1534  		autocomplete.InTeam = users
  1535  	}
  1536  
  1537  	return autocomplete, nil
  1538  }
  1539  
  1540  func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provider einterfaces.OauthProvider, service string) *model.AppError {
  1541  	oauthUser := provider.GetUserFromJson(userData)
  1542  
  1543  	if oauthUser == nil {
  1544  		return model.NewAppError("UpdateOAuthUserAttrs", "api.user.update_oauth_user_attrs.get_user.app_error", map[string]interface{}{"Service": service}, "", http.StatusBadRequest)
  1545  	}
  1546  
  1547  	userAttrsChanged := false
  1548  
  1549  	if oauthUser.Username != user.Username {
  1550  		if existingUser, _ := a.GetUserByUsername(oauthUser.Username); existingUser == nil {
  1551  			user.Username = oauthUser.Username
  1552  			userAttrsChanged = true
  1553  		}
  1554  	}
  1555  
  1556  	if oauthUser.GetFullName() != user.GetFullName() {
  1557  		user.FirstName = oauthUser.FirstName
  1558  		user.LastName = oauthUser.LastName
  1559  		userAttrsChanged = true
  1560  	}
  1561  
  1562  	if oauthUser.Email != user.Email {
  1563  		if existingUser, _ := a.GetUserByEmail(oauthUser.Email); existingUser == nil {
  1564  			user.Email = oauthUser.Email
  1565  			userAttrsChanged = true
  1566  		}
  1567  	}
  1568  
  1569  	if user.DeleteAt > 0 {
  1570  		// Make sure they are not disabled
  1571  		user.DeleteAt = 0
  1572  		userAttrsChanged = true
  1573  	}
  1574  
  1575  	if userAttrsChanged {
  1576  		var result store.StoreResult
  1577  		if result = <-a.Srv.Store.User().Update(user, true); result.Err != nil {
  1578  			return result.Err
  1579  		}
  1580  
  1581  		user = result.Data.([2]*model.User)[0]
  1582  		a.InvalidateCacheForUser(user.Id)
  1583  	}
  1584  
  1585  	return nil
  1586  }