github.com/gigforks/mattermost-server@v4.9.1-0.20180619094218-800d97fa55d0+incompatible/api4/user_test.go (about) 1 // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package api4 5 6 import ( 7 "net/http" 8 "strconv" 9 "testing" 10 "time" 11 12 "github.com/mattermost/mattermost-server/app" 13 "github.com/mattermost/mattermost-server/model" 14 "github.com/mattermost/mattermost-server/store" 15 "github.com/stretchr/testify/assert" 16 "github.com/stretchr/testify/require" 17 ) 18 19 func TestCreateUser(t *testing.T) { 20 th := Setup().InitBasic().InitSystemAdmin() 21 defer th.TearDown() 22 Client := th.Client 23 AdminClient := th.SystemAdminClient 24 25 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 26 27 ruser, resp := Client.CreateUser(&user) 28 CheckNoError(t, resp) 29 CheckCreatedStatus(t, resp) 30 31 Client.Login(user.Email, user.Password) 32 33 if ruser.Nickname != user.Nickname { 34 t.Fatal("nickname didn't match") 35 } 36 37 if ruser.Roles != model.SYSTEM_USER_ROLE_ID { 38 t.Log(ruser.Roles) 39 t.Fatal("did not clear roles") 40 } 41 42 CheckUserSanitization(t, ruser) 43 44 _, resp = Client.CreateUser(ruser) 45 CheckBadRequestStatus(t, resp) 46 47 ruser.Id = "" 48 ruser.Username = GenerateTestUsername() 49 ruser.Password = "passwd1" 50 _, resp = Client.CreateUser(ruser) 51 CheckErrorMessage(t, resp, "store.sql_user.save.email_exists.app_error") 52 CheckBadRequestStatus(t, resp) 53 54 ruser.Email = th.GenerateTestEmail() 55 ruser.Username = user.Username 56 _, resp = Client.CreateUser(ruser) 57 CheckErrorMessage(t, resp, "store.sql_user.save.username_exists.app_error") 58 CheckBadRequestStatus(t, resp) 59 60 ruser.Email = "" 61 _, resp = Client.CreateUser(ruser) 62 CheckErrorMessage(t, resp, "model.user.is_valid.email.app_error") 63 CheckBadRequestStatus(t, resp) 64 65 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) 66 th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false }) 67 68 user2 := &model.User{Email: th.GenerateTestEmail(), Password: "Password1", Username: GenerateTestUsername()} 69 _, resp = AdminClient.CreateUser(user2) 70 CheckNoError(t, resp) 71 72 if r, err := Client.DoApiPost("/users", "garbage"); err == nil { 73 t.Fatal("should have errored") 74 } else { 75 if r.StatusCode != http.StatusBadRequest { 76 t.Log("actual: " + strconv.Itoa(r.StatusCode)) 77 t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) 78 t.Fatal("wrong status code") 79 } 80 } 81 } 82 83 func TestCreateUserWithToken(t *testing.T) { 84 th := Setup().InitBasic().InitSystemAdmin() 85 defer th.TearDown() 86 Client := th.Client 87 88 t.Run("CreateWithTokenHappyPath", func(t *testing.T) { 89 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 90 token := model.NewToken( 91 app.TOKEN_TYPE_TEAM_INVITATION, 92 model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), 93 ) 94 <-th.App.Srv.Store.Token().Save(token) 95 96 ruser, resp := Client.CreateUserWithToken(&user, token.Token) 97 CheckNoError(t, resp) 98 CheckCreatedStatus(t, resp) 99 100 Client.Login(user.Email, user.Password) 101 if ruser.Nickname != user.Nickname { 102 t.Fatal("nickname didn't match") 103 } 104 if ruser.Roles != model.SYSTEM_USER_ROLE_ID { 105 t.Log(ruser.Roles) 106 t.Fatal("did not clear roles") 107 } 108 CheckUserSanitization(t, ruser) 109 if result := <-th.App.Srv.Store.Token().GetByToken(token.Token); result.Err == nil { 110 t.Fatal("The token must be deleted after be used") 111 } 112 113 if result := <-th.App.Srv.Store.Token().GetByToken(token.Token); result.Err == nil { 114 t.Fatal("The token must be deleted after be used") 115 } 116 117 if teams, err := th.App.GetTeamsForUser(ruser.Id); err != nil || len(teams) == 0 { 118 t.Fatal("The user must have teams") 119 } else if teams[0].Id != th.BasicTeam.Id { 120 t.Fatal("The user joined team must be the team provided.") 121 } 122 }) 123 124 t.Run("NoToken", func(t *testing.T) { 125 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 126 token := model.NewToken( 127 app.TOKEN_TYPE_TEAM_INVITATION, 128 model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), 129 ) 130 <-th.App.Srv.Store.Token().Save(token) 131 defer th.App.DeleteToken(token) 132 133 _, resp := Client.CreateUserWithToken(&user, "") 134 CheckBadRequestStatus(t, resp) 135 CheckErrorMessage(t, resp, "api.user.create_user.missing_token.app_error") 136 }) 137 138 t.Run("TokenExpired", func(t *testing.T) { 139 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 140 timeNow := time.Now() 141 past49Hours := timeNow.Add(-49*time.Hour).UnixNano() / int64(time.Millisecond) 142 token := model.NewToken( 143 app.TOKEN_TYPE_TEAM_INVITATION, 144 model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), 145 ) 146 token.CreateAt = past49Hours 147 <-th.App.Srv.Store.Token().Save(token) 148 defer th.App.DeleteToken(token) 149 150 _, resp := Client.CreateUserWithToken(&user, token.Token) 151 CheckBadRequestStatus(t, resp) 152 CheckErrorMessage(t, resp, "api.user.create_user.signup_link_expired.app_error") 153 }) 154 155 t.Run("WrongToken", func(t *testing.T) { 156 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 157 158 _, resp := Client.CreateUserWithToken(&user, "wrong") 159 CheckBadRequestStatus(t, resp) 160 CheckErrorMessage(t, resp, "api.user.create_user.signup_link_invalid.app_error") 161 }) 162 163 t.Run("EnableUserCreationDisable", func(t *testing.T) { 164 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 165 166 token := model.NewToken( 167 app.TOKEN_TYPE_TEAM_INVITATION, 168 model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), 169 ) 170 <-th.App.Srv.Store.Token().Save(token) 171 defer th.App.DeleteToken(token) 172 173 th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false }) 174 175 _, resp := Client.CreateUserWithToken(&user, token.Token) 176 CheckNotImplementedStatus(t, resp) 177 CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error") 178 179 th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = true }) 180 }) 181 182 t.Run("EnableOpenServerDisable", func(t *testing.T) { 183 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 184 185 token := model.NewToken( 186 app.TOKEN_TYPE_TEAM_INVITATION, 187 model.MapToJson(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), 188 ) 189 <-th.App.Srv.Store.Token().Save(token) 190 191 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) 192 193 ruser, resp := Client.CreateUserWithToken(&user, token.Token) 194 CheckNoError(t, resp) 195 CheckCreatedStatus(t, resp) 196 197 Client.Login(user.Email, user.Password) 198 if ruser.Nickname != user.Nickname { 199 t.Fatal("nickname didn't match") 200 } 201 if ruser.Roles != model.SYSTEM_USER_ROLE_ID { 202 t.Log(ruser.Roles) 203 t.Fatal("did not clear roles") 204 } 205 CheckUserSanitization(t, ruser) 206 if result := <-th.App.Srv.Store.Token().GetByToken(token.Token); result.Err == nil { 207 t.Fatal("The token must be deleted after be used") 208 } 209 }) 210 } 211 212 func TestCreateUserWithInviteId(t *testing.T) { 213 th := Setup().InitBasic().InitSystemAdmin() 214 defer th.TearDown() 215 Client := th.Client 216 AdminClient := th.SystemAdminClient 217 218 t.Run("CreateWithInviteIdHappyPath", func(t *testing.T) { 219 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 220 221 inviteId := th.BasicTeam.InviteId 222 223 ruser, resp := Client.CreateUserWithInviteId(&user, inviteId) 224 CheckNoError(t, resp) 225 CheckCreatedStatus(t, resp) 226 227 Client.Login(user.Email, user.Password) 228 if ruser.Nickname != user.Nickname { 229 t.Fatal("nickname didn't match") 230 } 231 if ruser.Roles != model.SYSTEM_USER_ROLE_ID { 232 t.Log(ruser.Roles) 233 t.Fatal("did not clear roles") 234 } 235 CheckUserSanitization(t, ruser) 236 }) 237 238 t.Run("WrongInviteId", func(t *testing.T) { 239 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 240 241 inviteId := model.NewId() 242 243 _, resp := Client.CreateUserWithInviteId(&user, inviteId) 244 CheckNotFoundStatus(t, resp) 245 CheckErrorMessage(t, resp, "store.sql_team.get_by_invite_id.find.app_error") 246 }) 247 248 t.Run("NoInviteId", func(t *testing.T) { 249 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 250 251 _, resp := Client.CreateUserWithInviteId(&user, "") 252 CheckBadRequestStatus(t, resp) 253 CheckErrorMessage(t, resp, "api.user.create_user.missing_invite_id.app_error") 254 }) 255 256 t.Run("ExpiredInviteId", func(t *testing.T) { 257 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 258 259 inviteId := th.BasicTeam.InviteId 260 261 th.BasicTeam.InviteId = model.NewId() 262 _, resp := AdminClient.UpdateTeam(th.BasicTeam) 263 CheckNoError(t, resp) 264 265 _, resp = Client.CreateUserWithInviteId(&user, inviteId) 266 CheckNotFoundStatus(t, resp) 267 CheckErrorMessage(t, resp, "store.sql_team.get_by_invite_id.find.app_error") 268 }) 269 270 t.Run("EnableUserCreationDisable", func(t *testing.T) { 271 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 272 273 th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = false }) 274 275 inviteId := th.BasicTeam.InviteId 276 277 _, resp := Client.CreateUserWithInviteId(&user, inviteId) 278 CheckNotImplementedStatus(t, resp) 279 CheckErrorMessage(t, resp, "api.user.create_user.signup_email_disabled.app_error") 280 281 th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.EnableUserCreation = true }) 282 }) 283 284 t.Run("EnableOpenServerDisable", func(t *testing.T) { 285 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Corey Hulen", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 286 287 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = false }) 288 289 inviteId := th.BasicTeam.InviteId 290 291 ruser, resp := Client.CreateUserWithInviteId(&user, inviteId) 292 CheckNoError(t, resp) 293 CheckCreatedStatus(t, resp) 294 295 Client.Login(user.Email, user.Password) 296 if ruser.Nickname != user.Nickname { 297 t.Fatal("nickname didn't match") 298 } 299 if ruser.Roles != model.SYSTEM_USER_ROLE_ID { 300 t.Log(ruser.Roles) 301 t.Fatal("did not clear roles") 302 } 303 CheckUserSanitization(t, ruser) 304 }) 305 306 } 307 308 func TestGetMe(t *testing.T) { 309 th := Setup().InitBasic() 310 defer th.TearDown() 311 Client := th.Client 312 313 ruser, resp := Client.GetMe("") 314 CheckNoError(t, resp) 315 316 if ruser.Id != th.BasicUser.Id { 317 t.Fatal("wrong user") 318 } 319 320 Client.Logout() 321 _, resp = Client.GetMe("") 322 CheckUnauthorizedStatus(t, resp) 323 } 324 325 func TestGetUser(t *testing.T) { 326 th := Setup().InitBasic().InitSystemAdmin() 327 defer th.TearDown() 328 Client := th.Client 329 330 user := th.CreateUser() 331 user.Props = map[string]string{"testpropkey": "testpropvalue"} 332 333 th.App.UpdateUser(user, false) 334 335 ruser, resp := Client.GetUser(user.Id, "") 336 CheckNoError(t, resp) 337 CheckUserSanitization(t, ruser) 338 339 if ruser.Email != user.Email { 340 t.Fatal("emails did not match") 341 } 342 343 assert.NotNil(t, ruser.Props) 344 assert.Equal(t, ruser.Props["testpropkey"], "testpropvalue") 345 346 ruser, resp = Client.GetUser(user.Id, resp.Etag) 347 CheckEtag(t, ruser, resp) 348 349 _, resp = Client.GetUser("junk", "") 350 CheckBadRequestStatus(t, resp) 351 352 _, resp = Client.GetUser(model.NewId(), "") 353 CheckNotFoundStatus(t, resp) 354 355 // Check against privacy config settings 356 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) 357 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) 358 359 ruser, resp = Client.GetUser(user.Id, "") 360 CheckNoError(t, resp) 361 362 if ruser.Email != "" { 363 t.Fatal("email should be blank") 364 } 365 if ruser.FirstName != "" { 366 t.Fatal("first name should be blank") 367 } 368 if ruser.LastName != "" { 369 t.Fatal("last name should be blank") 370 } 371 372 Client.Logout() 373 _, resp = Client.GetUser(user.Id, "") 374 CheckUnauthorizedStatus(t, resp) 375 376 // System admins should ignore privacy settings 377 ruser, resp = th.SystemAdminClient.GetUser(user.Id, resp.Etag) 378 if ruser.Email == "" { 379 t.Fatal("email should not be blank") 380 } 381 if ruser.FirstName == "" { 382 t.Fatal("first name should not be blank") 383 } 384 if ruser.LastName == "" { 385 t.Fatal("last name should not be blank") 386 } 387 } 388 389 func TestGetUserByUsername(t *testing.T) { 390 th := Setup().InitBasic().InitSystemAdmin() 391 defer th.TearDown() 392 Client := th.Client 393 394 user := th.BasicUser 395 396 ruser, resp := Client.GetUserByUsername(user.Username, "") 397 CheckNoError(t, resp) 398 CheckUserSanitization(t, ruser) 399 400 if ruser.Email != user.Email { 401 t.Fatal("emails did not match") 402 } 403 404 ruser, resp = Client.GetUserByUsername(user.Username, resp.Etag) 405 CheckEtag(t, ruser, resp) 406 407 _, resp = Client.GetUserByUsername(GenerateTestUsername(), "") 408 CheckNotFoundStatus(t, resp) 409 410 // Check against privacy config settings 411 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) 412 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) 413 414 ruser, resp = Client.GetUserByUsername(user.Username, "") 415 CheckNoError(t, resp) 416 417 if ruser.Email != "" { 418 t.Fatal("email should be blank") 419 } 420 if ruser.FirstName != "" { 421 t.Fatal("first name should be blank") 422 } 423 if ruser.LastName != "" { 424 t.Fatal("last name should be blank") 425 } 426 427 Client.Logout() 428 _, resp = Client.GetUserByUsername(user.Username, "") 429 CheckUnauthorizedStatus(t, resp) 430 431 // System admins should ignore privacy settings 432 ruser, resp = th.SystemAdminClient.GetUserByUsername(user.Username, resp.Etag) 433 if ruser.Email == "" { 434 t.Fatal("email should not be blank") 435 } 436 if ruser.FirstName == "" { 437 t.Fatal("first name should not be blank") 438 } 439 if ruser.LastName == "" { 440 t.Fatal("last name should not be blank") 441 } 442 } 443 444 func TestGetUserByEmail(t *testing.T) { 445 th := Setup().InitBasic().InitSystemAdmin() 446 defer th.TearDown() 447 Client := th.Client 448 449 user := th.CreateUser() 450 451 ruser, resp := Client.GetUserByEmail(user.Email, "") 452 CheckNoError(t, resp) 453 CheckUserSanitization(t, ruser) 454 455 if ruser.Email != user.Email { 456 t.Fatal("emails did not match") 457 } 458 459 ruser, resp = Client.GetUserByEmail(user.Email, resp.Etag) 460 CheckEtag(t, ruser, resp) 461 462 _, resp = Client.GetUserByEmail(GenerateTestUsername(), "") 463 CheckBadRequestStatus(t, resp) 464 465 _, resp = Client.GetUserByEmail(th.GenerateTestEmail(), "") 466 CheckNotFoundStatus(t, resp) 467 468 // Check against privacy config settings 469 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) 470 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) 471 472 ruser, resp = Client.GetUserByEmail(user.Email, "") 473 CheckNoError(t, resp) 474 475 if ruser.Email != "" { 476 t.Fatal("email should be blank") 477 } 478 if ruser.FirstName != "" { 479 t.Fatal("first name should be blank") 480 } 481 if ruser.LastName != "" { 482 t.Fatal("last name should be blank") 483 } 484 485 Client.Logout() 486 _, resp = Client.GetUserByEmail(user.Email, "") 487 CheckUnauthorizedStatus(t, resp) 488 489 // System admins should ignore privacy settings 490 ruser, resp = th.SystemAdminClient.GetUserByEmail(user.Email, resp.Etag) 491 if ruser.Email == "" { 492 t.Fatal("email should not be blank") 493 } 494 if ruser.FirstName == "" { 495 t.Fatal("first name should not be blank") 496 } 497 if ruser.LastName == "" { 498 t.Fatal("last name should not be blank") 499 } 500 } 501 502 func TestSearchUsers(t *testing.T) { 503 th := Setup().InitBasic().InitSystemAdmin() 504 defer th.TearDown() 505 Client := th.Client 506 507 search := &model.UserSearch{Term: th.BasicUser.Username} 508 509 users, resp := Client.SearchUsers(search) 510 CheckNoError(t, resp) 511 512 if !findUserInList(th.BasicUser.Id, users) { 513 t.Fatal("should have found user") 514 } 515 516 _, err := th.App.UpdateNonSSOUserActive(th.BasicUser2.Id, false) 517 if err != nil { 518 t.Fatal(err) 519 } 520 521 search.Term = th.BasicUser2.Username 522 search.AllowInactive = false 523 524 users, resp = Client.SearchUsers(search) 525 CheckNoError(t, resp) 526 527 if findUserInList(th.BasicUser2.Id, users) { 528 t.Fatal("should not have found user") 529 } 530 531 search.AllowInactive = true 532 533 users, resp = Client.SearchUsers(search) 534 CheckNoError(t, resp) 535 536 if !findUserInList(th.BasicUser2.Id, users) { 537 t.Fatal("should have found user") 538 } 539 540 search.Term = th.BasicUser.Username 541 search.AllowInactive = false 542 search.TeamId = th.BasicTeam.Id 543 544 users, resp = Client.SearchUsers(search) 545 CheckNoError(t, resp) 546 547 if !findUserInList(th.BasicUser.Id, users) { 548 t.Fatal("should have found user") 549 } 550 551 search.NotInChannelId = th.BasicChannel.Id 552 553 users, resp = Client.SearchUsers(search) 554 CheckNoError(t, resp) 555 556 if findUserInList(th.BasicUser.Id, users) { 557 t.Fatal("should not have found user") 558 } 559 560 search.TeamId = "" 561 search.NotInChannelId = "" 562 search.InChannelId = th.BasicChannel.Id 563 564 users, resp = Client.SearchUsers(search) 565 CheckNoError(t, resp) 566 567 if !findUserInList(th.BasicUser.Id, users) { 568 t.Fatal("should have found user") 569 } 570 571 search.InChannelId = "" 572 search.NotInChannelId = th.BasicChannel.Id 573 _, resp = Client.SearchUsers(search) 574 CheckBadRequestStatus(t, resp) 575 576 search.NotInChannelId = model.NewId() 577 search.TeamId = model.NewId() 578 _, resp = Client.SearchUsers(search) 579 CheckForbiddenStatus(t, resp) 580 581 search.NotInChannelId = "" 582 search.TeamId = model.NewId() 583 _, resp = Client.SearchUsers(search) 584 CheckForbiddenStatus(t, resp) 585 586 search.InChannelId = model.NewId() 587 search.TeamId = "" 588 _, resp = Client.SearchUsers(search) 589 CheckForbiddenStatus(t, resp) 590 591 // Test search for users not in any team 592 search.TeamId = "" 593 search.NotInChannelId = "" 594 search.InChannelId = "" 595 search.NotInTeamId = th.BasicTeam.Id 596 597 users, resp = Client.SearchUsers(search) 598 CheckNoError(t, resp) 599 600 if findUserInList(th.BasicUser.Id, users) { 601 t.Fatal("should not have found user") 602 } 603 604 oddUser := th.CreateUser() 605 search.Term = oddUser.Username 606 607 users, resp = Client.SearchUsers(search) 608 CheckNoError(t, resp) 609 610 if !findUserInList(oddUser.Id, users) { 611 t.Fatal("should have found user") 612 } 613 614 _, resp = th.SystemAdminClient.AddTeamMember(th.BasicTeam.Id, oddUser.Id) 615 CheckNoError(t, resp) 616 617 users, resp = Client.SearchUsers(search) 618 CheckNoError(t, resp) 619 620 if findUserInList(oddUser.Id, users) { 621 t.Fatal("should not have found user") 622 } 623 624 search.NotInTeamId = model.NewId() 625 _, resp = Client.SearchUsers(search) 626 CheckForbiddenStatus(t, resp) 627 628 search.Term = th.BasicUser.Username 629 630 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowEmailAddress = false }) 631 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) 632 633 _, err = th.App.UpdateNonSSOUserActive(th.BasicUser2.Id, true) 634 if err != nil { 635 t.Fatal(err) 636 } 637 638 search.InChannelId = "" 639 search.NotInTeamId = "" 640 search.Term = th.BasicUser2.Email 641 users, resp = Client.SearchUsers(search) 642 CheckNoError(t, resp) 643 644 if findUserInList(th.BasicUser2.Id, users) { 645 t.Fatal("should not have found user") 646 } 647 648 search.Term = th.BasicUser2.FirstName 649 users, resp = Client.SearchUsers(search) 650 CheckNoError(t, resp) 651 652 if findUserInList(th.BasicUser2.Id, users) { 653 t.Fatal("should not have found user") 654 } 655 656 search.Term = th.BasicUser2.LastName 657 users, resp = Client.SearchUsers(search) 658 CheckNoError(t, resp) 659 660 if findUserInList(th.BasicUser2.Id, users) { 661 t.Fatal("should not have found user") 662 } 663 664 search.Term = th.BasicUser.FirstName 665 search.InChannelId = th.BasicChannel.Id 666 search.NotInChannelId = th.BasicChannel.Id 667 search.TeamId = th.BasicTeam.Id 668 users, resp = th.SystemAdminClient.SearchUsers(search) 669 CheckNoError(t, resp) 670 671 if !findUserInList(th.BasicUser.Id, users) { 672 t.Fatal("should have found user") 673 } 674 } 675 676 func findUserInList(id string, users []*model.User) bool { 677 for _, user := range users { 678 if user.Id == id { 679 return true 680 } 681 } 682 return false 683 } 684 685 func TestAutocompleteUsers(t *testing.T) { 686 th := Setup().InitBasic().InitSystemAdmin() 687 defer th.TearDown() 688 Client := th.Client 689 teamId := th.BasicTeam.Id 690 channelId := th.BasicChannel.Id 691 username := th.BasicUser.Username 692 693 rusers, resp := Client.AutocompleteUsersInChannel(teamId, channelId, username, "") 694 CheckNoError(t, resp) 695 696 if len(rusers.Users) != 1 { 697 t.Fatal("should have returned 1 user") 698 } 699 700 rusers, resp = Client.AutocompleteUsersInChannel(teamId, channelId, "amazonses", "") 701 CheckNoError(t, resp) 702 if len(rusers.Users) != 0 { 703 t.Fatal("should have returned 0 users") 704 } 705 706 rusers, resp = Client.AutocompleteUsersInChannel(teamId, channelId, "", "") 707 CheckNoError(t, resp) 708 if len(rusers.Users) < 2 { 709 t.Fatal("should have many users") 710 } 711 712 rusers, resp = Client.AutocompleteUsersInChannel("", channelId, "", "") 713 CheckNoError(t, resp) 714 if len(rusers.Users) < 2 { 715 t.Fatal("should have many users") 716 } 717 718 rusers, resp = Client.AutocompleteUsersInTeam(teamId, username, "") 719 CheckNoError(t, resp) 720 721 if len(rusers.Users) != 1 { 722 t.Fatal("should have returned 1 user") 723 } 724 725 rusers, resp = Client.AutocompleteUsers(username, "") 726 CheckNoError(t, resp) 727 728 if len(rusers.Users) != 1 { 729 t.Fatal("should have returned 1 users") 730 } 731 732 rusers, resp = Client.AutocompleteUsers("", "") 733 CheckNoError(t, resp) 734 735 if len(rusers.Users) < 2 { 736 t.Fatal("should have returned many users") 737 } 738 739 rusers, resp = Client.AutocompleteUsersInTeam(teamId, "amazonses", "") 740 CheckNoError(t, resp) 741 if len(rusers.Users) != 0 { 742 t.Fatal("should have returned 0 users") 743 } 744 745 rusers, resp = Client.AutocompleteUsersInTeam(teamId, "", "") 746 CheckNoError(t, resp) 747 if len(rusers.Users) < 2 { 748 t.Fatal("should have many users") 749 } 750 751 Client.Logout() 752 _, resp = Client.AutocompleteUsersInChannel(teamId, channelId, username, "") 753 CheckUnauthorizedStatus(t, resp) 754 755 _, resp = Client.AutocompleteUsersInTeam(teamId, username, "") 756 CheckUnauthorizedStatus(t, resp) 757 758 _, resp = Client.AutocompleteUsers(username, "") 759 CheckUnauthorizedStatus(t, resp) 760 761 user := th.CreateUser() 762 Client.Login(user.Email, user.Password) 763 _, resp = Client.AutocompleteUsersInChannel(teamId, channelId, username, "") 764 CheckForbiddenStatus(t, resp) 765 766 _, resp = Client.AutocompleteUsersInTeam(teamId, username, "") 767 CheckForbiddenStatus(t, resp) 768 769 _, resp = Client.AutocompleteUsers(username, "") 770 CheckNoError(t, resp) 771 772 _, resp = th.SystemAdminClient.AutocompleteUsersInChannel(teamId, channelId, username, "") 773 CheckNoError(t, resp) 774 775 _, resp = th.SystemAdminClient.AutocompleteUsersInTeam(teamId, username, "") 776 CheckNoError(t, resp) 777 778 _, resp = th.SystemAdminClient.AutocompleteUsers(username, "") 779 CheckNoError(t, resp) 780 781 // Check against privacy config settings 782 th.App.UpdateConfig(func(cfg *model.Config) { cfg.PrivacySettings.ShowFullName = false }) 783 784 th.LoginBasic() 785 786 rusers, resp = Client.AutocompleteUsers(username, "") 787 CheckNoError(t, resp) 788 789 if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" { 790 t.Fatal("should not show first/last name") 791 } 792 793 rusers, resp = Client.AutocompleteUsersInChannel(teamId, channelId, username, "") 794 CheckNoError(t, resp) 795 796 if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" { 797 t.Fatal("should not show first/last name") 798 } 799 800 rusers, resp = Client.AutocompleteUsersInTeam(teamId, username, "") 801 CheckNoError(t, resp) 802 803 if rusers.Users[0].FirstName != "" || rusers.Users[0].LastName != "" { 804 t.Fatal("should not show first/last name") 805 } 806 } 807 808 func TestGetProfileImage(t *testing.T) { 809 th := Setup().InitBasic().InitSystemAdmin() 810 defer th.TearDown() 811 Client := th.Client 812 user := th.BasicUser 813 814 data, resp := Client.GetProfileImage(user.Id, "") 815 CheckNoError(t, resp) 816 if len(data) == 0 { 817 t.Fatal("Should not be empty") 818 } 819 820 _, resp = Client.GetProfileImage(user.Id, resp.Etag) 821 if resp.StatusCode == http.StatusNotModified { 822 t.Fatal("Shouldn't have hit etag") 823 } 824 825 _, resp = Client.GetProfileImage("junk", "") 826 CheckBadRequestStatus(t, resp) 827 828 _, resp = Client.GetProfileImage(model.NewId(), "") 829 CheckNotFoundStatus(t, resp) 830 831 Client.Logout() 832 _, resp = Client.GetProfileImage(user.Id, "") 833 CheckUnauthorizedStatus(t, resp) 834 835 _, resp = th.SystemAdminClient.GetProfileImage(user.Id, "") 836 CheckNoError(t, resp) 837 838 info := &model.FileInfo{Path: "/users/" + user.Id + "/profile.png"} 839 if err := th.cleanupTestFile(info); err != nil { 840 t.Fatal(err) 841 } 842 } 843 844 func TestGetUsersByIds(t *testing.T) { 845 th := Setup().InitBasic() 846 defer th.TearDown() 847 848 Client := th.Client 849 850 users, resp := Client.GetUsersByIds([]string{th.BasicUser.Id}) 851 CheckNoError(t, resp) 852 853 if users[0].Id != th.BasicUser.Id { 854 t.Fatal("returned wrong user") 855 } 856 CheckUserSanitization(t, users[0]) 857 858 _, resp = Client.GetUsersByIds([]string{}) 859 CheckBadRequestStatus(t, resp) 860 861 users, resp = Client.GetUsersByIds([]string{"junk"}) 862 CheckNoError(t, resp) 863 if len(users) > 0 { 864 t.Fatal("no users should be returned") 865 } 866 867 users, resp = Client.GetUsersByIds([]string{"junk", th.BasicUser.Id}) 868 CheckNoError(t, resp) 869 if len(users) != 1 { 870 t.Fatal("1 user should be returned") 871 } 872 873 Client.Logout() 874 _, resp = Client.GetUsersByIds([]string{th.BasicUser.Id}) 875 CheckUnauthorizedStatus(t, resp) 876 } 877 878 func TestGetUsersByUsernames(t *testing.T) { 879 th := Setup().InitBasic() 880 defer th.TearDown() 881 882 Client := th.Client 883 884 users, resp := Client.GetUsersByUsernames([]string{th.BasicUser.Username}) 885 CheckNoError(t, resp) 886 887 if users[0].Id != th.BasicUser.Id { 888 t.Fatal("returned wrong user") 889 } 890 CheckUserSanitization(t, users[0]) 891 892 _, resp = Client.GetUsersByIds([]string{}) 893 CheckBadRequestStatus(t, resp) 894 895 users, resp = Client.GetUsersByUsernames([]string{"junk"}) 896 CheckNoError(t, resp) 897 if len(users) > 0 { 898 t.Fatal("no users should be returned") 899 } 900 901 users, resp = Client.GetUsersByUsernames([]string{"junk", th.BasicUser.Username}) 902 CheckNoError(t, resp) 903 if len(users) != 1 { 904 t.Fatal("1 user should be returned") 905 } 906 907 Client.Logout() 908 _, resp = Client.GetUsersByUsernames([]string{th.BasicUser.Username}) 909 CheckUnauthorizedStatus(t, resp) 910 } 911 912 func TestUpdateUser(t *testing.T) { 913 th := Setup().InitBasic().InitSystemAdmin() 914 defer th.TearDown() 915 Client := th.Client 916 917 user := th.CreateUser() 918 Client.Login(user.Email, user.Password) 919 920 user.Nickname = "Joram Wilander" 921 user.Roles = model.SYSTEM_ADMIN_ROLE_ID 922 user.LastPasswordUpdate = 123 923 924 ruser, resp := Client.UpdateUser(user) 925 CheckNoError(t, resp) 926 CheckUserSanitization(t, ruser) 927 928 if ruser.Nickname != "Joram Wilander" { 929 t.Fatal("Nickname did not update properly") 930 } 931 if ruser.Roles != model.SYSTEM_USER_ROLE_ID { 932 t.Fatal("Roles should not have updated") 933 } 934 if ruser.LastPasswordUpdate == 123 { 935 t.Fatal("LastPasswordUpdate should not have updated") 936 } 937 938 ruser.Id = "junk" 939 _, resp = Client.UpdateUser(ruser) 940 CheckBadRequestStatus(t, resp) 941 942 ruser.Id = model.NewId() 943 _, resp = Client.UpdateUser(ruser) 944 CheckForbiddenStatus(t, resp) 945 946 if r, err := Client.DoApiPut("/users/"+ruser.Id, "garbage"); err == nil { 947 t.Fatal("should have errored") 948 } else { 949 if r.StatusCode != http.StatusBadRequest { 950 t.Log("actual: " + strconv.Itoa(r.StatusCode)) 951 t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) 952 t.Fatal("wrong status code") 953 } 954 } 955 956 session, _ := th.App.GetSession(Client.AuthToken) 957 session.IsOAuth = true 958 th.App.AddSessionToCache(session) 959 960 ruser.Id = user.Id 961 ruser.Email = th.GenerateTestEmail() 962 _, resp = Client.UpdateUser(ruser) 963 CheckForbiddenStatus(t, resp) 964 965 Client.Logout() 966 _, resp = Client.UpdateUser(user) 967 CheckUnauthorizedStatus(t, resp) 968 969 th.LoginBasic() 970 _, resp = Client.UpdateUser(user) 971 CheckForbiddenStatus(t, resp) 972 973 _, resp = th.SystemAdminClient.UpdateUser(user) 974 CheckNoError(t, resp) 975 } 976 977 func TestPatchUser(t *testing.T) { 978 th := Setup().InitBasic().InitSystemAdmin() 979 defer th.TearDown() 980 Client := th.Client 981 982 user := th.CreateUser() 983 Client.Login(user.Email, user.Password) 984 985 patch := &model.UserPatch{} 986 987 patch.Nickname = model.NewString("Joram Wilander") 988 patch.FirstName = model.NewString("Joram") 989 patch.LastName = model.NewString("Wilander") 990 patch.Position = new(string) 991 patch.NotifyProps = model.StringMap{} 992 patch.NotifyProps["comment"] = "somethingrandom" 993 patch.Timezone = model.StringMap{} 994 patch.Timezone["useAutomaticTimezone"] = "true" 995 patch.Timezone["automaticTimezone"] = "America/New_York" 996 patch.Timezone["manualTimezone"] = "" 997 998 ruser, resp := Client.PatchUser(user.Id, patch) 999 CheckNoError(t, resp) 1000 CheckUserSanitization(t, ruser) 1001 1002 if ruser.Nickname != "Joram Wilander" { 1003 t.Fatal("Nickname did not update properly") 1004 } 1005 if ruser.FirstName != "Joram" { 1006 t.Fatal("FirstName did not update properly") 1007 } 1008 if ruser.LastName != "Wilander" { 1009 t.Fatal("LastName did not update properly") 1010 } 1011 if ruser.Position != "" { 1012 t.Fatal("Position did not update properly") 1013 } 1014 if ruser.Username != user.Username { 1015 t.Fatal("Username should not have updated") 1016 } 1017 if ruser.NotifyProps["comment"] != "somethingrandom" { 1018 t.Fatal("NotifyProps did not update properly") 1019 } 1020 if ruser.Timezone["useAutomaticTimezone"] != "true" { 1021 t.Fatal("useAutomaticTimezone did not update properly") 1022 } 1023 if ruser.Timezone["automaticTimezone"] != "America/New_York" { 1024 t.Fatal("automaticTimezone did not update properly") 1025 } 1026 if ruser.Timezone["manualTimezone"] != "" { 1027 t.Fatal("manualTimezone did not update properly") 1028 } 1029 1030 patch.Username = model.NewString(th.BasicUser2.Username) 1031 _, resp = Client.PatchUser(user.Id, patch) 1032 CheckBadRequestStatus(t, resp) 1033 1034 patch.Username = nil 1035 1036 _, resp = Client.PatchUser("junk", patch) 1037 CheckBadRequestStatus(t, resp) 1038 1039 ruser.Id = model.NewId() 1040 _, resp = Client.PatchUser(model.NewId(), patch) 1041 CheckForbiddenStatus(t, resp) 1042 1043 if r, err := Client.DoApiPut("/users/"+user.Id+"/patch", "garbage"); err == nil { 1044 t.Fatal("should have errored") 1045 } else { 1046 if r.StatusCode != http.StatusBadRequest { 1047 t.Log("actual: " + strconv.Itoa(r.StatusCode)) 1048 t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) 1049 t.Fatal("wrong status code") 1050 } 1051 } 1052 1053 session, _ := th.App.GetSession(Client.AuthToken) 1054 session.IsOAuth = true 1055 th.App.AddSessionToCache(session) 1056 1057 patch.Email = model.NewString(th.GenerateTestEmail()) 1058 _, resp = Client.PatchUser(user.Id, patch) 1059 CheckForbiddenStatus(t, resp) 1060 1061 Client.Logout() 1062 _, resp = Client.PatchUser(user.Id, patch) 1063 CheckUnauthorizedStatus(t, resp) 1064 1065 th.LoginBasic() 1066 _, resp = Client.PatchUser(user.Id, patch) 1067 CheckForbiddenStatus(t, resp) 1068 1069 _, resp = th.SystemAdminClient.PatchUser(user.Id, patch) 1070 CheckNoError(t, resp) 1071 } 1072 1073 func TestUpdateUserAuth(t *testing.T) { 1074 th := Setup().InitSystemAdmin().InitBasic() 1075 defer th.TearDown() 1076 1077 Client := th.SystemAdminClient 1078 team := th.CreateTeamWithClient(Client) 1079 1080 user := th.CreateUser() 1081 1082 th.LinkUserToTeam(user, team) 1083 store.Must(th.App.Srv.Store.User().VerifyEmail(user.Id)) 1084 1085 userAuth := &model.UserAuth{} 1086 userAuth.AuthData = user.AuthData 1087 userAuth.AuthService = user.AuthService 1088 userAuth.Password = user.Password 1089 1090 // Regular user can not use endpoint 1091 if _, err := th.Client.UpdateUserAuth(user.Id, userAuth); err == nil { 1092 t.Fatal("Shouldn't have permissions. Only Admins") 1093 } 1094 1095 userAuth.AuthData = model.NewString("test@test.com") 1096 userAuth.AuthService = model.USER_AUTH_SERVICE_SAML 1097 userAuth.Password = "newpassword" 1098 ruser, resp := Client.UpdateUserAuth(user.Id, userAuth) 1099 CheckNoError(t, resp) 1100 1101 // AuthData and AuthService are set, password is set to empty 1102 if *ruser.AuthData != *userAuth.AuthData { 1103 t.Fatal("Should have set the correct AuthData") 1104 } 1105 if ruser.AuthService != model.USER_AUTH_SERVICE_SAML { 1106 t.Fatal("Should have set the correct AuthService") 1107 } 1108 if ruser.Password != "" { 1109 t.Fatal("Password should be empty") 1110 } 1111 1112 // When AuthData or AuthService are empty, password must be valid 1113 userAuth.AuthData = user.AuthData 1114 userAuth.AuthService = "" 1115 userAuth.Password = "1" 1116 if _, err := Client.UpdateUserAuth(user.Id, userAuth); err == nil { 1117 t.Fatal("Should have errored - user password not valid") 1118 } 1119 1120 // Regular user can not use endpoint 1121 user2 := th.CreateUser() 1122 th.LinkUserToTeam(user2, team) 1123 store.Must(th.App.Srv.Store.User().VerifyEmail(user2.Id)) 1124 1125 Client.Login(user2.Email, "passwd1") 1126 1127 userAuth.AuthData = user.AuthData 1128 userAuth.AuthService = user.AuthService 1129 userAuth.Password = user.Password 1130 if _, err := Client.UpdateUserAuth(user.Id, userAuth); err == nil { 1131 t.Fatal("Should have errored") 1132 } 1133 } 1134 1135 func TestDeleteUser(t *testing.T) { 1136 th := Setup().InitBasic().InitSystemAdmin() 1137 defer th.TearDown() 1138 1139 Client := th.Client 1140 1141 user := th.BasicUser 1142 th.LoginBasic() 1143 1144 testUser := th.SystemAdminUser 1145 _, resp := Client.DeleteUser(testUser.Id) 1146 CheckForbiddenStatus(t, resp) 1147 1148 Client.Logout() 1149 1150 _, resp = Client.DeleteUser(user.Id) 1151 CheckUnauthorizedStatus(t, resp) 1152 1153 Client.Login(testUser.Email, testUser.Password) 1154 1155 user.Id = model.NewId() 1156 _, resp = Client.DeleteUser(user.Id) 1157 CheckNotFoundStatus(t, resp) 1158 1159 user.Id = "junk" 1160 _, resp = Client.DeleteUser(user.Id) 1161 CheckBadRequestStatus(t, resp) 1162 1163 _, resp = Client.DeleteUser(testUser.Id) 1164 CheckNoError(t, resp) 1165 } 1166 1167 func TestUpdateUserRoles(t *testing.T) { 1168 th := Setup().InitBasic().InitSystemAdmin() 1169 defer th.TearDown() 1170 1171 Client := th.Client 1172 SystemAdminClient := th.SystemAdminClient 1173 1174 _, resp := Client.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID) 1175 CheckForbiddenStatus(t, resp) 1176 1177 _, resp = SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID) 1178 CheckNoError(t, resp) 1179 1180 _, resp = SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID) 1181 CheckNoError(t, resp) 1182 1183 _, resp = SystemAdminClient.UpdateUserRoles(th.BasicUser.Id, "junk") 1184 CheckBadRequestStatus(t, resp) 1185 1186 _, resp = SystemAdminClient.UpdateUserRoles("junk", model.SYSTEM_USER_ROLE_ID) 1187 CheckBadRequestStatus(t, resp) 1188 1189 _, resp = SystemAdminClient.UpdateUserRoles(model.NewId(), model.SYSTEM_USER_ROLE_ID) 1190 CheckBadRequestStatus(t, resp) 1191 } 1192 1193 func TestUpdateUserActive(t *testing.T) { 1194 th := Setup().InitBasic().InitSystemAdmin() 1195 defer th.TearDown() 1196 1197 Client := th.Client 1198 SystemAdminClient := th.SystemAdminClient 1199 user := th.BasicUser 1200 1201 pass, resp := Client.UpdateUserActive(user.Id, false) 1202 CheckNoError(t, resp) 1203 1204 if !pass { 1205 t.Fatal("should have returned true") 1206 } 1207 1208 pass, resp = Client.UpdateUserActive(user.Id, false) 1209 CheckUnauthorizedStatus(t, resp) 1210 1211 if pass { 1212 t.Fatal("should have returned false") 1213 } 1214 1215 th.LoginBasic2() 1216 1217 _, resp = Client.UpdateUserActive(user.Id, true) 1218 CheckForbiddenStatus(t, resp) 1219 1220 _, resp = Client.UpdateUserActive(GenerateTestId(), true) 1221 CheckForbiddenStatus(t, resp) 1222 1223 _, resp = Client.UpdateUserActive("junk", true) 1224 CheckBadRequestStatus(t, resp) 1225 1226 Client.Logout() 1227 1228 _, resp = Client.UpdateUserActive(user.Id, true) 1229 CheckUnauthorizedStatus(t, resp) 1230 1231 _, resp = SystemAdminClient.UpdateUserActive(user.Id, true) 1232 CheckNoError(t, resp) 1233 1234 _, resp = SystemAdminClient.UpdateUserActive(user.Id, false) 1235 CheckNoError(t, resp) 1236 1237 authData := model.NewId() 1238 result := <-th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) 1239 require.Nil(t, result.Err) 1240 1241 _, resp = SystemAdminClient.UpdateUserActive(user.Id, false) 1242 CheckNoError(t, resp) 1243 } 1244 1245 func TestGetUsers(t *testing.T) { 1246 th := Setup().InitBasic() 1247 defer th.TearDown() 1248 Client := th.Client 1249 1250 rusers, resp := Client.GetUsers(0, 60, "") 1251 CheckNoError(t, resp) 1252 for _, u := range rusers { 1253 CheckUserSanitization(t, u) 1254 } 1255 1256 rusers, resp = Client.GetUsers(0, 60, resp.Etag) 1257 CheckEtag(t, rusers, resp) 1258 1259 rusers, resp = Client.GetUsers(0, 1, "") 1260 CheckNoError(t, resp) 1261 if len(rusers) != 1 { 1262 t.Fatal("should be 1 per page") 1263 } 1264 1265 rusers, resp = Client.GetUsers(1, 1, "") 1266 CheckNoError(t, resp) 1267 if len(rusers) != 1 { 1268 t.Fatal("should be 1 per page") 1269 } 1270 1271 rusers, resp = Client.GetUsers(10000, 100, "") 1272 CheckNoError(t, resp) 1273 if len(rusers) != 0 { 1274 t.Fatal("should be no users") 1275 } 1276 1277 // Check default params for page and per_page 1278 if _, err := Client.DoApiGet("/users", ""); err != nil { 1279 t.Fatal("should not have errored") 1280 } 1281 1282 Client.Logout() 1283 _, resp = Client.GetUsers(0, 60, "") 1284 CheckUnauthorizedStatus(t, resp) 1285 } 1286 1287 func TestGetNewUsersInTeam(t *testing.T) { 1288 th := Setup().InitBasic() 1289 defer th.TearDown() 1290 Client := th.Client 1291 teamId := th.BasicTeam.Id 1292 1293 rusers, resp := Client.GetNewUsersInTeam(teamId, 0, 60, "") 1294 CheckNoError(t, resp) 1295 1296 lastCreateAt := model.GetMillis() 1297 for _, u := range rusers { 1298 if u.CreateAt > lastCreateAt { 1299 t.Fatal("bad sorting") 1300 } 1301 lastCreateAt = u.CreateAt 1302 CheckUserSanitization(t, u) 1303 } 1304 1305 rusers, resp = Client.GetNewUsersInTeam(teamId, 1, 1, "") 1306 CheckNoError(t, resp) 1307 if len(rusers) != 1 { 1308 t.Fatal("should be 1 per page") 1309 } 1310 1311 Client.Logout() 1312 _, resp = Client.GetNewUsersInTeam(teamId, 1, 1, "") 1313 CheckUnauthorizedStatus(t, resp) 1314 } 1315 1316 func TestGetRecentlyActiveUsersInTeam(t *testing.T) { 1317 th := Setup().InitBasic() 1318 defer th.TearDown() 1319 Client := th.Client 1320 teamId := th.BasicTeam.Id 1321 1322 th.App.SetStatusOnline(th.BasicUser.Id, "", true) 1323 1324 rusers, resp := Client.GetRecentlyActiveUsersInTeam(teamId, 0, 60, "") 1325 CheckNoError(t, resp) 1326 1327 for _, u := range rusers { 1328 if u.LastActivityAt == 0 { 1329 t.Fatal("did not return last activity at") 1330 } 1331 CheckUserSanitization(t, u) 1332 } 1333 1334 rusers, resp = Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "") 1335 CheckNoError(t, resp) 1336 if len(rusers) != 1 { 1337 t.Fatal("should be 1 per page") 1338 } 1339 1340 Client.Logout() 1341 _, resp = Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "") 1342 CheckUnauthorizedStatus(t, resp) 1343 } 1344 1345 func TestGetUsersWithoutTeam(t *testing.T) { 1346 th := Setup().InitBasic().InitSystemAdmin() 1347 defer th.TearDown() 1348 Client := th.Client 1349 SystemAdminClient := th.SystemAdminClient 1350 1351 if _, resp := Client.GetUsersWithoutTeam(0, 100, ""); resp.Error == nil { 1352 t.Fatal("should prevent non-admin user from getting users without a team") 1353 } 1354 1355 // These usernames need to appear in the first 100 users for this to work 1356 1357 user, resp := Client.CreateUser(&model.User{ 1358 Username: "a000000000" + model.NewId(), 1359 Email: "success+" + model.NewId() + "@simulator.amazonses.com", 1360 Password: "Password1", 1361 }) 1362 CheckNoError(t, resp) 1363 th.LinkUserToTeam(user, th.BasicTeam) 1364 defer th.App.Srv.Store.User().PermanentDelete(user.Id) 1365 1366 user2, resp := Client.CreateUser(&model.User{ 1367 Username: "a000000001" + model.NewId(), 1368 Email: "success+" + model.NewId() + "@simulator.amazonses.com", 1369 Password: "Password1", 1370 }) 1371 CheckNoError(t, resp) 1372 defer th.App.Srv.Store.User().PermanentDelete(user2.Id) 1373 1374 rusers, resp := SystemAdminClient.GetUsersWithoutTeam(0, 100, "") 1375 CheckNoError(t, resp) 1376 1377 found1 := false 1378 found2 := false 1379 1380 for _, u := range rusers { 1381 if u.Id == user.Id { 1382 found1 = true 1383 } else if u.Id == user2.Id { 1384 found2 = true 1385 } 1386 } 1387 1388 if found1 { 1389 t.Fatal("shouldn't have returned user that has a team") 1390 } else if !found2 { 1391 t.Fatal("should've returned user that has no teams") 1392 } 1393 } 1394 1395 func TestGetUsersInTeam(t *testing.T) { 1396 th := Setup().InitBasic().InitSystemAdmin() 1397 defer th.TearDown() 1398 Client := th.Client 1399 teamId := th.BasicTeam.Id 1400 1401 rusers, resp := Client.GetUsersInTeam(teamId, 0, 60, "") 1402 CheckNoError(t, resp) 1403 for _, u := range rusers { 1404 CheckUserSanitization(t, u) 1405 } 1406 1407 rusers, resp = Client.GetUsersInTeam(teamId, 0, 60, resp.Etag) 1408 CheckEtag(t, rusers, resp) 1409 1410 rusers, resp = Client.GetUsersInTeam(teamId, 0, 1, "") 1411 CheckNoError(t, resp) 1412 if len(rusers) != 1 { 1413 t.Fatal("should be 1 per page") 1414 } 1415 1416 rusers, resp = Client.GetUsersInTeam(teamId, 1, 1, "") 1417 CheckNoError(t, resp) 1418 if len(rusers) != 1 { 1419 t.Fatal("should be 1 per page") 1420 } 1421 1422 rusers, resp = Client.GetUsersInTeam(teamId, 10000, 100, "") 1423 CheckNoError(t, resp) 1424 if len(rusers) != 0 { 1425 t.Fatal("should be no users") 1426 } 1427 1428 Client.Logout() 1429 _, resp = Client.GetUsersInTeam(teamId, 0, 60, "") 1430 CheckUnauthorizedStatus(t, resp) 1431 1432 user := th.CreateUser() 1433 Client.Login(user.Email, user.Password) 1434 _, resp = Client.GetUsersInTeam(teamId, 0, 60, "") 1435 CheckForbiddenStatus(t, resp) 1436 1437 _, resp = th.SystemAdminClient.GetUsersInTeam(teamId, 0, 60, "") 1438 CheckNoError(t, resp) 1439 } 1440 1441 func TestGetUsersNotInTeam(t *testing.T) { 1442 th := Setup().InitBasic().InitSystemAdmin() 1443 defer th.TearDown() 1444 Client := th.Client 1445 teamId := th.BasicTeam.Id 1446 1447 rusers, resp := Client.GetUsersNotInTeam(teamId, 0, 60, "") 1448 CheckNoError(t, resp) 1449 for _, u := range rusers { 1450 CheckUserSanitization(t, u) 1451 } 1452 1453 rusers, resp = Client.GetUsersNotInTeam(teamId, 0, 60, resp.Etag) 1454 CheckEtag(t, rusers, resp) 1455 1456 rusers, resp = Client.GetUsersNotInTeam(teamId, 0, 1, "") 1457 CheckNoError(t, resp) 1458 if len(rusers) != 1 { 1459 t.Fatal("should be 1 per page") 1460 } 1461 1462 rusers, resp = Client.GetUsersNotInTeam(teamId, 1, 1, "") 1463 CheckNoError(t, resp) 1464 if len(rusers) != 1 { 1465 t.Fatal("should be 1 per page") 1466 } 1467 1468 rusers, resp = Client.GetUsersNotInTeam(teamId, 10000, 100, "") 1469 CheckNoError(t, resp) 1470 if len(rusers) != 0 { 1471 t.Fatal("should be no users") 1472 } 1473 1474 Client.Logout() 1475 _, resp = Client.GetUsersNotInTeam(teamId, 0, 60, "") 1476 CheckUnauthorizedStatus(t, resp) 1477 1478 user := th.CreateUser() 1479 Client.Login(user.Email, user.Password) 1480 _, resp = Client.GetUsersNotInTeam(teamId, 0, 60, "") 1481 CheckForbiddenStatus(t, resp) 1482 1483 _, resp = th.SystemAdminClient.GetUsersNotInTeam(teamId, 0, 60, "") 1484 CheckNoError(t, resp) 1485 } 1486 1487 func TestGetUsersInChannel(t *testing.T) { 1488 th := Setup().InitBasic().InitSystemAdmin() 1489 defer th.TearDown() 1490 Client := th.Client 1491 channelId := th.BasicChannel.Id 1492 1493 rusers, resp := Client.GetUsersInChannel(channelId, 0, 60, "") 1494 CheckNoError(t, resp) 1495 for _, u := range rusers { 1496 CheckUserSanitization(t, u) 1497 } 1498 1499 rusers, resp = Client.GetUsersInChannel(channelId, 0, 1, "") 1500 CheckNoError(t, resp) 1501 if len(rusers) != 1 { 1502 t.Fatal("should be 1 per page") 1503 } 1504 1505 rusers, resp = Client.GetUsersInChannel(channelId, 1, 1, "") 1506 CheckNoError(t, resp) 1507 if len(rusers) != 1 { 1508 t.Fatal("should be 1 per page") 1509 } 1510 1511 rusers, resp = Client.GetUsersInChannel(channelId, 10000, 100, "") 1512 CheckNoError(t, resp) 1513 if len(rusers) != 0 { 1514 t.Fatal("should be no users") 1515 } 1516 1517 Client.Logout() 1518 _, resp = Client.GetUsersInChannel(channelId, 0, 60, "") 1519 CheckUnauthorizedStatus(t, resp) 1520 1521 user := th.CreateUser() 1522 Client.Login(user.Email, user.Password) 1523 _, resp = Client.GetUsersInChannel(channelId, 0, 60, "") 1524 CheckForbiddenStatus(t, resp) 1525 1526 _, resp = th.SystemAdminClient.GetUsersInChannel(channelId, 0, 60, "") 1527 CheckNoError(t, resp) 1528 } 1529 1530 func TestGetUsersNotInChannel(t *testing.T) { 1531 th := Setup().InitBasic().InitSystemAdmin() 1532 defer th.TearDown() 1533 Client := th.Client 1534 teamId := th.BasicTeam.Id 1535 channelId := th.BasicChannel.Id 1536 1537 user := th.CreateUser() 1538 th.LinkUserToTeam(user, th.BasicTeam) 1539 1540 rusers, resp := Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "") 1541 CheckNoError(t, resp) 1542 for _, u := range rusers { 1543 CheckUserSanitization(t, u) 1544 } 1545 1546 rusers, resp = Client.GetUsersNotInChannel(teamId, channelId, 0, 1, "") 1547 CheckNoError(t, resp) 1548 if len(rusers) != 1 { 1549 t.Log(len(rusers)) 1550 t.Fatal("should be 1 per page") 1551 } 1552 1553 rusers, resp = Client.GetUsersNotInChannel(teamId, channelId, 10000, 100, "") 1554 CheckNoError(t, resp) 1555 if len(rusers) != 0 { 1556 t.Fatal("should be no users") 1557 } 1558 1559 Client.Logout() 1560 _, resp = Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "") 1561 CheckUnauthorizedStatus(t, resp) 1562 1563 Client.Login(user.Email, user.Password) 1564 _, resp = Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "") 1565 CheckForbiddenStatus(t, resp) 1566 1567 _, resp = th.SystemAdminClient.GetUsersNotInChannel(teamId, channelId, 0, 60, "") 1568 CheckNoError(t, resp) 1569 } 1570 1571 func TestUpdateUserMfa(t *testing.T) { 1572 th := Setup().InitBasic().InitSystemAdmin() 1573 defer th.TearDown() 1574 Client := th.Client 1575 1576 th.App.SetLicense(model.NewTestLicense("mfa")) 1577 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) 1578 1579 session, _ := th.App.GetSession(Client.AuthToken) 1580 session.IsOAuth = true 1581 th.App.AddSessionToCache(session) 1582 1583 _, resp := Client.UpdateUserMfa(th.BasicUser.Id, "12345", false) 1584 CheckForbiddenStatus(t, resp) 1585 } 1586 1587 func TestCheckUserMfa(t *testing.T) { 1588 th := Setup().InitBasic().InitSystemAdmin() 1589 defer th.TearDown() 1590 Client := th.Client 1591 1592 required, resp := Client.CheckUserMfa(th.BasicUser.Email) 1593 CheckNoError(t, resp) 1594 1595 if required { 1596 t.Fatal("should be false - mfa not active") 1597 } 1598 1599 _, resp = Client.CheckUserMfa("") 1600 CheckBadRequestStatus(t, resp) 1601 1602 Client.Logout() 1603 1604 required, resp = Client.CheckUserMfa(th.BasicUser.Email) 1605 CheckNoError(t, resp) 1606 1607 if required { 1608 t.Fatal("should be false - mfa not active") 1609 } 1610 1611 th.App.SetLicense(model.NewTestLicense("mfa")) 1612 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) 1613 1614 th.LoginBasic() 1615 1616 required, resp = Client.CheckUserMfa(th.BasicUser.Email) 1617 CheckNoError(t, resp) 1618 1619 if required { 1620 t.Fatal("should be false - mfa not active") 1621 } 1622 1623 Client.Logout() 1624 1625 required, resp = Client.CheckUserMfa(th.BasicUser.Email) 1626 CheckNoError(t, resp) 1627 1628 if required { 1629 t.Fatal("should be false - mfa not active") 1630 } 1631 } 1632 1633 func TestGenerateMfaSecret(t *testing.T) { 1634 th := Setup().InitBasic().InitSystemAdmin() 1635 defer th.TearDown() 1636 Client := th.Client 1637 1638 _, resp := Client.GenerateMfaSecret(th.BasicUser.Id) 1639 CheckNotImplementedStatus(t, resp) 1640 1641 _, resp = th.SystemAdminClient.GenerateMfaSecret(th.BasicUser.Id) 1642 CheckNotImplementedStatus(t, resp) 1643 1644 _, resp = Client.GenerateMfaSecret("junk") 1645 CheckBadRequestStatus(t, resp) 1646 1647 th.App.SetLicense(model.NewTestLicense("mfa")) 1648 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) 1649 1650 _, resp = Client.GenerateMfaSecret(model.NewId()) 1651 CheckForbiddenStatus(t, resp) 1652 1653 session, _ := th.App.GetSession(Client.AuthToken) 1654 session.IsOAuth = true 1655 th.App.AddSessionToCache(session) 1656 1657 _, resp = Client.GenerateMfaSecret(th.BasicUser.Id) 1658 CheckForbiddenStatus(t, resp) 1659 1660 Client.Logout() 1661 1662 _, resp = Client.GenerateMfaSecret(th.BasicUser.Id) 1663 CheckUnauthorizedStatus(t, resp) 1664 } 1665 1666 func TestUpdateUserPassword(t *testing.T) { 1667 th := Setup().InitBasic().InitSystemAdmin() 1668 defer th.TearDown() 1669 Client := th.Client 1670 1671 password := "newpassword1" 1672 pass, resp := Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, password) 1673 CheckNoError(t, resp) 1674 1675 if !pass { 1676 t.Fatal("should have returned true") 1677 } 1678 1679 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, "") 1680 CheckBadRequestStatus(t, resp) 1681 1682 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, "junk") 1683 CheckBadRequestStatus(t, resp) 1684 1685 _, resp = Client.UpdateUserPassword("junk", password, password) 1686 CheckBadRequestStatus(t, resp) 1687 1688 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, "", password) 1689 CheckBadRequestStatus(t, resp) 1690 1691 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, "junk", password) 1692 CheckBadRequestStatus(t, resp) 1693 1694 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, th.BasicUser.Password) 1695 CheckNoError(t, resp) 1696 1697 Client.Logout() 1698 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, password) 1699 CheckUnauthorizedStatus(t, resp) 1700 1701 th.LoginBasic2() 1702 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, password, password) 1703 CheckForbiddenStatus(t, resp) 1704 1705 th.LoginBasic() 1706 1707 // Test lockout 1708 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.MaximumLoginAttempts = 2 }) 1709 1710 // Fail twice 1711 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd") 1712 CheckBadRequestStatus(t, resp) 1713 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, "badpwd", "newpwd") 1714 CheckBadRequestStatus(t, resp) 1715 1716 // Should fail because account is locked out 1717 _, resp = Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, "newpwd") 1718 CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error") 1719 CheckUnauthorizedStatus(t, resp) 1720 1721 // System admin can update another user's password 1722 adminSetPassword := "pwdsetbyadmin" 1723 pass, resp = th.SystemAdminClient.UpdateUserPassword(th.BasicUser.Id, "", adminSetPassword) 1724 CheckNoError(t, resp) 1725 1726 if !pass { 1727 t.Fatal("should have returned true") 1728 } 1729 1730 _, resp = Client.Login(th.BasicUser.Email, adminSetPassword) 1731 CheckNoError(t, resp) 1732 } 1733 1734 /*func TestResetPassword(t *testing.T) { 1735 th := Setup().InitBasic() 1736 Client := th.Client 1737 1738 Client.Logout() 1739 1740 user := th.BasicUser 1741 1742 // Delete all the messages before check the reset password 1743 utils.DeleteMailBox(user.Email) 1744 1745 success, resp := Client.SendPasswordResetEmail(user.Email) 1746 CheckNoError(t, resp) 1747 if !success { 1748 t.Fatal("should have succeeded") 1749 } 1750 1751 _, resp = Client.SendPasswordResetEmail("") 1752 CheckBadRequestStatus(t, resp) 1753 1754 // Should not leak whether the email is attached to an account or not 1755 success, resp = Client.SendPasswordResetEmail("notreal@example.com") 1756 CheckNoError(t, resp) 1757 if !success { 1758 t.Fatal("should have succeeded") 1759 } 1760 1761 // Check if the email was send to the right email address and the recovery key match 1762 var resultsMailbox utils.JSONMessageHeaderInbucket 1763 err := utils.RetryInbucket(5, func() error { 1764 var err error 1765 resultsMailbox, err = utils.GetMailBox(user.Email) 1766 return err 1767 }) 1768 if err != nil { 1769 t.Log(err) 1770 t.Log("No email was received, maybe due load on the server. Disabling this verification") 1771 } 1772 1773 var recoveryTokenString string 1774 if err == nil && len(resultsMailbox) > 0 { 1775 if !strings.ContainsAny(resultsMailbox[0].To[0], user.Email) { 1776 t.Fatal("Wrong To recipient") 1777 } else { 1778 if resultsEmail, err := utils.GetMessageFromMailbox(user.Email, resultsMailbox[0].ID); err == nil { 1779 loc := strings.Index(resultsEmail.Body.Text, "token=") 1780 if loc == -1 { 1781 t.Log(resultsEmail.Body.Text) 1782 t.Fatal("Code not found in email") 1783 } 1784 loc += 6 1785 recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] 1786 } 1787 } 1788 } 1789 1790 var recoveryToken *model.Token 1791 if result := <-th.App.Srv.Store.Token().GetByToken(recoveryTokenString); result.Err != nil { 1792 t.Log(recoveryTokenString) 1793 t.Fatal(result.Err) 1794 } else { 1795 recoveryToken = result.Data.(*model.Token) 1796 } 1797 1798 _, resp = Client.ResetPassword(recoveryToken.Token, "") 1799 CheckBadRequestStatus(t, resp) 1800 1801 _, resp = Client.ResetPassword(recoveryToken.Token, "newp") 1802 CheckBadRequestStatus(t, resp) 1803 1804 _, resp = Client.ResetPassword("", "newpwd") 1805 CheckBadRequestStatus(t, resp) 1806 1807 _, resp = Client.ResetPassword("junk", "newpwd") 1808 CheckBadRequestStatus(t, resp) 1809 1810 code := "" 1811 for i := 0; i < model.TOKEN_SIZE; i++ { 1812 code += "a" 1813 } 1814 1815 _, resp = Client.ResetPassword(code, "newpwd") 1816 CheckBadRequestStatus(t, resp) 1817 1818 success, resp = Client.ResetPassword(recoveryToken.Token, "newpwd") 1819 CheckNoError(t, resp) 1820 if !success { 1821 t.Fatal("should have succeeded") 1822 } 1823 1824 Client.Login(user.Email, "newpwd") 1825 Client.Logout() 1826 1827 _, resp = Client.ResetPassword(recoveryToken.Token, "newpwd") 1828 CheckBadRequestStatus(t, resp) 1829 1830 authData := model.NewId() 1831 if result := <-app.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true); result.Err != nil { 1832 t.Fatal(result.Err) 1833 } 1834 1835 _, resp = Client.SendPasswordResetEmail(user.Email) 1836 CheckBadRequestStatus(t, resp) 1837 }*/ 1838 1839 func TestGetSessions(t *testing.T) { 1840 th := Setup().InitBasic().InitSystemAdmin() 1841 defer th.TearDown() 1842 Client := th.Client 1843 1844 user := th.BasicUser 1845 1846 Client.Login(user.Email, user.Password) 1847 1848 sessions, resp := Client.GetSessions(user.Id, "") 1849 for _, session := range sessions { 1850 if session.UserId != user.Id { 1851 t.Fatal("user id does not match session user id") 1852 } 1853 } 1854 CheckNoError(t, resp) 1855 1856 _, resp = Client.RevokeSession("junk", model.NewId()) 1857 CheckBadRequestStatus(t, resp) 1858 1859 _, resp = Client.GetSessions(th.BasicUser2.Id, "") 1860 CheckForbiddenStatus(t, resp) 1861 1862 _, resp = Client.GetSessions(model.NewId(), "") 1863 CheckForbiddenStatus(t, resp) 1864 1865 Client.Logout() 1866 _, resp = Client.GetSessions(th.BasicUser2.Id, "") 1867 CheckUnauthorizedStatus(t, resp) 1868 1869 _, resp = th.SystemAdminClient.GetSessions(user.Id, "") 1870 CheckNoError(t, resp) 1871 1872 _, resp = th.SystemAdminClient.GetSessions(th.BasicUser2.Id, "") 1873 CheckNoError(t, resp) 1874 1875 _, resp = th.SystemAdminClient.GetSessions(model.NewId(), "") 1876 CheckNoError(t, resp) 1877 } 1878 1879 func TestRevokeSessions(t *testing.T) { 1880 th := Setup().InitBasic().InitSystemAdmin() 1881 defer th.TearDown() 1882 Client := th.Client 1883 1884 user := th.BasicUser 1885 Client.Login(user.Email, user.Password) 1886 sessions, _ := Client.GetSessions(user.Id, "") 1887 if len(sessions) == 0 { 1888 t.Fatal("sessions should exist") 1889 } 1890 for _, session := range sessions { 1891 if session.UserId != user.Id { 1892 t.Fatal("user id does not match session user id") 1893 } 1894 } 1895 session := sessions[0] 1896 1897 _, resp := Client.RevokeSession(user.Id, model.NewId()) 1898 CheckBadRequestStatus(t, resp) 1899 1900 _, resp = Client.RevokeSession(th.BasicUser2.Id, model.NewId()) 1901 CheckForbiddenStatus(t, resp) 1902 1903 _, resp = Client.RevokeSession("junk", model.NewId()) 1904 CheckBadRequestStatus(t, resp) 1905 1906 status, resp := Client.RevokeSession(user.Id, session.Id) 1907 if !status { 1908 t.Fatal("user session revoke unsuccessful") 1909 } 1910 CheckNoError(t, resp) 1911 1912 th.LoginBasic() 1913 1914 sessions, _ = th.App.GetSessions(th.SystemAdminUser.Id) 1915 session = sessions[0] 1916 1917 _, resp = Client.RevokeSession(user.Id, session.Id) 1918 CheckBadRequestStatus(t, resp) 1919 1920 Client.Logout() 1921 _, resp = Client.RevokeSession(user.Id, model.NewId()) 1922 CheckUnauthorizedStatus(t, resp) 1923 1924 _, resp = th.SystemAdminClient.RevokeSession(user.Id, model.NewId()) 1925 CheckBadRequestStatus(t, resp) 1926 1927 sessions, _ = th.SystemAdminClient.GetSessions(th.SystemAdminUser.Id, "") 1928 if len(sessions) == 0 { 1929 t.Fatal("sessions should exist") 1930 } 1931 for _, session := range sessions { 1932 if session.UserId != th.SystemAdminUser.Id { 1933 t.Fatal("user id does not match session user id") 1934 } 1935 } 1936 session = sessions[0] 1937 1938 _, resp = th.SystemAdminClient.RevokeSession(th.SystemAdminUser.Id, session.Id) 1939 CheckNoError(t, resp) 1940 } 1941 1942 func TestRevokeAllSessions(t *testing.T) { 1943 th := Setup().InitBasic() 1944 defer th.TearDown() 1945 Client := th.Client 1946 1947 user := th.BasicUser 1948 Client.Login(user.Email, user.Password) 1949 1950 _, resp := Client.RevokeAllSessions(th.BasicUser2.Id) 1951 CheckForbiddenStatus(t, resp) 1952 1953 th.InitSystemAdmin() 1954 1955 _, resp = Client.RevokeAllSessions("junk" + user.Id) 1956 CheckBadRequestStatus(t, resp) 1957 1958 status, resp := Client.RevokeAllSessions(user.Id) 1959 if !status { 1960 t.Fatal("user all sessions revoke unsuccessful") 1961 } 1962 CheckNoError(t, resp) 1963 1964 Client.Logout() 1965 _, resp = Client.RevokeAllSessions(user.Id) 1966 CheckUnauthorizedStatus(t, resp) 1967 1968 Client.Login(user.Email, user.Password) 1969 1970 sessions, _ := Client.GetSessions(user.Id, "") 1971 if len(sessions) < 1 { 1972 t.Fatal("session should exist") 1973 } 1974 1975 _, resp = Client.RevokeAllSessions(user.Id) 1976 CheckNoError(t, resp) 1977 1978 sessions, _ = th.SystemAdminClient.GetSessions(user.Id, "") 1979 if len(sessions) != 0 { 1980 t.Fatal("no sessions should exist for user") 1981 } 1982 1983 _, resp = Client.RevokeAllSessions(user.Id) 1984 CheckUnauthorizedStatus(t, resp) 1985 } 1986 1987 func TestAttachDeviceId(t *testing.T) { 1988 th := Setup().InitBasic() 1989 defer th.TearDown() 1990 Client := th.Client 1991 1992 deviceId := model.PUSH_NOTIFY_APPLE + ":1234567890" 1993 pass, resp := Client.AttachDeviceId(deviceId) 1994 CheckNoError(t, resp) 1995 1996 if !pass { 1997 t.Fatal("should have passed") 1998 } 1999 2000 if sessions, err := th.App.GetSessions(th.BasicUser.Id); err != nil { 2001 t.Fatal(err) 2002 } else { 2003 if sessions[0].DeviceId != deviceId { 2004 t.Fatal("Missing device Id") 2005 } 2006 } 2007 2008 _, resp = Client.AttachDeviceId("") 2009 CheckBadRequestStatus(t, resp) 2010 2011 Client.Logout() 2012 2013 _, resp = Client.AttachDeviceId("") 2014 CheckUnauthorizedStatus(t, resp) 2015 } 2016 2017 func TestGetUserAudits(t *testing.T) { 2018 th := Setup().InitBasic().InitSystemAdmin() 2019 defer th.TearDown() 2020 Client := th.Client 2021 user := th.BasicUser 2022 2023 audits, resp := Client.GetUserAudits(user.Id, 0, 100, "") 2024 for _, audit := range audits { 2025 if audit.UserId != user.Id { 2026 t.Fatal("user id does not match audit user id") 2027 } 2028 } 2029 CheckNoError(t, resp) 2030 2031 _, resp = Client.GetUserAudits(th.BasicUser2.Id, 0, 100, "") 2032 CheckForbiddenStatus(t, resp) 2033 2034 Client.Logout() 2035 _, resp = Client.GetUserAudits(user.Id, 0, 100, "") 2036 CheckUnauthorizedStatus(t, resp) 2037 2038 _, resp = th.SystemAdminClient.GetUserAudits(user.Id, 0, 100, "") 2039 CheckNoError(t, resp) 2040 } 2041 2042 func TestVerifyUserEmail(t *testing.T) { 2043 th := Setup().InitBasic() 2044 defer th.TearDown() 2045 Client := th.Client 2046 2047 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Darth Vader", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID} 2048 2049 ruser, resp := Client.CreateUser(&user) 2050 2051 token, err := th.App.CreateVerifyEmailToken(ruser.Id) 2052 if err != nil { 2053 t.Fatal("Unable to create email verify token") 2054 } 2055 2056 _, resp = Client.VerifyUserEmail(token.Token) 2057 CheckNoError(t, resp) 2058 2059 _, resp = Client.VerifyUserEmail(GenerateTestId()) 2060 CheckBadRequestStatus(t, resp) 2061 2062 _, resp = Client.VerifyUserEmail("") 2063 CheckBadRequestStatus(t, resp) 2064 } 2065 2066 func TestSendVerificationEmail(t *testing.T) { 2067 th := Setup().InitBasic() 2068 defer th.TearDown() 2069 Client := th.Client 2070 2071 pass, resp := Client.SendVerificationEmail(th.BasicUser.Email) 2072 CheckNoError(t, resp) 2073 2074 if !pass { 2075 t.Fatal("should have passed") 2076 } 2077 2078 _, resp = Client.SendVerificationEmail("") 2079 CheckBadRequestStatus(t, resp) 2080 2081 // Even non-existent emails should return 200 OK 2082 _, resp = Client.SendVerificationEmail(th.GenerateTestEmail()) 2083 CheckNoError(t, resp) 2084 2085 Client.Logout() 2086 _, resp = Client.SendVerificationEmail(th.BasicUser.Email) 2087 CheckNoError(t, resp) 2088 } 2089 2090 func TestSetProfileImage(t *testing.T) { 2091 th := Setup().InitBasic().InitSystemAdmin() 2092 defer th.TearDown() 2093 Client := th.Client 2094 user := th.BasicUser 2095 2096 data, err := readTestFile("test.png") 2097 if err != nil { 2098 t.Fatal(err) 2099 } 2100 2101 ok, resp := Client.SetProfileImage(user.Id, data) 2102 if !ok { 2103 t.Fatal(resp.Error) 2104 } 2105 CheckNoError(t, resp) 2106 2107 ok, resp = Client.SetProfileImage(model.NewId(), data) 2108 if ok { 2109 t.Fatal("Should return false, set profile image not allowed") 2110 } 2111 CheckForbiddenStatus(t, resp) 2112 2113 // status code returns either forbidden or unauthorized 2114 // note: forbidden is set as default at Client4.SetProfileImage when request is terminated early by server 2115 Client.Logout() 2116 _, resp = Client.SetProfileImage(user.Id, data) 2117 if resp.StatusCode == http.StatusForbidden { 2118 CheckForbiddenStatus(t, resp) 2119 } else if resp.StatusCode == http.StatusUnauthorized { 2120 CheckUnauthorizedStatus(t, resp) 2121 } else { 2122 t.Fatal("Should have failed either forbidden or unauthorized") 2123 } 2124 2125 buser, err := th.App.GetUser(user.Id) 2126 require.Nil(t, err) 2127 2128 _, resp = th.SystemAdminClient.SetProfileImage(user.Id, data) 2129 CheckNoError(t, resp) 2130 2131 ruser, err := th.App.GetUser(user.Id) 2132 require.Nil(t, err) 2133 assert.True(t, buser.LastPictureUpdate < ruser.LastPictureUpdate, "Picture should have updated for user") 2134 2135 info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"} 2136 if err := th.cleanupTestFile(info); err != nil { 2137 t.Fatal(err) 2138 } 2139 } 2140 2141 func TestSwitchAccount(t *testing.T) { 2142 th := Setup().InitBasic().InitSystemAdmin() 2143 defer th.TearDown() 2144 Client := th.Client 2145 2146 th.App.UpdateConfig(func(cfg *model.Config) { cfg.GitLabSettings.Enable = true }) 2147 2148 Client.Logout() 2149 2150 sr := &model.SwitchRequest{ 2151 CurrentService: model.USER_AUTH_SERVICE_EMAIL, 2152 NewService: model.USER_AUTH_SERVICE_GITLAB, 2153 Email: th.BasicUser.Email, 2154 Password: th.BasicUser.Password, 2155 } 2156 2157 link, resp := Client.SwitchAccountType(sr) 2158 CheckNoError(t, resp) 2159 2160 if link == "" { 2161 t.Fatal("bad link") 2162 } 2163 2164 th.App.SetLicense(model.NewTestLicense()) 2165 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false }) 2166 2167 sr = &model.SwitchRequest{ 2168 CurrentService: model.USER_AUTH_SERVICE_EMAIL, 2169 NewService: model.USER_AUTH_SERVICE_GITLAB, 2170 } 2171 2172 _, resp = Client.SwitchAccountType(sr) 2173 CheckForbiddenStatus(t, resp) 2174 2175 th.LoginBasic() 2176 2177 sr = &model.SwitchRequest{ 2178 CurrentService: model.USER_AUTH_SERVICE_SAML, 2179 NewService: model.USER_AUTH_SERVICE_EMAIL, 2180 Email: th.BasicUser.Email, 2181 NewPassword: th.BasicUser.Password, 2182 } 2183 2184 _, resp = Client.SwitchAccountType(sr) 2185 CheckForbiddenStatus(t, resp) 2186 2187 sr = &model.SwitchRequest{ 2188 CurrentService: model.USER_AUTH_SERVICE_EMAIL, 2189 NewService: model.USER_AUTH_SERVICE_LDAP, 2190 } 2191 2192 _, resp = Client.SwitchAccountType(sr) 2193 CheckForbiddenStatus(t, resp) 2194 2195 sr = &model.SwitchRequest{ 2196 CurrentService: model.USER_AUTH_SERVICE_LDAP, 2197 NewService: model.USER_AUTH_SERVICE_EMAIL, 2198 } 2199 2200 _, resp = Client.SwitchAccountType(sr) 2201 CheckForbiddenStatus(t, resp) 2202 2203 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = true }) 2204 2205 th.LoginBasic() 2206 2207 fakeAuthData := model.NewId() 2208 if result := <-th.App.Srv.Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true); result.Err != nil { 2209 t.Fatal(result.Err) 2210 } 2211 2212 sr = &model.SwitchRequest{ 2213 CurrentService: model.USER_AUTH_SERVICE_GITLAB, 2214 NewService: model.USER_AUTH_SERVICE_EMAIL, 2215 Email: th.BasicUser.Email, 2216 NewPassword: th.BasicUser.Password, 2217 } 2218 2219 link, resp = Client.SwitchAccountType(sr) 2220 CheckNoError(t, resp) 2221 2222 if link != "/login?extra=signin_change" { 2223 t.Log(link) 2224 t.Fatal("bad link") 2225 } 2226 2227 Client.Logout() 2228 _, resp = Client.Login(th.BasicUser.Email, th.BasicUser.Password) 2229 CheckNoError(t, resp) 2230 Client.Logout() 2231 2232 sr = &model.SwitchRequest{ 2233 CurrentService: model.USER_AUTH_SERVICE_GITLAB, 2234 NewService: model.SERVICE_GOOGLE, 2235 } 2236 2237 _, resp = Client.SwitchAccountType(sr) 2238 CheckBadRequestStatus(t, resp) 2239 2240 sr = &model.SwitchRequest{ 2241 CurrentService: model.USER_AUTH_SERVICE_EMAIL, 2242 NewService: model.USER_AUTH_SERVICE_GITLAB, 2243 Password: th.BasicUser.Password, 2244 } 2245 2246 _, resp = Client.SwitchAccountType(sr) 2247 CheckNotFoundStatus(t, resp) 2248 2249 sr = &model.SwitchRequest{ 2250 CurrentService: model.USER_AUTH_SERVICE_EMAIL, 2251 NewService: model.USER_AUTH_SERVICE_GITLAB, 2252 Email: th.BasicUser.Email, 2253 } 2254 2255 _, resp = Client.SwitchAccountType(sr) 2256 CheckUnauthorizedStatus(t, resp) 2257 2258 sr = &model.SwitchRequest{ 2259 CurrentService: model.USER_AUTH_SERVICE_GITLAB, 2260 NewService: model.USER_AUTH_SERVICE_EMAIL, 2261 Email: th.BasicUser.Email, 2262 NewPassword: th.BasicUser.Password, 2263 } 2264 2265 _, resp = Client.SwitchAccountType(sr) 2266 CheckUnauthorizedStatus(t, resp) 2267 } 2268 2269 func TestCreateUserAccessToken(t *testing.T) { 2270 th := Setup().InitBasic().InitSystemAdmin() 2271 defer th.TearDown() 2272 Client := th.Client 2273 AdminClient := th.SystemAdminClient 2274 2275 testDescription := "test token" 2276 2277 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2278 2279 _, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2280 CheckForbiddenStatus(t, resp) 2281 2282 _, resp = Client.CreateUserAccessToken("notarealuserid", testDescription) 2283 CheckBadRequestStatus(t, resp) 2284 2285 _, resp = Client.CreateUserAccessToken(th.BasicUser.Id, "") 2286 CheckBadRequestStatus(t, resp) 2287 2288 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2289 2290 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false }) 2291 _, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2292 CheckNotImplementedStatus(t, resp) 2293 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2294 2295 rtoken, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2296 CheckNoError(t, resp) 2297 2298 if rtoken.UserId != th.BasicUser.Id { 2299 t.Fatal("wrong user id") 2300 } else if rtoken.Token == "" { 2301 t.Fatal("token should not be empty") 2302 } else if rtoken.Id == "" { 2303 t.Fatal("id should not be empty") 2304 } else if rtoken.Description != testDescription { 2305 t.Fatal("description did not match") 2306 } else if !rtoken.IsActive { 2307 t.Fatal("token should be active") 2308 } 2309 2310 oldSessionToken := Client.AuthToken 2311 Client.AuthToken = rtoken.Token 2312 ruser, resp := Client.GetMe("") 2313 CheckNoError(t, resp) 2314 2315 if ruser.Id != th.BasicUser.Id { 2316 t.Fatal("returned wrong user") 2317 } 2318 2319 Client.AuthToken = oldSessionToken 2320 2321 _, resp = Client.CreateUserAccessToken(th.BasicUser2.Id, testDescription) 2322 CheckForbiddenStatus(t, resp) 2323 2324 rtoken, resp = AdminClient.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2325 CheckNoError(t, resp) 2326 2327 if rtoken.UserId != th.BasicUser.Id { 2328 t.Fatal("wrong user id") 2329 } 2330 2331 oldSessionToken = Client.AuthToken 2332 Client.AuthToken = rtoken.Token 2333 ruser, resp = Client.GetMe("") 2334 CheckNoError(t, resp) 2335 2336 if ruser.Id != th.BasicUser.Id { 2337 t.Fatal("returned wrong user") 2338 } 2339 2340 Client.AuthToken = oldSessionToken 2341 2342 session, _ := th.App.GetSession(Client.AuthToken) 2343 session.IsOAuth = true 2344 th.App.AddSessionToCache(session) 2345 2346 _, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2347 CheckForbiddenStatus(t, resp) 2348 } 2349 2350 func TestGetUserAccessToken(t *testing.T) { 2351 th := Setup().InitBasic().InitSystemAdmin() 2352 defer th.TearDown() 2353 Client := th.Client 2354 AdminClient := th.SystemAdminClient 2355 2356 testDescription := "test token" 2357 2358 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2359 2360 _, resp := Client.GetUserAccessToken("123") 2361 CheckBadRequestStatus(t, resp) 2362 2363 _, resp = Client.GetUserAccessToken(model.NewId()) 2364 CheckForbiddenStatus(t, resp) 2365 2366 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2367 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2368 CheckNoError(t, resp) 2369 2370 rtoken, resp := Client.GetUserAccessToken(token.Id) 2371 CheckNoError(t, resp) 2372 2373 if rtoken.UserId != th.BasicUser.Id { 2374 t.Fatal("wrong user id") 2375 } else if rtoken.Token != "" { 2376 t.Fatal("token should be blank") 2377 } else if rtoken.Id == "" { 2378 t.Fatal("id should not be empty") 2379 } else if rtoken.Description != testDescription { 2380 t.Fatal("description did not match") 2381 } 2382 2383 _, resp = AdminClient.GetUserAccessToken(token.Id) 2384 CheckNoError(t, resp) 2385 2386 token, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2387 CheckNoError(t, resp) 2388 2389 rtokens, resp := Client.GetUserAccessTokensForUser(th.BasicUser.Id, 0, 100) 2390 CheckNoError(t, resp) 2391 2392 if len(rtokens) != 2 { 2393 t.Fatal("should have 2 tokens") 2394 } 2395 2396 for _, uat := range rtokens { 2397 if uat.UserId != th.BasicUser.Id { 2398 t.Fatal("wrong user id") 2399 } 2400 } 2401 2402 rtokens, resp = Client.GetUserAccessTokensForUser(th.BasicUser.Id, 1, 1) 2403 CheckNoError(t, resp) 2404 2405 if len(rtokens) != 1 { 2406 t.Fatal("should have 1 token") 2407 } 2408 2409 rtokens, resp = AdminClient.GetUserAccessTokensForUser(th.BasicUser.Id, 0, 100) 2410 CheckNoError(t, resp) 2411 2412 if len(rtokens) != 2 { 2413 t.Fatal("should have 2 tokens") 2414 } 2415 2416 _, resp = Client.GetUserAccessTokens(0, 100) 2417 CheckForbiddenStatus(t, resp) 2418 2419 rtokens, resp = AdminClient.GetUserAccessTokens(1, 1) 2420 CheckNoError(t, resp) 2421 2422 if len(rtokens) != 1 { 2423 t.Fatal("should have 1 token") 2424 } 2425 2426 rtokens, resp = AdminClient.GetUserAccessTokens(0, 2) 2427 CheckNoError(t, resp) 2428 2429 if len(rtokens) != 2 { 2430 t.Fatal("should have 2 tokens") 2431 } 2432 } 2433 2434 func TestSearchUserAccessToken(t *testing.T) { 2435 th := Setup().InitBasic().InitSystemAdmin() 2436 defer th.TearDown() 2437 Client := th.Client 2438 AdminClient := th.SystemAdminClient 2439 2440 testDescription := "test token" 2441 2442 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2443 2444 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2445 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2446 CheckNoError(t, resp) 2447 2448 _, resp = Client.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id}) 2449 CheckForbiddenStatus(t, resp) 2450 2451 rtokens, resp := AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Id}) 2452 CheckNoError(t, resp) 2453 2454 if len(rtokens) != 1 { 2455 t.Fatal("should have 1 tokens") 2456 } 2457 2458 rtokens, resp = AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id}) 2459 CheckNoError(t, resp) 2460 2461 if len(rtokens) != 1 { 2462 t.Fatal("should have 1 tokens") 2463 } 2464 2465 rtokens, resp = AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Username}) 2466 CheckNoError(t, resp) 2467 2468 if len(rtokens) != 1 { 2469 t.Fatal("should have 1 tokens") 2470 } 2471 2472 rtokens, resp = AdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: "not found"}) 2473 CheckNoError(t, resp) 2474 2475 if len(rtokens) != 0 { 2476 t.Fatal("should have 0 tokens") 2477 } 2478 } 2479 2480 func TestRevokeUserAccessToken(t *testing.T) { 2481 th := Setup().InitBasic().InitSystemAdmin() 2482 defer th.TearDown() 2483 Client := th.Client 2484 AdminClient := th.SystemAdminClient 2485 2486 testDescription := "test token" 2487 2488 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2489 2490 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2491 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2492 CheckNoError(t, resp) 2493 2494 oldSessionToken := Client.AuthToken 2495 Client.AuthToken = token.Token 2496 _, resp = Client.GetMe("") 2497 CheckNoError(t, resp) 2498 Client.AuthToken = oldSessionToken 2499 2500 ok, resp := Client.RevokeUserAccessToken(token.Id) 2501 CheckNoError(t, resp) 2502 2503 if !ok { 2504 t.Fatal("should have passed") 2505 } 2506 2507 oldSessionToken = Client.AuthToken 2508 Client.AuthToken = token.Token 2509 _, resp = Client.GetMe("") 2510 CheckUnauthorizedStatus(t, resp) 2511 Client.AuthToken = oldSessionToken 2512 2513 token, resp = AdminClient.CreateUserAccessToken(th.BasicUser2.Id, testDescription) 2514 CheckNoError(t, resp) 2515 2516 ok, resp = Client.RevokeUserAccessToken(token.Id) 2517 CheckForbiddenStatus(t, resp) 2518 2519 if ok { 2520 t.Fatal("should have failed") 2521 } 2522 } 2523 2524 func TestDisableUserAccessToken(t *testing.T) { 2525 th := Setup().InitBasic().InitSystemAdmin() 2526 defer th.TearDown() 2527 Client := th.Client 2528 AdminClient := th.SystemAdminClient 2529 2530 testDescription := "test token" 2531 2532 *th.App.Config().ServiceSettings.EnableUserAccessTokens = true 2533 2534 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2535 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2536 CheckNoError(t, resp) 2537 2538 oldSessionToken := Client.AuthToken 2539 Client.AuthToken = token.Token 2540 _, resp = Client.GetMe("") 2541 CheckNoError(t, resp) 2542 Client.AuthToken = oldSessionToken 2543 2544 ok, resp := Client.DisableUserAccessToken(token.Id) 2545 CheckNoError(t, resp) 2546 2547 if !ok { 2548 t.Fatal("should have passed") 2549 } 2550 2551 oldSessionToken = Client.AuthToken 2552 Client.AuthToken = token.Token 2553 _, resp = Client.GetMe("") 2554 CheckUnauthorizedStatus(t, resp) 2555 Client.AuthToken = oldSessionToken 2556 2557 token, resp = AdminClient.CreateUserAccessToken(th.BasicUser2.Id, testDescription) 2558 CheckNoError(t, resp) 2559 2560 ok, resp = Client.DisableUserAccessToken(token.Id) 2561 CheckForbiddenStatus(t, resp) 2562 2563 if ok { 2564 t.Fatal("should have failed") 2565 } 2566 } 2567 2568 func TestEnableUserAccessToken(t *testing.T) { 2569 th := Setup().InitBasic().InitSystemAdmin() 2570 defer th.TearDown() 2571 Client := th.Client 2572 2573 testDescription := "test token" 2574 2575 *th.App.Config().ServiceSettings.EnableUserAccessTokens = true 2576 2577 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2578 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2579 CheckNoError(t, resp) 2580 2581 oldSessionToken := Client.AuthToken 2582 Client.AuthToken = token.Token 2583 _, resp = Client.GetMe("") 2584 CheckNoError(t, resp) 2585 Client.AuthToken = oldSessionToken 2586 2587 _, resp = Client.DisableUserAccessToken(token.Id) 2588 CheckNoError(t, resp) 2589 2590 oldSessionToken = Client.AuthToken 2591 Client.AuthToken = token.Token 2592 _, resp = Client.GetMe("") 2593 CheckUnauthorizedStatus(t, resp) 2594 Client.AuthToken = oldSessionToken 2595 2596 ok, resp := Client.EnableUserAccessToken(token.Id) 2597 CheckNoError(t, resp) 2598 2599 if !ok { 2600 t.Fatal("should have passed") 2601 } 2602 2603 oldSessionToken = Client.AuthToken 2604 Client.AuthToken = token.Token 2605 _, resp = Client.GetMe("") 2606 CheckNoError(t, resp) 2607 Client.AuthToken = oldSessionToken 2608 } 2609 2610 func TestUserAccessTokenInactiveUser(t *testing.T) { 2611 th := Setup().InitBasic().InitSystemAdmin() 2612 defer th.TearDown() 2613 Client := th.Client 2614 2615 testDescription := "test token" 2616 2617 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2618 2619 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2620 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2621 CheckNoError(t, resp) 2622 2623 Client.AuthToken = token.Token 2624 _, resp = Client.GetMe("") 2625 CheckNoError(t, resp) 2626 2627 th.App.UpdateActive(th.BasicUser, false) 2628 2629 _, resp = Client.GetMe("") 2630 CheckUnauthorizedStatus(t, resp) 2631 } 2632 2633 func TestUserAccessTokenDisableConfig(t *testing.T) { 2634 th := Setup().InitBasic().InitSystemAdmin() 2635 defer th.TearDown() 2636 Client := th.Client 2637 2638 testDescription := "test token" 2639 2640 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = true }) 2641 2642 th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_USER_ACCESS_TOKEN_ROLE_ID, false) 2643 token, resp := Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) 2644 CheckNoError(t, resp) 2645 2646 oldSessionToken := Client.AuthToken 2647 Client.AuthToken = token.Token 2648 _, resp = Client.GetMe("") 2649 CheckNoError(t, resp) 2650 2651 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableUserAccessTokens = false }) 2652 2653 _, resp = Client.GetMe("") 2654 CheckUnauthorizedStatus(t, resp) 2655 2656 Client.AuthToken = oldSessionToken 2657 _, resp = Client.GetMe("") 2658 CheckNoError(t, resp) 2659 } 2660 2661 func TestGetUsersByStatus(t *testing.T) { 2662 th := Setup() 2663 defer th.TearDown() 2664 2665 team, err := th.App.CreateTeam(&model.Team{ 2666 DisplayName: "dn_" + model.NewId(), 2667 Name: GenerateTestTeamName(), 2668 Email: th.GenerateTestEmail(), 2669 Type: model.TEAM_OPEN, 2670 }) 2671 if err != nil { 2672 t.Fatalf("failed to create team: %v", err) 2673 } 2674 2675 channel, err := th.App.CreateChannel(&model.Channel{ 2676 DisplayName: "dn_" + model.NewId(), 2677 Name: "name_" + model.NewId(), 2678 Type: model.CHANNEL_OPEN, 2679 TeamId: team.Id, 2680 CreatorId: model.NewId(), 2681 }, false) 2682 if err != nil { 2683 t.Fatalf("failed to create channel: %v", err) 2684 } 2685 2686 createUserWithStatus := func(username string, status string) *model.User { 2687 id := model.NewId() 2688 2689 user, err := th.App.CreateUser(&model.User{ 2690 Email: "success+" + id + "@simulator.amazonses.com", 2691 Username: "un_" + username + "_" + id, 2692 Nickname: "nn_" + id, 2693 Password: "Password1", 2694 }) 2695 if err != nil { 2696 t.Fatalf("failed to create user: %v", err) 2697 } 2698 2699 th.LinkUserToTeam(user, team) 2700 th.AddUserToChannel(user, channel) 2701 2702 th.App.SaveAndBroadcastStatus(&model.Status{ 2703 UserId: user.Id, 2704 Status: status, 2705 Manual: true, 2706 }) 2707 2708 return user 2709 } 2710 2711 // Creating these out of order in case that affects results 2712 offlineUser1 := createUserWithStatus("offline1", model.STATUS_OFFLINE) 2713 offlineUser2 := createUserWithStatus("offline2", model.STATUS_OFFLINE) 2714 awayUser1 := createUserWithStatus("away1", model.STATUS_AWAY) 2715 awayUser2 := createUserWithStatus("away2", model.STATUS_AWAY) 2716 onlineUser1 := createUserWithStatus("online1", model.STATUS_ONLINE) 2717 onlineUser2 := createUserWithStatus("online2", model.STATUS_ONLINE) 2718 dndUser1 := createUserWithStatus("dnd1", model.STATUS_DND) 2719 dndUser2 := createUserWithStatus("dnd2", model.STATUS_DND) 2720 2721 client := th.CreateClient() 2722 if _, resp := client.Login(onlineUser2.Username, "Password1"); resp.Error != nil { 2723 t.Fatal(resp.Error) 2724 } 2725 2726 t.Run("sorting by status then alphabetical", func(t *testing.T) { 2727 usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 8, "") 2728 if resp.Error != nil { 2729 t.Fatal(resp.Error) 2730 } 2731 2732 expectedUsersByStatus := []*model.User{ 2733 onlineUser1, 2734 onlineUser2, 2735 awayUser1, 2736 awayUser2, 2737 dndUser1, 2738 dndUser2, 2739 offlineUser1, 2740 offlineUser2, 2741 } 2742 2743 if len(usersByStatus) != len(expectedUsersByStatus) { 2744 t.Fatalf("received only %v users, expected %v", len(usersByStatus), len(expectedUsersByStatus)) 2745 } 2746 2747 for i := range usersByStatus { 2748 if usersByStatus[i].Id != expectedUsersByStatus[i].Id { 2749 t.Fatalf("received user %v at index %v, expected %v", usersByStatus[i].Username, i, expectedUsersByStatus[i].Username) 2750 } 2751 } 2752 }) 2753 2754 t.Run("paging", func(t *testing.T) { 2755 usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 3, "") 2756 if resp.Error != nil { 2757 t.Fatal(resp.Error) 2758 } 2759 2760 if len(usersByStatus) != 3 { 2761 t.Fatal("received too many users") 2762 } 2763 2764 if usersByStatus[0].Id != onlineUser1.Id && usersByStatus[1].Id != onlineUser2.Id { 2765 t.Fatal("expected to receive online users first") 2766 } 2767 2768 if usersByStatus[2].Id != awayUser1.Id { 2769 t.Fatal("expected to receive away users second") 2770 } 2771 2772 usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 3, "") 2773 if resp.Error != nil { 2774 t.Fatal(resp.Error) 2775 } 2776 2777 if usersByStatus[0].Id != awayUser2.Id { 2778 t.Fatal("expected to receive away users second") 2779 } 2780 2781 if usersByStatus[1].Id != dndUser1.Id && usersByStatus[2].Id != dndUser2.Id { 2782 t.Fatal("expected to receive dnd users third") 2783 } 2784 2785 usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 4, "") 2786 if resp.Error != nil { 2787 t.Fatal(resp.Error) 2788 } 2789 2790 if len(usersByStatus) != 4 { 2791 t.Fatal("received too many users") 2792 } 2793 2794 if usersByStatus[0].Id != dndUser1.Id && usersByStatus[1].Id != dndUser2.Id { 2795 t.Fatal("expected to receive dnd users third") 2796 } 2797 2798 if usersByStatus[2].Id != offlineUser1.Id && usersByStatus[3].Id != offlineUser2.Id { 2799 t.Fatal("expected to receive offline users last") 2800 } 2801 }) 2802 }