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