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