github.com/resonatecoop/id@v1.1.0-43/oauth/grant_type_password_test.go (about) 1 package oauth_test 2 3 import ( 4 "context" 5 "net/http" 6 "net/http/httptest" 7 "net/url" 8 9 "github.com/resonatecoop/id/oauth" 10 11 "github.com/resonatecoop/id/oauth/tokentypes" 12 testutil "github.com/resonatecoop/id/test-util" 13 "github.com/resonatecoop/user-api/model" 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func (suite *OauthTestSuite) TestPasswordGrant() { 18 // Prepare a request 19 r, err := http.NewRequest("POST", "http://1.2.3.4/v1/oauth/tokens", nil) 20 assert.NoError(suite.T(), err, "Request setup should not get an error") 21 r.SetBasicAuth("test_client_1", "test_secret") 22 r.PostForm = url.Values{ 23 "grant_type": {"password"}, 24 "username": {"test@user.com"}, 25 "password": {"test_password"}, 26 "scope": {"read_write artist"}, 27 } 28 29 // Serve the request 30 w := httptest.NewRecorder() 31 suite.router.ServeHTTP(w, r) 32 33 // Fetch data 34 accessToken, refreshToken := new(model.AccessToken), new(model.RefreshToken) 35 36 ctx := context.Background() 37 38 err = suite.db.NewSelect(). 39 Model(accessToken). 40 Limit(1). 41 Scan(ctx) 42 43 // an access token is found 44 assert.Nil(suite.T(), err) 45 46 err = suite.db.NewSelect(). 47 Model(refreshToken). 48 Limit(1). 49 Scan(ctx) 50 51 // a refresh token is founds 52 assert.Nil(suite.T(), err) 53 54 // Check the response 55 expected := &oauth.AccessTokenResponse{ 56 UserID: accessToken.UserID.String(), 57 AccessToken: accessToken.Token, 58 ExpiresIn: 3600, 59 TokenType: tokentypes.Bearer, 60 Scope: "read_write artist", 61 RefreshToken: refreshToken.Token, 62 } 63 testutil.TestResponseObject(suite.T(), w, expected, 200) 64 } 65 66 func (suite *OauthTestSuite) TestPasswordGrantWithRoleRestriction() { 67 suite.service.RestrictToRoles(int32(model.SuperAdminRole)) 68 69 // Prepare a request 70 r, err := http.NewRequest("POST", "http://1.2.3.4/v1/oauth/tokens", nil) 71 assert.NoError(suite.T(), err, "Request setup should not get an error") 72 r.SetBasicAuth("test_client_1", "test_secret") 73 r.PostForm = url.Values{ 74 "grant_type": {"password"}, 75 "username": {"test@user.com"}, 76 "password": {"test_password"}, 77 "scope": {"read_write artist"}, 78 } 79 80 // Serve the request 81 w := httptest.NewRecorder() 82 suite.router.ServeHTTP(w, r) 83 84 // Check the response 85 testutil.TestResponseForError( 86 suite.T(), 87 w, 88 oauth.ErrInvalidUsernameOrPassword.Error(), 89 401, 90 ) 91 92 suite.service.RestrictToRoles(int32(model.SuperAdminRole), int32(model.AdminRole), int32(model.TenantAdminRole), int32(model.LabelRole), int32(model.ArtistRole), int32(model.UserRole)) 93 }