From edcc793a338a36ee68e1dbe0f5ba9e04018e362b Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Tue, 9 Apr 2024 14:40:00 +0530 Subject: [PATCH] moves tests around and removes tpep folder --- frontendDriverInterfaceSupported.json | 3 +- .../api/userdetails/userPasswordPut.go | 59 +- recipe/dashboard/api/userdetails/userPut.go | 41 - recipe/dashboard/api/utils.go | 49 - recipe/dashboard/testingUtils.go | 2 - recipe/dashboard/userGet_test.go | 19 +- recipe/dashboard/userPasswordPut_test.go | 10 +- recipe/dashboard/userPut_test.go | 10 +- recipe/emailpassword/authFlow_test.go | 54 + .../signinFeature_test.go} | 179 +--- .../signoutFeature_test.go | 10 +- .../userIdMapping_create_test.go | 75 ++ recipe/thirdparty/email_test.go | 181 ++++ recipe/thirdparty/signinupFeature_test.go | 103 ++ recipe/thirdparty/testingUtils.go | 2 +- .../api/emailPasswordAPIImplementation.go | 103 -- .../api/implementation.go | 185 ---- .../api/thirdPartyAPIImplementation.go | 78 -- .../backwardCompatibilityService/main.go | 46 - .../emaildelivery/smtpService/main.go | 42 - recipe/thirdpartyemailpassword/main.go | 240 ----- recipe/thirdpartyemailpassword/recipe.go | 220 ---- .../emailPasswordRecipeImplementation.go | 122 --- .../recipeimplementation/main.go | 328 ------ .../thirdPartyRecipeImplementation.go | 149 --- .../signinFeature_test.go | 458 --------- .../thirdpartyemailpassword/testingUtils.go | 160 --- .../tpep_email_test.go | 968 ------------------ .../tpep_userIdMapping_test.go | 166 --- .../tpepmodels/apiInterface.go | 80 -- .../tpepmodels/models.go | 62 -- .../tpepmodels/recipeInterface.go | 68 -- recipe/thirdpartyemailpassword/utils.go | 79 -- test/auth-react-server/main.go | 259 +++-- 34 files changed, 610 insertions(+), 4000 deletions(-) rename recipe/{thirdpartyemailpassword/signupFeature_test.go => emailpassword/signinFeature_test.go} (50%) rename recipe/{thirdpartyemailpassword => emailpassword}/signoutFeature_test.go (94%) create mode 100644 recipe/thirdparty/email_test.go delete mode 100644 recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.go delete mode 100644 recipe/thirdpartyemailpassword/api/implementation.go delete mode 100644 recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.go delete mode 100644 recipe/thirdpartyemailpassword/emaildelivery/backwardCompatibilityService/main.go delete mode 100644 recipe/thirdpartyemailpassword/emaildelivery/smtpService/main.go delete mode 100644 recipe/thirdpartyemailpassword/main.go delete mode 100644 recipe/thirdpartyemailpassword/recipe.go delete mode 100644 recipe/thirdpartyemailpassword/recipeimplementation/emailPasswordRecipeImplementation.go delete mode 100644 recipe/thirdpartyemailpassword/recipeimplementation/main.go delete mode 100644 recipe/thirdpartyemailpassword/recipeimplementation/thirdPartyRecipeImplementation.go delete mode 100644 recipe/thirdpartyemailpassword/signinFeature_test.go delete mode 100644 recipe/thirdpartyemailpassword/testingUtils.go delete mode 100644 recipe/thirdpartyemailpassword/tpep_email_test.go delete mode 100644 recipe/thirdpartyemailpassword/tpep_userIdMapping_test.go delete mode 100644 recipe/thirdpartyemailpassword/tpepmodels/apiInterface.go delete mode 100644 recipe/thirdpartyemailpassword/tpepmodels/models.go delete mode 100644 recipe/thirdpartyemailpassword/tpepmodels/recipeInterface.go delete mode 100644 recipe/thirdpartyemailpassword/utils.go diff --git a/frontendDriverInterfaceSupported.json b/frontendDriverInterfaceSupported.json index 0d1267d8..8ca4e370 100644 --- a/frontendDriverInterfaceSupported.json +++ b/frontendDriverInterfaceSupported.json @@ -1,6 +1,7 @@ { "_comment": "contains a list of frontend-driver interfaces branch names that this core supports", "versions": [ - "1.17" + "1.17", + "2.0" ] } \ No newline at end of file diff --git a/recipe/dashboard/api/userdetails/userPasswordPut.go b/recipe/dashboard/api/userdetails/userPasswordPut.go index 672e195b..bff11fdf 100644 --- a/recipe/dashboard/api/userdetails/userPasswordPut.go +++ b/recipe/dashboard/api/userdetails/userPasswordPut.go @@ -22,7 +22,6 @@ import ( "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" "github.com/supertokens/supertokens-golang/recipe/emailpassword" "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" "github.com/supertokens/supertokens-golang/supertokens" ) @@ -69,66 +68,14 @@ func UserPasswordPut(apiInterface dashboardmodels.APIInterface, tenantId string, recipeToUse = "emailpassword" } - if recipeToUse == "none" { - tpepInstance := thirdpartyemailpassword.GetRecipeInstance() - - if tpepInstance != nil { - recipeToUse = "thirdpartyemailpassword" - } - } - if recipeToUse == "none" { // This means that neither emailpassword or thirdpartyemailpassword is initialised return userPasswordPutResponse{}, errors.New("Should never come here") } - if recipeToUse == "emailpassword" { - var passwordField epmodels.NormalisedFormField - - for _, value := range emailPasswordInstance.Config.SignUpFeature.FormFields { - if value.ID == "password" { - passwordField = value - } - } - - validationError := passwordField.Validate(*readBody.NewPassword, tenantId) - - if validationError != nil { - return userPasswordPutResponse{ - Status: "INVALID_PASSWORD_ERROR", - Error: *validationError, - }, nil - } - - passwordResetToken, resetTokenErr := emailpassword.CreateResetPasswordToken(tenantId, *readBody.UserId, userContext) - - if resetTokenErr != nil { - return userPasswordPutResponse{}, resetTokenErr - } - - if passwordResetToken.UnknownUserIdError != nil { - // Techincally it can but its an edge case so we assume that it wont - return userPasswordPutResponse{}, errors.New("Should never come here") - } - - passwordResetResponse, passwordResetErr := emailpassword.ResetPasswordUsingToken(tenantId, passwordResetToken.OK.Token, *readBody.NewPassword, userContext) - - if passwordResetErr != nil { - return userPasswordPutResponse{}, passwordResetErr - } - - if passwordResetResponse.ResetPasswordInvalidTokenError != nil { - return userPasswordPutResponse{}, errors.New("Should never come here") - } - - return userPasswordPutResponse{ - Status: "OK", - }, nil - } - var passwordField epmodels.NormalisedFormField - for _, value := range thirdpartyemailpassword.GetRecipeInstance().GetEmailPasswordRecipe().Config.SignUpFeature.FormFields { + for _, value := range emailPasswordInstance.Config.SignUpFeature.FormFields { if value.ID == "password" { passwordField = value } @@ -143,7 +90,7 @@ func UserPasswordPut(apiInterface dashboardmodels.APIInterface, tenantId string, }, nil } - passwordResetToken, resetTokenErr := thirdpartyemailpassword.CreateResetPasswordToken(tenantId, *readBody.UserId, userContext) + passwordResetToken, resetTokenErr := emailpassword.CreateResetPasswordToken(tenantId, *readBody.UserId, userContext) if resetTokenErr != nil { return userPasswordPutResponse{}, resetTokenErr @@ -154,7 +101,7 @@ func UserPasswordPut(apiInterface dashboardmodels.APIInterface, tenantId string, return userPasswordPutResponse{}, errors.New("Should never come here") } - passwordResetResponse, passwordResetErr := thirdpartyemailpassword.ResetPasswordUsingToken(tenantId, passwordResetToken.OK.Token, *readBody.NewPassword, userContext) + passwordResetResponse, passwordResetErr := emailpassword.ResetPasswordUsingToken(tenantId, passwordResetToken.OK.Token, *readBody.NewPassword, userContext) if passwordResetErr != nil { return userPasswordPutResponse{}, passwordResetErr diff --git a/recipe/dashboard/api/userdetails/userPut.go b/recipe/dashboard/api/userdetails/userPut.go index c778f05d..4320f06c 100644 --- a/recipe/dashboard/api/userdetails/userPut.go +++ b/recipe/dashboard/api/userdetails/userPut.go @@ -25,7 +25,6 @@ import ( "github.com/supertokens/supertokens-golang/recipe/emailpassword" "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" "github.com/supertokens/supertokens-golang/recipe/passwordless" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless" "github.com/supertokens/supertokens-golang/recipe/usermetadata" "github.com/supertokens/supertokens-golang/supertokens" @@ -95,46 +94,6 @@ func updateEmailForRecipeId(recipeId string, userId string, email string, tenant }, nil } - if recipeId == "thirdpartyemailpassword" { - var emailField epmodels.NormalisedFormField - - for _, value := range thirdpartyemailpassword.GetRecipeInstance().GetEmailPasswordRecipe().Config.SignUpFeature.FormFields { - if value.ID == "email" { - emailField = value - } - } - - validationError := emailField.Validate(email, tenantId) - - if validationError != nil { - return updateEmailResponse{ - Status: "INVALID_EMAIL_ERROR", - Error: *validationError, - }, nil - } - - tenantId := "public" - updateResponse, err := thirdpartyemailpassword.UpdateEmailOrPassword(userId, &email, nil, nil, &tenantId, userContext) - - if err != nil { - return updateEmailResponse{}, err - } - - if updateResponse.EmailAlreadyExistsError != nil { - return updateEmailResponse{ - Status: "EMAIL_ALREADY_EXISTS_ERROR", - }, nil - } - - if updateResponse.UnknownUserIdError != nil { - return updateEmailResponse{}, errors.New("Should never come here") - } - - return updateEmailResponse{ - Status: "OK", - }, nil - } - if recipeId == "passwordless" { isValidEmail := true validationError := "" diff --git a/recipe/dashboard/api/utils.go b/recipe/dashboard/api/utils.go index 5134d1f3..7179f08c 100644 --- a/recipe/dashboard/api/utils.go +++ b/recipe/dashboard/api/utils.go @@ -7,7 +7,6 @@ import ( "github.com/supertokens/supertokens-golang/recipe/emailpassword" "github.com/supertokens/supertokens-golang/recipe/passwordless" "github.com/supertokens/supertokens-golang/recipe/thirdparty" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless" "github.com/supertokens/supertokens-golang/supertokens" ) @@ -45,21 +44,6 @@ func GetUserForRecipeId(userId string, recipeId string, userContext supertokens. recipeToReturn = emailpassword.RECIPE_ID } - - if reflect.DeepEqual(userToReturn, dashboardmodels.UserType{}) { - tpepResponse, tpepError := thirdpartyemailpassword.GetUserById(userId, userContext) - - if tpepError == nil && tpepResponse != nil { - userToReturn.Id = tpepResponse.ID - userToReturn.TimeJoined = tpepResponse.TimeJoined - userToReturn.FirstName = "" - userToReturn.LastName = "" - userToReturn.Email = tpepResponse.Email - userToReturn.TenantIds = tpepResponse.TenantIds - - recipeToReturn = thirdpartyemailpassword.RECIPE_ID - } - } } else if recipeId == thirdparty.RECIPE_ID { response, error := thirdparty.GetUserByID(userId, userContext) @@ -76,23 +60,6 @@ func GetUserForRecipeId(userId string, recipeId string, userContext supertokens. userToReturn.TenantIds = response.TenantIds } - if reflect.DeepEqual(userToReturn, dashboardmodels.UserType{}) { - tpepResponse, tpepError := thirdpartyemailpassword.GetUserById(userId, userContext) - - if tpepError == nil && tpepResponse != nil { - userToReturn.Id = tpepResponse.ID - userToReturn.TimeJoined = tpepResponse.TimeJoined - userToReturn.FirstName = "" - userToReturn.LastName = "" - userToReturn.Email = tpepResponse.Email - userToReturn.ThirdParty = &dashboardmodels.ThirdParty{ - Id: tpepResponse.ThirdParty.ID, - UserId: tpepResponse.ThirdParty.UserID, - } - userToReturn.TenantIds = tpepResponse.TenantIds - } - } - if reflect.DeepEqual(userToReturn, dashboardmodels.UserType{}) { tpplessResponse, tpplessError := thirdpartypasswordless.GetUserById(userId, userContext) @@ -171,14 +138,6 @@ func IsRecipeInitialised(recipeId string) bool { if err == nil { isRecipeInitialised = true } - - if !isRecipeInitialised { - _, err := thirdpartyemailpassword.GetRecipeInstanceOrThrowError() - - if err == nil { - isRecipeInitialised = true - } - } } else if recipeId == passwordless.RECIPE_ID { _, err := passwordless.GetRecipeInstanceOrThrowError() @@ -200,14 +159,6 @@ func IsRecipeInitialised(recipeId string) bool { isRecipeInitialised = true } - if !isRecipeInitialised { - _, err := thirdpartyemailpassword.GetRecipeInstanceOrThrowError() - - if err == nil { - isRecipeInitialised = true - } - } - if !isRecipeInitialised { _, err := thirdpartypasswordless.GetRecipeInstanceOrThrowError() diff --git a/recipe/dashboard/testingUtils.go b/recipe/dashboard/testingUtils.go index 0763f1f9..43e80591 100644 --- a/recipe/dashboard/testingUtils.go +++ b/recipe/dashboard/testingUtils.go @@ -20,7 +20,6 @@ import ( "github.com/supertokens/supertokens-golang/recipe/multitenancy" "github.com/supertokens/supertokens-golang/recipe/session" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" "github.com/supertokens/supertokens-golang/supertokens" "github.com/supertokens/supertokens-golang/test/unittesting" @@ -30,7 +29,6 @@ func resetAll() { supertokens.ResetForTest() ResetForTest() session.ResetForTest() - thirdpartyemailpassword.ResetForTest() multitenancy.ResetForTest() } diff --git a/recipe/dashboard/userGet_test.go b/recipe/dashboard/userGet_test.go index 8bdd34a2..7f6b8b5c 100644 --- a/recipe/dashboard/userGet_test.go +++ b/recipe/dashboard/userGet_test.go @@ -2,29 +2,28 @@ package dashboard import ( "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "github.com/supertokens/supertokens-golang/recipe/dashboard/api" "github.com/supertokens/supertokens-golang/recipe/dashboard/api/userdetails" + "github.com/supertokens/supertokens-golang/recipe/emailpassword" "github.com/supertokens/supertokens-golang/recipe/passwordless/plessmodels" "github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless/tplmodels" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" "github.com/stretchr/testify/assert" "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" "github.com/supertokens/supertokens-golang/supertokens" "github.com/supertokens/supertokens-golang/test/unittesting" ) /* -- Initialise with thirdpartyemailpassword and provide no custom form fields -- Create an emailpassword user using the thirdpartyemailpassword recipe - Get user from the user get API - Check that user has public tenant */ @@ -42,7 +41,7 @@ func TestThatUserGetReturnsTenantIDsCorrectly(t *testing.T) { WebsiteDomain: "supertokens.io", }, RecipeList: []supertokens.Recipe{ - thirdpartyemailpassword.Init(nil), + emailpassword.Init(nil), Init(&dashboardmodels.TypeInput{ ApiKey: "testapikey", }), @@ -61,7 +60,7 @@ func TestThatUserGetReturnsTenantIDsCorrectly(t *testing.T) { testServer := httptest.NewServer(supertokens.Middleware(mux)) defer testServer.Close() - signupResponse, err := thirdpartyemailpassword.EmailPasswordSignUp("public", "testing@supertokens.com", "abcd1234") + signupResponse, err := emailpassword.SignUp("public", "testing@supertokens.com", "abcd1234") if err != nil { t.Error(err.Error()) } diff --git a/recipe/dashboard/userPasswordPut_test.go b/recipe/dashboard/userPasswordPut_test.go index a85421f9..30442361 100644 --- a/recipe/dashboard/userPasswordPut_test.go +++ b/recipe/dashboard/userPasswordPut_test.go @@ -8,14 +8,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" + "github.com/supertokens/supertokens-golang/recipe/emailpassword" "github.com/supertokens/supertokens-golang/supertokens" "github.com/supertokens/supertokens-golang/test/unittesting" ) /* -- Initialise with thirdpartyemailpassword and provide no custom form fields -- Create an emailpassword user using the thirdpartyemailpassword recipe - Try to change the password of the user - Should result in no errors - Sign in with new password @@ -35,7 +33,7 @@ func TestThatUpdatingPasswordWithNoSignUpFeatureInTPEPWorks(t *testing.T) { WebsiteDomain: "supertokens.io", }, RecipeList: []supertokens.Recipe{ - thirdpartyemailpassword.Init(nil), + emailpassword.Init(nil), Init(&dashboardmodels.TypeInput{ ApiKey: "testapikey", }), @@ -54,7 +52,7 @@ func TestThatUpdatingPasswordWithNoSignUpFeatureInTPEPWorks(t *testing.T) { testServer := httptest.NewServer(supertokens.Middleware(mux)) defer testServer.Close() - signupResponse, err := thirdpartyemailpassword.EmailPasswordSignUp("public", "testing@supertokens.com", "abcd1234") + signupResponse, err := emailpassword.SignUp("public", "testing@supertokens.com", "abcd1234") if err != nil { t.Error(err.Error()) } @@ -78,7 +76,7 @@ func TestThatUpdatingPasswordWithNoSignUpFeatureInTPEPWorks(t *testing.T) { assert.Equal(t, http.StatusOK, res.StatusCode) - signInResponse, err := thirdpartyemailpassword.EmailPasswordSignIn("public", "testing@supertokens.com", "newabcd1234") + signInResponse, err := emailpassword.SignIn("public", "testing@supertokens.com", "newabcd1234") if err != nil { t.Error(err.Error()) } diff --git a/recipe/dashboard/userPut_test.go b/recipe/dashboard/userPut_test.go index de8afb9a..fc15ec8c 100644 --- a/recipe/dashboard/userPut_test.go +++ b/recipe/dashboard/userPut_test.go @@ -8,14 +8,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" + "github.com/supertokens/supertokens-golang/recipe/emailpassword" "github.com/supertokens/supertokens-golang/supertokens" "github.com/supertokens/supertokens-golang/test/unittesting" ) /* -- Initialise with thirdpartyemailpassword and provide no custom form fields -- Create an emailpassword user using the thirdpartyemailpassword recipe - Try to change the password of the user - Should result in no errors - Sign in with new password @@ -35,7 +33,7 @@ func TestThatUpdatingEmailWithNoSignUpFeatureInTPEPWorks(t *testing.T) { WebsiteDomain: "supertokens.io", }, RecipeList: []supertokens.Recipe{ - thirdpartyemailpassword.Init(nil), + emailpassword.Init(nil), Init(&dashboardmodels.TypeInput{ ApiKey: "testapikey", }), @@ -54,7 +52,7 @@ func TestThatUpdatingEmailWithNoSignUpFeatureInTPEPWorks(t *testing.T) { testServer := httptest.NewServer(supertokens.Middleware(mux)) defer testServer.Close() - signupResponse, err := thirdpartyemailpassword.EmailPasswordSignUp("public", "testing@supertokens.com", "abcd1234") + signupResponse, err := emailpassword.SignUp("public", "testing@supertokens.com", "abcd1234") if err != nil { t.Error(err.Error()) } @@ -78,7 +76,7 @@ func TestThatUpdatingEmailWithNoSignUpFeatureInTPEPWorks(t *testing.T) { assert.Equal(t, http.StatusOK, res.StatusCode) - signInResponse, err := thirdpartyemailpassword.EmailPasswordSignIn("public", "testing2@supertokens.com", "abcd1234") + signInResponse, err := emailpassword.SignIn("public", "testing2@supertokens.com", "abcd1234") if err != nil { t.Error(err.Error()) diff --git a/recipe/emailpassword/authFlow_test.go b/recipe/emailpassword/authFlow_test.go index b2233c0a..720d973f 100644 --- a/recipe/emailpassword/authFlow_test.go +++ b/recipe/emailpassword/authFlow_test.go @@ -20,6 +20,7 @@ import ( "bytes" "encoding/json" "io" + "io/ioutil" "net/http" "net/http/httptest" "strconv" @@ -3016,3 +3017,56 @@ func TestInputEmailIsTrimmed(t *testing.T) { assert.Equal(t, "random@gmail.com", data["user"].(map[string]interface{})["email"]) } + +func TestSignUpAPIWorksWhenInputIsFine(t *testing.T) { + configValue := supertokens.TypeInput{ + Supertokens: &supertokens.ConnectionInfo{ + ConnectionURI: "http://localhost:8080", + }, + AppInfo: supertokens.AppInfo{ + APIDomain: "api.supertokens.io", + AppName: "SuperTokens", + WebsiteDomain: "supertokens.io", + }, + RecipeList: []supertokens.Recipe{ + Init(nil), + session.Init(&sessmodels.TypeInput{ + GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { + return sessmodels.CookieTransferMethod + }, + }), + }, + } + + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + err := supertokens.Init(configValue) + if err != nil { + t.Error(err.Error()) + } + mux := http.NewServeMux() + testServer := httptest.NewServer(supertokens.Middleware(mux)) + defer testServer.Close() + + resp, err := unittesting.SignupRequest("random@gmail.com", "validpass123", testServer.URL) + if err != nil { + t.Error(err.Error()) + } + assert.Equal(t, http.StatusOK, resp.StatusCode) + dataInBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Error(err.Error()) + } + resp.Body.Close() + + var result map[string]interface{} + + err = json.Unmarshal(dataInBytes, &result) + if err != nil { + t.Error(err.Error()) + } + + assert.Equal(t, "OK", result["status"]) + assert.Equal(t, "random@gmail.com", result["user"].(map[string]interface{})["email"]) +} diff --git a/recipe/thirdpartyemailpassword/signupFeature_test.go b/recipe/emailpassword/signinFeature_test.go similarity index 50% rename from recipe/thirdpartyemailpassword/signupFeature_test.go rename to recipe/emailpassword/signinFeature_test.go index be319ea4..cbc5a3cb 100644 --- a/recipe/thirdpartyemailpassword/signupFeature_test.go +++ b/recipe/emailpassword/signinFeature_test.go @@ -13,28 +13,24 @@ * under the License. */ -package thirdpartyemailpassword +package emailpassword import ( - "bytes" "encoding/json" "io" - "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" + "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" "github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" "github.com/supertokens/supertokens-golang/supertokens" "github.com/supertokens/supertokens-golang/test/unittesting" - "gopkg.in/h2non/gock.v1" ) -func TestDisablingDefaultAPIDoesNotWork(t *testing.T) { +func TestAfterDisablingTheDefaultSigninAPIdoesNotWork(t *testing.T) { configValue := supertokens.TypeInput{ Supertokens: &supertokens.ConnectionInfo{ ConnectionURI: "http://localhost:8080", @@ -45,23 +41,10 @@ func TestDisablingDefaultAPIDoesNotWork(t *testing.T) { WebsiteDomain: "supertokens.io", }, RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - { - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "google", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: "test", - ClientSecret: "test-secret", - }, - }, - }, - }, - }, - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - *originalImplementation.ThirdPartySignInUpPOST = nil + Init(&epmodels.TypeInput{ + Override: &epmodels.OverrideStruct{ + APIs: func(originalImplementation epmodels.APIInterface) epmodels.APIInterface { + *originalImplementation.SignInPOST = nil return originalImplementation }, }, @@ -80,29 +63,14 @@ func TestDisablingDefaultAPIDoesNotWork(t *testing.T) { testServer := httptest.NewServer(supertokens.Middleware(mux)) defer testServer.Close() - signinupPostData := map[string]interface{}{ - "thirdPartyId": "google", - "redirectURIInfo": map[string]interface{}{ - "redirectURIOnProviderDashboard": "http://127.0.0.1/callback", - "redirectURIQueryParams": map[string]interface{}{ - "code": "abcdefghj", - }, - }, - } - - postBody, err := json.Marshal(signinupPostData) - if err != nil { - t.Error(err.Error()) - } - - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) + resp, err := unittesting.SignInRequest("random@gmail.com", "validpass123", testServer.URL) if err != nil { t.Error(err.Error()) } assert.Equal(t, http.StatusNotFound, resp.StatusCode) } -func TestThatIfDisableAPIDefaultSignupAPIDoesNotWork(t *testing.T) { +func TestSignInAPIWorksWhenInputIsFine(t *testing.T) { configValue := supertokens.TypeInput{ Supertokens: &supertokens.ConnectionInfo{ ConnectionURI: "http://localhost:8080", @@ -113,14 +81,7 @@ func TestThatIfDisableAPIDefaultSignupAPIDoesNotWork(t *testing.T) { WebsiteDomain: "supertokens.io", }, RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - *originalImplementation.EmailPasswordSignUpPOST = nil - return originalImplementation - }, - }, - }), + Init(nil), session.Init(&sessmodels.TypeInput{ GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { return sessmodels.CookieTransferMethod @@ -128,7 +89,6 @@ func TestThatIfDisableAPIDefaultSignupAPIDoesNotWork(t *testing.T) { }), }, } - BeforeEach() unittesting.StartUpST("localhost", "8080") defer AfterEach() @@ -144,104 +104,43 @@ func TestThatIfDisableAPIDefaultSignupAPIDoesNotWork(t *testing.T) { if err != nil { t.Error(err.Error()) } - assert.Equal(t, http.StatusNotFound, resp.StatusCode) -} - -func TestMinimumConfigForOneProvider(t *testing.T) { - customAntiCsrfVal := "VIA_TOKEN" - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - customProvider2, - }, - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - *originalImplementation.EmailPasswordSignUpPOST = nil - return originalImplementation - }, - }, - }), - session.Init(&sessmodels.TypeInput{ - AntiCsrf: &customAntiCsrfVal, - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - }, - } - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) + assert.Equal(t, http.StatusOK, resp.StatusCode) + dataInBytes, err := io.ReadAll(resp.Body) if err != nil { t.Error(err.Error()) } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() + var result map[string]interface{} + json.Unmarshal(dataInBytes, &result) + resp.Body.Close() - defer gock.OffAll() - gock.New("https://test.com/"). - Post("oauth/token"). - Reply(200). - JSON(map[string]string{}) + assert.Equal(t, "OK", result["status"]) - postData := map[string]interface{}{ - "thirdPartyId": "custom", - "redirectURIInfo": map[string]interface{}{ - "redirectURIOnProviderDashboard": "http://127.0.0.1/callback", - "redirectURIQueryParams": map[string]interface{}{ - "code": "abcdefghj", - }, - }, - } + signupUserInfo := result["user"].(map[string]interface{}) - postBody, err := json.Marshal(postData) + resp1, err := unittesting.SignInRequest("random@gmail.com", "validpass123", testServer.URL) if err != nil { t.Error(err.Error()) } - gock.New(testServer.URL).EnableNetworking().Persist() - gock.New("http://localhost:8080/").EnableNetworking().Persist() - - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) + assert.Equal(t, http.StatusOK, resp1.StatusCode) + dataInBytes1, err := io.ReadAll(resp1.Body) if err != nil { t.Error(err.Error()) } - assert.Equal(t, http.StatusOK, resp.StatusCode) - dataInBytes, err := io.ReadAll(resp.Body) - if err != nil { - t.Error(err.Error()) - } - resp.Body.Close() + var result1 map[string]interface{} + json.Unmarshal(dataInBytes1, &result1) + resp1.Body.Close() - var result map[string]interface{} - - err = json.Unmarshal(dataInBytes, &result) - if err != nil { - t.Error(err.Error()) - } + assert.Equal(t, "OK", result1["status"]) - user := result["user"].(map[string]interface{}) + signInUserInfo := result1["user"].(map[string]interface{}) - assert.Equal(t, "OK", result["status"]) - assert.Equal(t, true, result["createdNewUser"]) - assert.Equal(t, "email@test.com", user["email"]) - assert.Equal(t, "custom", user["thirdParty"].(map[string]interface{})["id"]) - assert.Equal(t, "user", user["thirdParty"].(map[string]interface{})["userId"]) + assert.Equal(t, signInUserInfo["id"], signupUserInfo["id"]) + assert.Equal(t, signInUserInfo["email"], signupUserInfo["email"]) } -func TestSignUpAPIWorksWhenInputIsFine(t *testing.T) { +func TestSigninAPIthrowsAnErrorWhenEmailDoesNotExist(t *testing.T) { configValue := supertokens.TypeInput{ Supertokens: &supertokens.ConnectionInfo{ ConnectionURI: "http://localhost:8080", @@ -260,7 +159,6 @@ func TestSignUpAPIWorksWhenInputIsFine(t *testing.T) { }), }, } - BeforeEach() unittesting.StartUpST("localhost", "8080") defer AfterEach() @@ -276,20 +174,31 @@ func TestSignUpAPIWorksWhenInputIsFine(t *testing.T) { if err != nil { t.Error(err.Error()) } + assert.Equal(t, http.StatusOK, resp.StatusCode) - dataInBytes, err := ioutil.ReadAll(resp.Body) + dataInBytes, err := io.ReadAll(resp.Body) if err != nil { t.Error(err.Error()) } + var result map[string]interface{} + json.Unmarshal(dataInBytes, &result) resp.Body.Close() - var result map[string]interface{} + assert.Equal(t, "OK", result["status"]) - err = json.Unmarshal(dataInBytes, &result) + resp1, err := unittesting.SignInRequest("rand@gmail.com", "validpass123", testServer.URL) if err != nil { t.Error(err.Error()) } - assert.Equal(t, "OK", result["status"]) - assert.Equal(t, "random@gmail.com", result["user"].(map[string]interface{})["email"]) + assert.Equal(t, http.StatusOK, resp1.StatusCode) + dataInBytes1, err := io.ReadAll(resp1.Body) + if err != nil { + t.Error(err.Error()) + } + var result1 map[string]interface{} + json.Unmarshal(dataInBytes1, &result1) + resp1.Body.Close() + + assert.Equal(t, "WRONG_CREDENTIALS_ERROR", result1["status"]) } diff --git a/recipe/thirdpartyemailpassword/signoutFeature_test.go b/recipe/emailpassword/signoutFeature_test.go similarity index 94% rename from recipe/thirdpartyemailpassword/signoutFeature_test.go rename to recipe/emailpassword/signoutFeature_test.go index 288eb7de..85159c4e 100644 --- a/recipe/thirdpartyemailpassword/signoutFeature_test.go +++ b/recipe/emailpassword/signoutFeature_test.go @@ -13,7 +13,7 @@ * under the License. */ -package thirdpartyemailpassword +package emailpassword import ( "bytes" @@ -26,8 +26,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" "github.com/supertokens/supertokens-golang/supertokens" "github.com/supertokens/supertokens-golang/test/unittesting" "gopkg.in/h2non/gock.v1" @@ -45,11 +43,7 @@ func TestDefaultRouteShouldRevokeSession(t *testing.T) { WebsiteDomain: "supertokens.io", }, RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - customProvider2, - }, - }), + Init(nil), session.Init(&sessmodels.TypeInput{ AntiCsrf: &customAntiCsrfVal, GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { diff --git a/recipe/emailpassword/userIdMapping_create_test.go b/recipe/emailpassword/userIdMapping_create_test.go index f98d9461..13c4e5ac 100644 --- a/recipe/emailpassword/userIdMapping_create_test.go +++ b/recipe/emailpassword/userIdMapping_create_test.go @@ -213,3 +213,78 @@ func TestCreateUserIdMappingWithMetadataAndWithAndWithoutForce(t *testing.T) { assert.NotNil(t, createResp.OK) } } + +func TestEPCreateUserIdMappingGetUserById(t *testing.T) { + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + + initForUserIdMappingTest(t) + + querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") + assert.NoError(t, err) + + cdiVersion, err := querier.GetQuerierAPIVersion() + assert.NoError(t, err) + + if unittesting.MaxVersion(cdiVersion, "2.14") == "2.14" { + return + } + + signUpResponse, err := SignUp("public", "test@example.com", "testpass123") + assert.NoError(t, err) + + assert.NotNil(t, signUpResponse.OK) + + externalUserId := "externalId" + externalUserIdInfo := "externalIdInfo" + createResp, err := supertokens.CreateUserIdMapping(signUpResponse.OK.User.ID, externalUserId, &externalUserIdInfo, nil) + assert.NoError(t, err) + assert.NotNil(t, createResp.OK) + + { // Using supertokens ID + userResp, err := GetUserByID(signUpResponse.OK.User.ID) + assert.NoError(t, err) + assert.Equal(t, externalUserId, userResp.ID) + } + + { // Using external ID + userResp, err := GetUserByID(externalUserId) + assert.NoError(t, err) + assert.Equal(t, externalUserId, userResp.ID) + } +} + +func TestEPCreateUserIdMappingGetUserByEmail(t *testing.T) { + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + + initForUserIdMappingTest(t) + + querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") + assert.NoError(t, err) + + cdiVersion, err := querier.GetQuerierAPIVersion() + assert.NoError(t, err) + + if unittesting.MaxVersion(cdiVersion, "2.14") == "2.14" { + return + } + + signUpResponse, err := SignUp("public", "test@example.com", "testpass123") + assert.NoError(t, err) + + assert.NotNil(t, signUpResponse.OK) + + externalUserId := "externalId" + externalUserIdInfo := "externalIdInfo" + createResp, err := supertokens.CreateUserIdMapping(signUpResponse.OK.User.ID, externalUserId, &externalUserIdInfo, nil) + assert.NoError(t, err) + assert.NotNil(t, createResp.OK) + + userResp, err := GetUserByEmail("public", "test@example.com") + assert.NoError(t, err) + assert.NotNil(t, userResp) + assert.Equal(t, externalUserId, userResp.ID) +} diff --git a/recipe/thirdparty/email_test.go b/recipe/thirdparty/email_test.go new file mode 100644 index 00000000..4a895698 --- /dev/null +++ b/recipe/thirdparty/email_test.go @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * You may not use this file except in compliance with the License. You may + * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package thirdparty + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" + "github.com/supertokens/supertokens-golang/recipe/emailpassword" + "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" + "github.com/supertokens/supertokens-golang/recipe/session" + "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" + "github.com/supertokens/supertokens-golang/supertokens" + "github.com/supertokens/supertokens-golang/test/unittesting" +) + +func TestDefaultBackwardCompatibilityPasswordResetForThirdpartyUser(t *testing.T) { + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + + testServer := supertokensInitForTest( + t, + session.Init(&sessmodels.TypeInput{ + GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { + return sessmodels.CookieTransferMethod + }, + }), + Init(nil), + emailpassword.Init(nil), + ) + defer testServer.Close() + + ManuallyCreateOrUpdateUser("public", "custom", "user-id", "test@example.com") + resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) + assert.False(t, emailpassword.PasswordResetEmailSentForTest) + assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) + assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) +} + +func TestCustomOverrideResetPasswordForThirdpartyUser(t *testing.T) { + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + + customCalled := false + email := "" + passwordResetLink := "" + + epConfig := &epmodels.TypeInput{ + EmailDelivery: &emaildelivery.TypeInput{ + Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { + *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { + if input.PasswordReset != nil { + customCalled = true + email = input.PasswordReset.User.Email + passwordResetLink = input.PasswordReset.PasswordResetLink + } + return nil + } + return originalImplementation + }, + }, + } + testServer := supertokensInitForTest( + t, + session.Init(&sessmodels.TypeInput{ + GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { + return sessmodels.CookieTransferMethod + }, + }), + Init(nil), + emailpassword.Init(epConfig), + ) + defer testServer.Close() + + ManuallyCreateOrUpdateUser("public", "custom", "user-id", "test@example.com") + resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) + + // Default handler not called + assert.False(t, emailpassword.PasswordResetEmailSentForTest) + assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) + assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) + + // Custom handler not called + assert.Empty(t, email) + assert.Empty(t, passwordResetLink) + assert.False(t, customCalled) +} + +func TestSMTPOverridePasswordResetForThirdpartyUser(t *testing.T) { + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + + getContentCalled := false + sendRawEmailCalled := false + email := "" + passwordResetLink := "" + + smtpService := emailpassword.MakeSMTPService(emaildelivery.SMTPServiceConfig{ + Settings: emaildelivery.SMTPSettings{ + Host: "", + From: emaildelivery.SMTPFrom{ + Name: "Test User", + Email: "", + }, + Port: 123, + Password: "", + }, + Override: func(originalImplementation emaildelivery.SMTPInterface) emaildelivery.SMTPInterface { + (*originalImplementation.GetContent) = func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { + if input.PasswordReset != nil { + email = input.PasswordReset.User.Email + passwordResetLink = input.PasswordReset.PasswordResetLink + getContentCalled = true + } + return emaildelivery.EmailContent{}, nil + } + + (*originalImplementation.SendRawEmail) = func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { + sendRawEmailCalled = true + return nil + } + + return originalImplementation + }, + }) + epConfig := &epmodels.TypeInput{ + EmailDelivery: &emaildelivery.TypeInput{ + Service: smtpService, + }, + } + testServer := supertokensInitForTest( + t, + session.Init(&sessmodels.TypeInput{ + GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { + return sessmodels.CookieTransferMethod + }, + }), + Init(nil), + emailpassword.Init(epConfig), + ) + defer testServer.Close() + + ManuallyCreateOrUpdateUser("public", "custom", "user-id", "test@example.com") + resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) + assert.NoError(t, err) + assert.Equal(t, http.StatusOK, resp.StatusCode) + + // Default handler not called + assert.False(t, emailpassword.PasswordResetEmailSentForTest) + assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) + assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) + + // Custom handler not called + assert.Empty(t, email) + assert.Empty(t, passwordResetLink) + assert.False(t, getContentCalled) + assert.False(t, sendRawEmailCalled) +} diff --git a/recipe/thirdparty/signinupFeature_test.go b/recipe/thirdparty/signinupFeature_test.go index 589ec9bc..88c99dce 100644 --- a/recipe/thirdparty/signinupFeature_test.go +++ b/recipe/thirdparty/signinupFeature_test.go @@ -969,3 +969,106 @@ func TestGetUserByThirdPartyInfoWhenUserDoesNotExist(t *testing.T) { assert.Equal(t, userInfoAfterSignup.ID, user["id"].(string)) assert.Equal(t, userInfoAfterSignup.Email, user["email"].(string)) } + +func TestHandlePostSignUpInGetsSetCorrectly(t *testing.T) { + userId := "" + loginType := "" + customAntiCsrfVal := "VIA_TOKEN" + configValue := supertokens.TypeInput{ + Supertokens: &supertokens.ConnectionInfo{ + ConnectionURI: "http://localhost:8080", + }, + AppInfo: supertokens.AppInfo{ + APIDomain: "api.supertokens.io", + AppName: "SuperTokens", + WebsiteDomain: "supertokens.io", + }, + RecipeList: []supertokens.Recipe{ + Init(&tpmodels.TypeInput{ + Override: &tpmodels.OverrideStruct{ + APIs: func(originalImplementation tpmodels.APIInterface) tpmodels.APIInterface { + originalSignInUpPost := *originalImplementation.SignInUpPOST + *originalImplementation.SignInUpPOST = func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpmodels.SignInUpPOSTResponse, error) { + resp, err := originalSignInUpPost(provider, input, tenantId, options, userContext) + if err != nil { + t.Error(err.Error()) + } + userId = resp.OK.User.ID + loginType = "thirdparty" + return resp, err + } + return originalImplementation + }, + }, + SignInAndUpFeature: tpmodels.TypeInputSignInAndUp{ + Providers: []tpmodels.ProviderInput{ + customProvider2, + }, + }, + }), + session.Init(&sessmodels.TypeInput{ + AntiCsrf: &customAntiCsrfVal, + GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { + return sessmodels.CookieTransferMethod + }, + }), + }, + } + BeforeEach() + unittesting.StartUpST("localhost", "8080") + defer AfterEach() + err := supertokens.Init(configValue) + if err != nil { + t.Error(err.Error()) + } + mux := http.NewServeMux() + testServer := httptest.NewServer(supertokens.Middleware(mux)) + defer testServer.Close() + + defer gock.OffAll() + gock.New("https://test.com/"). + Post("oauth/token"). + Reply(200). + JSON(map[string]string{"access_token": "abcdefghj", "email": "test@example.com"}) + + postData := map[string]interface{}{ + "thirdPartyId": "custom", + "redirectURIInfo": map[string]interface{}{ + "redirectURIOnProviderDashboard": "http://127.0.0.1/callback", + "redirectURIQueryParams": map[string]interface{}{ + "code": "abcdefghj", + }, + }, + } + + postBody, err := json.Marshal(postData) + if err != nil { + t.Error(err.Error()) + } + + gock.New(testServer.URL).EnableNetworking().Persist() + gock.New("http://localhost:8080/").EnableNetworking().Persist() + + resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) + if err != nil { + t.Error(err.Error()) + } + assert.Equal(t, http.StatusOK, resp.StatusCode) + dataInBytes, err := io.ReadAll(resp.Body) + if err != nil { + t.Error(err.Error()) + } + resp.Body.Close() + + var result map[string]interface{} + + err = json.Unmarshal(dataInBytes, &result) + if err != nil { + t.Error(err.Error()) + } + + user := result["user"].(map[string]interface{}) + + assert.Equal(t, userId, user["id"]) + assert.Equal(t, "thirdparty", loginType) +} diff --git a/recipe/thirdparty/testingUtils.go b/recipe/thirdparty/testingUtils.go index f3bf239d..00cc485d 100644 --- a/recipe/thirdparty/testingUtils.go +++ b/recipe/thirdparty/testingUtils.go @@ -179,7 +179,7 @@ var customProvider2 = tpmodels.ProviderInput{ Override: func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { originalImplementation.GetUserInfo = func(oAuthTokens tpmodels.TypeOAuthTokens, userContext supertokens.UserContext) (tpmodels.TypeUserInfo, error) { return tpmodels.TypeUserInfo{ - ThirdPartyUserId: oAuthTokens["id"].(string), + ThirdPartyUserId: oAuthTokens["access_token"].(string), Email: &tpmodels.EmailStruct{ ID: oAuthTokens["email"].(string), IsVerified: true, diff --git a/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.go b/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.go deleted file mode 100644 index eb8a1531..00000000 --- a/recipe/thirdpartyemailpassword/api/emailPasswordAPIImplementation.go +++ /dev/null @@ -1,103 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package api - -import ( - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func GetEmailPasswordIterfaceImpl(apiImplmentation tpepmodels.APIInterface) epmodels.APIInterface { - - result := epmodels.APIInterface{ - EmailExistsGET: apiImplmentation.EmailPasswordEmailExistsGET, - GeneratePasswordResetTokenPOST: apiImplmentation.GeneratePasswordResetTokenPOST, - PasswordResetPOST: apiImplmentation.PasswordResetPOST, - SignInPOST: nil, - SignUpPOST: nil, - } - - if apiImplmentation.EmailPasswordSignInPOST != nil && (*apiImplmentation.EmailPasswordSignInPOST) != nil { - signInPOST := func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.SignInPOSTResponse, error) { - result, err := (*apiImplmentation.EmailPasswordSignInPOST)(formFields, tenantId, options, userContext) - if err != nil { - return epmodels.SignInPOSTResponse{}, err - } - if result.OK != nil { - return epmodels.SignInPOSTResponse{ - OK: &struct { - User epmodels.User - Session sessmodels.SessionContainer - }{ - - User: epmodels.User{ - ID: result.OK.User.ID, - Email: result.OK.User.Email, - TimeJoined: result.OK.User.TimeJoined, - }, - Session: result.OK.Session, - }, - }, nil - } else if result.WrongCredentialsError != nil { - return epmodels.SignInPOSTResponse{ - WrongCredentialsError: &struct{}{}, - }, nil - } else { - return epmodels.SignInPOSTResponse{ - GeneralError: result.GeneralError, - }, nil - } - } - result.SignInPOST = &signInPOST - } - - if apiImplmentation.EmailPasswordSignUpPOST != nil && (*apiImplmentation.EmailPasswordSignUpPOST) != nil { - signUpPOST := func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.SignUpPOSTResponse, error) { - result, err := (*apiImplmentation.EmailPasswordSignUpPOST)(formFields, tenantId, options, userContext) - if err != nil { - return epmodels.SignUpPOSTResponse{}, err - } - if result.OK != nil { - return epmodels.SignUpPOSTResponse{ - OK: &struct { - User epmodels.User - Session sessmodels.SessionContainer - }{ - User: epmodels.User{ - ID: result.OK.User.ID, - Email: result.OK.User.Email, - TimeJoined: result.OK.User.TimeJoined, - }, - Session: result.OK.Session, - }, - }, nil - } else if result.EmailAlreadyExistsError != nil { - return epmodels.SignUpPOSTResponse{ - EmailAlreadyExistsError: &struct{}{}, - }, nil - } else { - return epmodels.SignUpPOSTResponse{ - GeneralError: result.GeneralError, - }, nil - } - } - result.SignUpPOST = &signUpPOST - } - - return result -} diff --git a/recipe/thirdpartyemailpassword/api/implementation.go b/recipe/thirdpartyemailpassword/api/implementation.go deleted file mode 100644 index b1b24bb2..00000000 --- a/recipe/thirdpartyemailpassword/api/implementation.go +++ /dev/null @@ -1,185 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package api - -import ( - epapi "github.com/supertokens/supertokens-golang/recipe/emailpassword/api" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - tpapi "github.com/supertokens/supertokens-golang/recipe/thirdparty/api" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func MakeAPIImplementation() tpepmodels.APIInterface { - emailPasswordImplementation := epapi.MakeAPIImplementation() - thirdPartyImplementation := tpapi.MakeAPIImplementation() - - ogEmailExistsGET := *emailPasswordImplementation.EmailExistsGET - emailExistsGET := func(email string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.EmailExistsGETResponse, error) { - return ogEmailExistsGET(email, tenantId, options, userContext) - - } - - ogGeneratePasswordResetTokenPOST := *emailPasswordImplementation.GeneratePasswordResetTokenPOST - generatePasswordResetTokenPOST := func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.GeneratePasswordResetTokenPOSTResponse, error) { - return ogGeneratePasswordResetTokenPOST(formFields, tenantId, options, userContext) - } - - ogPasswordResetPOST := *emailPasswordImplementation.PasswordResetPOST - passwordResetPOST := func(formFields []epmodels.TypeFormField, token string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.ResetPasswordPOSTResponse, error) { - return ogPasswordResetPOST(formFields, token, tenantId, options, userContext) - } - - ogSignInPOST := *emailPasswordImplementation.SignInPOST - emailPasswordSignInPOST := func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.SignInPOSTResponse, error) { - response, err := ogSignInPOST(formFields, tenantId, options, userContext) - if err != nil { - return tpepmodels.SignInPOSTResponse{}, err - } - if response.OK != nil { - return tpepmodels.SignInPOSTResponse{ - OK: &struct { - User tpepmodels.User - Session sessmodels.SessionContainer - }{ - User: tpepmodels.User{ - ID: response.OK.User.ID, - Email: response.OK.User.Email, - TimeJoined: response.OK.User.TimeJoined, - ThirdParty: nil, - }, - Session: response.OK.Session, - }, - }, nil - } else if response.WrongCredentialsError != nil { - return tpepmodels.SignInPOSTResponse{ - WrongCredentialsError: &struct{}{}, - }, nil - } else { - return tpepmodels.SignInPOSTResponse{ - GeneralError: response.GeneralError, - }, nil - } - } - - ogSignUpPOST := *emailPasswordImplementation.SignUpPOST - emailPasswordSignUpPOST := func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.SignUpPOSTResponse, error) { - response, err := ogSignUpPOST(formFields, tenantId, options, userContext) - if err != nil { - return tpepmodels.SignUpPOSTResponse{}, err - } - if response.OK != nil { - return tpepmodels.SignUpPOSTResponse{ - OK: &struct { - User tpepmodels.User - Session sessmodels.SessionContainer - }{ - User: tpepmodels.User{ - ID: response.OK.User.ID, - Email: response.OK.User.Email, - TimeJoined: response.OK.User.TimeJoined, - ThirdParty: nil, - }, - Session: response.OK.Session, - }, - }, nil - } else if response.EmailAlreadyExistsError != nil { - return tpepmodels.SignUpPOSTResponse{ - EmailAlreadyExistsError: &struct{}{}, - }, nil - } else { - return tpepmodels.SignUpPOSTResponse{ - GeneralError: response.GeneralError, - }, nil - } - } - - ogSignInUpPOST := *thirdPartyImplementation.SignInUpPOST - thirdPartySignInUpPOST := func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.ThirdPartySignInUpPOSTResponse, error) { - response, err := ogSignInUpPOST(provider, input, tenantId, options, userContext) - if err != nil { - return tpepmodels.ThirdPartySignInUpPOSTResponse{}, err - } - if response.GeneralError != nil { - return tpepmodels.ThirdPartySignInUpPOSTResponse{ - GeneralError: response.GeneralError, - }, nil - } else if response.NoEmailGivenByProviderError != nil { - return tpepmodels.ThirdPartySignInUpPOSTResponse{ - NoEmailGivenByProviderError: &struct{}{}, - }, nil - } else { - return tpepmodels.ThirdPartySignInUpPOSTResponse{ - OK: &struct { - CreatedNewUser bool - User tpepmodels.User - Session *sessmodels.TypeSessionContainer - OAuthTokens map[string]interface{} - RawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider - }{ - CreatedNewUser: response.OK.CreatedNewUser, - User: tpepmodels.User{ - ID: response.OK.User.ID, - TimeJoined: response.OK.User.TimeJoined, - Email: response.OK.User.Email, - ThirdParty: &response.OK.User.ThirdParty, - }, - Session: response.OK.Session, - OAuthTokens: response.OK.OAuthTokens, - RawUserInfoFromProvider: response.OK.RawUserInfoFromProvider, - }, - }, nil - } - } - - ogAuthorisationUrlGET := *thirdPartyImplementation.AuthorisationUrlGET - authorisationUrlGET := func(provider *tpmodels.TypeProvider, redirectURIOnProviderDashboard string, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpmodels.AuthorisationUrlGETResponse, error) { - return ogAuthorisationUrlGET(provider, redirectURIOnProviderDashboard, tenantId, options, userContext) - } - - ogAppleRedirectHandlerPOST := *thirdPartyImplementation.AppleRedirectHandlerPOST - appleRedirectHandlerPOST := func(formPostInfoFromProvider map[string]interface{}, options tpmodels.APIOptions, userContext supertokens.UserContext) error { - return ogAppleRedirectHandlerPOST(formPostInfoFromProvider, options, userContext) - } - - result := tpepmodels.APIInterface{ - AuthorisationUrlGET: &authorisationUrlGET, - ThirdPartySignInUpPOST: &thirdPartySignInUpPOST, - AppleRedirectHandlerPOST: &appleRedirectHandlerPOST, - - EmailPasswordEmailExistsGET: &emailExistsGET, - GeneratePasswordResetTokenPOST: &generatePasswordResetTokenPOST, - PasswordResetPOST: &passwordResetPOST, - EmailPasswordSignInPOST: &emailPasswordSignInPOST, - EmailPasswordSignUpPOST: &emailPasswordSignUpPOST, - } - - modifiedEP := GetEmailPasswordIterfaceImpl(result) - (*emailPasswordImplementation.EmailExistsGET) = *modifiedEP.EmailExistsGET - (*emailPasswordImplementation.GeneratePasswordResetTokenPOST) = *modifiedEP.GeneratePasswordResetTokenPOST - (*emailPasswordImplementation.PasswordResetPOST) = *modifiedEP.PasswordResetPOST - (*emailPasswordImplementation.SignInPOST) = *modifiedEP.SignInPOST - (*emailPasswordImplementation.SignUpPOST) = *modifiedEP.SignUpPOST - - modifiedTP := GetThirdPartyIterfaceImpl(result) - (*thirdPartyImplementation.AuthorisationUrlGET) = *modifiedTP.AuthorisationUrlGET - (*thirdPartyImplementation.SignInUpPOST) = *modifiedTP.SignInUpPOST - (*thirdPartyImplementation.AppleRedirectHandlerPOST) = *modifiedTP.AppleRedirectHandlerPOST - - return result -} diff --git a/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.go b/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.go deleted file mode 100644 index a3dbdc5b..00000000 --- a/recipe/thirdpartyemailpassword/api/thirdPartyAPIImplementation.go +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package api - -import ( - "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func GetThirdPartyIterfaceImpl(apiImplmentation tpepmodels.APIInterface) tpmodels.APIInterface { - if apiImplmentation.ThirdPartySignInUpPOST == nil || (*apiImplmentation.ThirdPartySignInUpPOST) == nil { - return tpmodels.APIInterface{ - AuthorisationUrlGET: apiImplmentation.AuthorisationUrlGET, - AppleRedirectHandlerPOST: apiImplmentation.AppleRedirectHandlerPOST, - SignInUpPOST: nil, - } - } - - signInUpPOST := func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpmodels.SignInUpPOSTResponse, error) { - result, err := (*apiImplmentation.ThirdPartySignInUpPOST)(provider, input, tenantId, options, userContext) - if err != nil { - return tpmodels.SignInUpPOSTResponse{}, err - } - - if result.OK != nil { - return tpmodels.SignInUpPOSTResponse{ - OK: &struct { - CreatedNewUser bool - User tpmodels.User - Session *sessmodels.TypeSessionContainer - OAuthTokens map[string]interface{} - RawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider - }{ - CreatedNewUser: result.OK.CreatedNewUser, - User: tpmodels.User{ - ID: result.OK.User.ID, - Email: result.OK.User.Email, - TenantIds: result.OK.User.TenantIds, - TimeJoined: result.OK.User.TimeJoined, - ThirdParty: *result.OK.User.ThirdParty, - }, - Session: result.OK.Session, - OAuthTokens: result.OK.OAuthTokens, - RawUserInfoFromProvider: result.OK.RawUserInfoFromProvider, - }, - }, nil - } else if result.NoEmailGivenByProviderError != nil { - return tpmodels.SignInUpPOSTResponse{ - NoEmailGivenByProviderError: &struct{}{}, - }, nil - } else { - return tpmodels.SignInUpPOSTResponse{ - GeneralError: result.GeneralError, - }, nil - } - } - - return tpmodels.APIInterface{ - AuthorisationUrlGET: apiImplmentation.AuthorisationUrlGET, - AppleRedirectHandlerPOST: apiImplmentation.AppleRedirectHandlerPOST, - SignInUpPOST: &signInUpPOST, - } -} diff --git a/recipe/thirdpartyemailpassword/emaildelivery/backwardCompatibilityService/main.go b/recipe/thirdpartyemailpassword/emaildelivery/backwardCompatibilityService/main.go deleted file mode 100644 index 4d79995a..00000000 --- a/recipe/thirdpartyemailpassword/emaildelivery/backwardCompatibilityService/main.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package backwardCompatibilityService - -import ( - "errors" - - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - emailPasswordBackwardsCompatibilityService "github.com/supertokens/supertokens-golang/recipe/emailpassword/emaildelivery/backwardCompatibilityService" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func MakeBackwardCompatibilityService(recipeInterfaceImpl tpepmodels.RecipeInterface, emailPasswordRecipeInterfaceImpl epmodels.RecipeInterface, appInfo supertokens.NormalisedAppinfo, sendResetPasswordEmail func(user epmodels.User, passwordResetURLWithToken string, userContext supertokens.UserContext)) emaildelivery.EmailDeliveryInterface { - // We are using evmodels.User as opposed to tpmodels.User because TypeInput of thirdparty accepts evmodels.TypeInput for EmailVerificationFeature - // Similarly with epmodels.User as well - emailPasswordService := emailPasswordBackwardsCompatibilityService.MakeBackwardCompatibilityService(emailPasswordRecipeInterfaceImpl, appInfo, sendResetPasswordEmail) - - sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.PasswordReset != nil { - return (*emailPasswordService.SendEmail)(input, userContext) - - } else { - return errors.New("should never come here") - } - } - - return emaildelivery.EmailDeliveryInterface{ - SendEmail: &sendEmail, - } -} diff --git a/recipe/thirdpartyemailpassword/emaildelivery/smtpService/main.go b/recipe/thirdpartyemailpassword/emaildelivery/smtpService/main.go deleted file mode 100644 index d852f922..00000000 --- a/recipe/thirdpartyemailpassword/emaildelivery/smtpService/main.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package smtpService - -import ( - "errors" - - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - epsmtpService "github.com/supertokens/supertokens-golang/recipe/emailpassword/emaildelivery/smtpService" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func MakeSMTPService(config emaildelivery.SMTPServiceConfig) *emaildelivery.EmailDeliveryInterface { - emailPasswordServiceImpl := epsmtpService.MakeSMTPService(config) - - sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.PasswordReset != nil { - return (*emailPasswordServiceImpl.SendEmail)(input, userContext) - - } else { - return errors.New("should never come here") - } - } - - return &emaildelivery.EmailDeliveryInterface{ - SendEmail: &sendEmail, - } -} diff --git a/recipe/thirdpartyemailpassword/main.go b/recipe/thirdpartyemailpassword/main.go deleted file mode 100644 index c297bf89..00000000 --- a/recipe/thirdpartyemailpassword/main.go +++ /dev/null @@ -1,240 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package thirdpartyemailpassword - -import ( - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/api" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/emaildelivery/smtpService" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func Init(config *tpepmodels.TypeInput) supertokens.Recipe { - return recipeInit(config) -} - -func ThirdPartyManuallyCreateOrUpdateUser(tenantId string, thirdPartyID string, thirdPartyUserID string, email string, userContext ...supertokens.UserContext) (tpepmodels.ManuallyCreateOrUpdateUserResponse, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return tpepmodels.ManuallyCreateOrUpdateUserResponse{}, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.ThirdPartyManuallyCreateOrUpdateUser)(thirdPartyID, thirdPartyUserID, email, tenantId, userContext[0]) -} - -func ThirdPartyGetProvider(tenantId string, thirdPartyID string, clientType *string, userContext ...supertokens.UserContext) (*tpmodels.TypeProvider, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return nil, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.ThirdPartyGetProvider)(thirdPartyID, clientType, tenantId, userContext[0]) -} - -func GetUserByThirdPartyInfo(tenantId string, thirdPartyID string, thirdPartyUserID string, userContext ...supertokens.UserContext) (*tpepmodels.User, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return nil, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.GetUserByThirdPartyInfo)(thirdPartyID, thirdPartyUserID, tenantId, userContext[0]) -} - -func EmailPasswordSignUp(tenantId string, email, password string, userContext ...supertokens.UserContext) (tpepmodels.SignUpResponse, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return tpepmodels.SignUpResponse{}, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.EmailPasswordSignUp)(email, password, tenantId, userContext[0]) -} - -func EmailPasswordSignIn(tenantId string, email, password string, userContext ...supertokens.UserContext) (tpepmodels.SignInResponse, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return tpepmodels.SignInResponse{}, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.EmailPasswordSignIn)(email, password, tenantId, userContext[0]) -} - -func GetUserById(userID string, userContext ...supertokens.UserContext) (*tpepmodels.User, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return nil, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.GetUserByID)(userID, userContext[0]) -} - -func GetUsersByEmail(tenantId string, email string, userContext ...supertokens.UserContext) ([]tpepmodels.User, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return nil, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.GetUsersByEmail)(email, tenantId, userContext[0]) -} - -func CreateResetPasswordToken(tenantId string, userID string, userContext ...supertokens.UserContext) (epmodels.CreateResetPasswordTokenResponse, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return epmodels.CreateResetPasswordTokenResponse{}, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.CreateResetPasswordToken)(userID, tenantId, userContext[0]) -} - -func ResetPasswordUsingToken(tenantId string, token, newPassword string, userContext ...supertokens.UserContext) (epmodels.ResetPasswordUsingTokenResponse, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return epmodels.ResetPasswordUsingTokenResponse{}, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.RecipeImpl.ResetPasswordUsingToken)(token, newPassword, tenantId, userContext[0]) -} - -func UpdateEmailOrPassword(userId string, email *string, password *string, applyPasswordPolicy *bool, tenantIdForPasswordPolicy *string, userContext ...supertokens.UserContext) (epmodels.UpdateEmailOrPasswordResponse, error) { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return epmodels.UpdateEmailOrPasswordResponse{}, err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - if tenantIdForPasswordPolicy == nil { - tenantId := supertokens.DefaultTenantId - tenantIdForPasswordPolicy = &tenantId - } - return (*instance.RecipeImpl.UpdateEmailOrPassword)(userId, email, password, applyPasswordPolicy, *tenantIdForPasswordPolicy, userContext[0]) -} - -func SendEmail(input emaildelivery.EmailType, userContext ...supertokens.UserContext) error { - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return err - } - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - return (*instance.EmailDelivery.IngredientInterfaceImpl.SendEmail)(input, userContext[0]) -} - -func CreateResetPasswordLink(tenantId string, userID string, userContext ...supertokens.UserContext) (epmodels.CreateResetPasswordLinkResponse, error) { - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - tokenResponse, err := CreateResetPasswordToken(tenantId, userID, userContext...) - if err != nil { - return epmodels.CreateResetPasswordLinkResponse{}, err - } - if tokenResponse.UnknownUserIdError != nil { - return epmodels.CreateResetPasswordLinkResponse{ - UnknownUserIdError: &struct{}{}, - }, nil - } - - instance, err := GetRecipeInstanceOrThrowError() - if err != nil { - return epmodels.CreateResetPasswordLinkResponse{}, err - } - - link, err := api.GetPasswordResetLink( - instance.RecipeModule.GetAppInfo(), - instance.RecipeModule.GetRecipeID(), - tokenResponse.OK.Token, - tenantId, - supertokens.GetRequestFromUserContext(userContext[0]), - userContext[0], - ) - - if err != nil { - return epmodels.CreateResetPasswordLinkResponse{}, err - } - - return epmodels.CreateResetPasswordLinkResponse{ - OK: &struct{ Link string }{ - Link: link, - }, - }, nil -} - -func SendResetPasswordEmail(tenantId string, userID string, userContext ...supertokens.UserContext) (epmodels.SendResetPasswordEmailResponse, error) { - if len(userContext) == 0 { - userContext = append(userContext, &map[string]interface{}{}) - } - linkResponse, err := CreateResetPasswordLink(tenantId, userID, userContext...) - if err != nil { - return epmodels.SendResetPasswordEmailResponse{}, err - } - if linkResponse.UnknownUserIdError != nil { - return epmodels.SendResetPasswordEmailResponse{ - UnknownUserIdError: &struct{}{}, - }, nil - } - - userInfo, err := GetUserById(userID, userContext...) - if err != nil { - return epmodels.SendResetPasswordEmailResponse{}, err - } - if userInfo == nil { - return epmodels.SendResetPasswordEmailResponse{ - UnknownUserIdError: &struct{}{}, - }, nil - } - err = SendEmail(emaildelivery.EmailType{ - PasswordReset: &emaildelivery.PasswordResetType{ - User: emaildelivery.User{ - ID: userInfo.ID, - Email: userInfo.Email, - }, - PasswordResetLink: linkResponse.OK.Link, - TenantId: tenantId, - }, - }, userContext...) - if err != nil { - return epmodels.SendResetPasswordEmailResponse{}, err - } - - return epmodels.SendResetPasswordEmailResponse{ - OK: &struct{}{}, - }, nil -} - -func MakeSMTPService(config emaildelivery.SMTPServiceConfig) *emaildelivery.EmailDeliveryInterface { - return smtpService.MakeSMTPService(config) -} diff --git a/recipe/thirdpartyemailpassword/recipe.go b/recipe/thirdpartyemailpassword/recipe.go deleted file mode 100644 index 382f385b..00000000 --- a/recipe/thirdpartyemailpassword/recipe.go +++ /dev/null @@ -1,220 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package thirdpartyemailpassword - -import ( - "errors" - "net/http" - - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - "github.com/supertokens/supertokens-golang/recipe/emailpassword" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/emailverification" - "github.com/supertokens/supertokens-golang/recipe/thirdparty" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/api" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/recipeimplementation" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -const RECIPE_ID = "thirdpartyemailpassword" - -type Recipe struct { - RecipeModule supertokens.RecipeModule - Config tpepmodels.TypeNormalisedInput - emailPasswordRecipe *emailpassword.Recipe - thirdPartyRecipe *thirdparty.Recipe - RecipeImpl tpepmodels.RecipeInterface - APIImpl tpepmodels.APIInterface - EmailDelivery emaildelivery.Ingredient - GetEmailPasswordRecipe func() *emailpassword.Recipe -} - -var singletonInstance *Recipe - -func MakeRecipe(recipeId string, appInfo supertokens.NormalisedAppinfo, config *tpepmodels.TypeInput, emailVerificationInstance *emailverification.Recipe, thirdPartyInstance *thirdparty.Recipe, emailPasswordInstance *emailpassword.Recipe, emailDeliveryIngredient *emaildelivery.Ingredient, onSuperTokensAPIError func(err error, req *http.Request, res http.ResponseWriter)) (Recipe, error) { - r := &Recipe{} - r.RecipeModule = supertokens.MakeRecipeModule(recipeId, appInfo, r.handleAPIRequest, r.getAllCORSHeaders, r.getAPIsHandled, nil, r.handleError, onSuperTokensAPIError) - - verifiedConfig, err := validateAndNormaliseUserInput(r, appInfo, config) - if err != nil { - return Recipe{}, err - } - r.Config = verifiedConfig - { - emailpasswordquerierInstance, err := supertokens.GetNewQuerierInstanceOrThrowError(emailpassword.RECIPE_ID) - if err != nil { - return Recipe{}, err - } - thirdpartyquerierInstance, err := supertokens.GetNewQuerierInstanceOrThrowError(thirdparty.RECIPE_ID) - if err != nil { - return Recipe{}, err - } - var getEmailPasswordConfig = func() epmodels.TypeNormalisedInput { - return r.emailPasswordRecipe.Config - } - r.RecipeImpl = verifiedConfig.Override.Functions(recipeimplementation.MakeRecipeImplementation(*emailpasswordquerierInstance, thirdpartyquerierInstance, getEmailPasswordConfig, verifiedConfig.Providers)) - } - r.APIImpl = verifiedConfig.Override.APIs(api.MakeAPIImplementation()) - - var emailPasswordRecipe emailpassword.Recipe - emailPasswordRecipeImpl := recipeimplementation.MakeEmailPasswordRecipeImplementation(r.RecipeImpl) - if emailDeliveryIngredient != nil { - r.EmailDelivery = *emailDeliveryIngredient - } else { - r.EmailDelivery = emaildelivery.MakeIngredient(verifiedConfig.GetEmailDeliveryConfig(r.RecipeImpl, emailPasswordRecipeImpl)) - } - - if emailPasswordInstance == nil { - emailPasswordConfig := &epmodels.TypeInput{ - SignUpFeature: verifiedConfig.SignUpFeature, - Override: &epmodels.OverrideStruct{ - Functions: func(_ epmodels.RecipeInterface) epmodels.RecipeInterface { - return emailPasswordRecipeImpl - }, - APIs: func(_ epmodels.APIInterface) epmodels.APIInterface { - return api.GetEmailPasswordIterfaceImpl(r.APIImpl) - }, - }, - } - emailPasswordRecipe, err = emailpassword.MakeRecipe(recipeId, appInfo, emailPasswordConfig, &r.EmailDelivery, onSuperTokensAPIError) - if err != nil { - return Recipe{}, err - } - r.emailPasswordRecipe = &emailPasswordRecipe - } else { - r.emailPasswordRecipe = emailPasswordInstance - } - - if thirdPartyInstance == nil { - thirdPartyConfig := &tpmodels.TypeInput{ - SignInAndUpFeature: tpmodels.TypeInputSignInAndUp{ - Providers: verifiedConfig.Providers, - }, - Override: &tpmodels.OverrideStruct{ - Functions: func(_ tpmodels.RecipeInterface) tpmodels.RecipeInterface { - return recipeimplementation.MakeThirdPartyRecipeImplementation(r.RecipeImpl) - }, - APIs: func(_ tpmodels.APIInterface) tpmodels.APIInterface { - return api.GetThirdPartyIterfaceImpl(r.APIImpl) - }, - }, - } - thirdPartyRecipeinstance, err := thirdparty.MakeRecipe(recipeId, appInfo, thirdPartyConfig, &r.EmailDelivery, onSuperTokensAPIError) - if err != nil { - return Recipe{}, err - } - r.thirdPartyRecipe = &thirdPartyRecipeinstance - } else { - r.thirdPartyRecipe = thirdPartyInstance - } - - r.GetEmailPasswordRecipe = func() *emailpassword.Recipe { - return r.emailPasswordRecipe - } - - return *r, nil -} - -func recipeInit(config *tpepmodels.TypeInput) supertokens.Recipe { - return func(appInfo supertokens.NormalisedAppinfo, onSuperTokensAPIError func(err error, req *http.Request, res http.ResponseWriter)) (*supertokens.RecipeModule, error) { - if singletonInstance == nil { - recipe, err := MakeRecipe(RECIPE_ID, appInfo, config, nil, nil, nil, nil, onSuperTokensAPIError) - if err != nil { - return nil, err - } - singletonInstance = &recipe - return &singletonInstance.RecipeModule, nil - } - return nil, errors.New("ThirdPartyEmailPassword recipe has already been initialised. Please check your code for bugs.") - } -} - -func GetRecipeInstanceOrThrowError() (*Recipe, error) { - if singletonInstance != nil { - return singletonInstance, nil - } - return nil, errors.New("Initialisation not done. Did you forget to call the init function?") -} - -func GetRecipeInstance() *Recipe { - return singletonInstance -} - -// implement RecipeModule - -func (r *Recipe) getAPIsHandled() ([]supertokens.APIHandled, error) { - emailpasswordAPIhandled, err := r.emailPasswordRecipe.RecipeModule.GetAPIsHandled() - if err != nil { - return nil, err - } - apisHandled := append(emailpasswordAPIhandled) - if r.thirdPartyRecipe != nil { - thirdpartyAPIhandled, err := r.thirdPartyRecipe.RecipeModule.GetAPIsHandled() - if err != nil { - return nil, err - } - apisHandled = append(apisHandled, thirdpartyAPIhandled...) - } - return apisHandled, nil -} - -func (r *Recipe) handleAPIRequest(id string, tenantId string, req *http.Request, res http.ResponseWriter, theirHandler http.HandlerFunc, path supertokens.NormalisedURLPath, method string, userContext supertokens.UserContext) error { - ok, _, err := r.emailPasswordRecipe.RecipeModule.ReturnAPIIdIfCanHandleRequest(path, method, userContext) - if err != nil { - return err - } - if ok != nil { - return r.emailPasswordRecipe.RecipeModule.HandleAPIRequest(id, tenantId, req, res, theirHandler, path, method, userContext) - } - if r.thirdPartyRecipe != nil { - ok, _, err := r.thirdPartyRecipe.RecipeModule.ReturnAPIIdIfCanHandleRequest(path, method, userContext) - if err != nil { - return err - } - if ok != nil { - return r.thirdPartyRecipe.RecipeModule.HandleAPIRequest(id, tenantId, req, res, theirHandler, path, method, userContext) - } - } - return errors.New("should not come here") -} - -func (r *Recipe) getAllCORSHeaders() []string { - corsHeaders := r.emailPasswordRecipe.RecipeModule.GetAllCORSHeaders() - if r.thirdPartyRecipe != nil { - corsHeaders = append(corsHeaders, r.thirdPartyRecipe.RecipeModule.GetAllCORSHeaders()...) - } - return corsHeaders -} - -func (r *Recipe) handleError(err error, req *http.Request, res http.ResponseWriter, userContext supertokens.UserContext) (bool, error) { - handleError, err := r.emailPasswordRecipe.RecipeModule.HandleError(err, req, res, userContext) - if err != nil || handleError { - return handleError, err - } - if r.thirdPartyRecipe != nil { - handleError, err = r.thirdPartyRecipe.RecipeModule.HandleError(err, req, res, userContext) - if err != nil || handleError { - return handleError, err - } - } - return false, nil -} - -func ResetForTest() { - singletonInstance = nil -} diff --git a/recipe/thirdpartyemailpassword/recipeimplementation/emailPasswordRecipeImplementation.go b/recipe/thirdpartyemailpassword/recipeimplementation/emailPasswordRecipeImplementation.go deleted file mode 100644 index 86919fd1..00000000 --- a/recipe/thirdpartyemailpassword/recipeimplementation/emailPasswordRecipeImplementation.go +++ /dev/null @@ -1,122 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package recipeimplementation - -import ( - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func MakeEmailPasswordRecipeImplementation(recipeImplementation tpepmodels.RecipeInterface) epmodels.RecipeInterface { - - signUp := func(email, password string, tenantId string, userContext supertokens.UserContext) (epmodels.SignUpResponse, error) { - response, err := (*recipeImplementation.EmailPasswordSignUp)(email, password, tenantId, userContext) - if err != nil { - return epmodels.SignUpResponse{}, err - } - if response.EmailAlreadyExistsError != nil { - return epmodels.SignUpResponse{ - EmailAlreadyExistsError: &struct{}{}, - }, nil - } - return epmodels.SignUpResponse{ - OK: &struct{ User epmodels.User }{ - User: epmodels.User{ - ID: response.OK.User.ID, - Email: response.OK.User.Email, - TimeJoined: response.OK.User.TimeJoined, - }, - }, - }, nil - } - - signIn := func(email, password string, tenantId string, userContext supertokens.UserContext) (epmodels.SignInResponse, error) { - response, err := (*recipeImplementation.EmailPasswordSignIn)(email, password, tenantId, userContext) - if err != nil { - return epmodels.SignInResponse{}, err - } - if response.WrongCredentialsError != nil { - return epmodels.SignInResponse{ - WrongCredentialsError: &struct{}{}, - }, nil - } - return epmodels.SignInResponse{ - OK: &struct{ User epmodels.User }{ - User: epmodels.User{ - ID: response.OK.User.ID, - Email: response.OK.User.Email, - TimeJoined: response.OK.User.TimeJoined, - }, - }, - }, nil - } - - getUserByID := func(userId string, userContext supertokens.UserContext) (*epmodels.User, error) { - user, err := (*recipeImplementation.GetUserByID)(userId, userContext) - if err != nil { - return nil, err - } - if user == nil || user.ThirdParty != nil { - return nil, nil - } - return &epmodels.User{ - ID: user.ID, - Email: user.Email, - TimeJoined: user.TimeJoined, - }, nil - } - - getUserByEmail := func(email string, tenantId string, userContext supertokens.UserContext) (*epmodels.User, error) { - users, err := (*recipeImplementation.GetUsersByEmail)(email, tenantId, userContext) - if err != nil { - return nil, err - } - - for _, user := range users { - if user.ThirdParty == nil { - return &epmodels.User{ - ID: user.ID, - Email: user.Email, - TimeJoined: user.TimeJoined, - }, nil - } - } - return nil, nil - } - - createResetPasswordToken := func(userID string, tenantId string, userContext supertokens.UserContext) (epmodels.CreateResetPasswordTokenResponse, error) { - return (*recipeImplementation.CreateResetPasswordToken)(userID, tenantId, userContext) - } - - resetPasswordUsingToken := func(token, newPassword string, tenantId string, userContext supertokens.UserContext) (epmodels.ResetPasswordUsingTokenResponse, error) { - return (*recipeImplementation.ResetPasswordUsingToken)(token, newPassword, tenantId, userContext) - } - - updateEmailOrPassword := func(userId string, email, password *string, applyPasswordPolicy *bool, tenantIdForPasswordPolicy string, userContext supertokens.UserContext) (epmodels.UpdateEmailOrPasswordResponse, error) { - return (*recipeImplementation.UpdateEmailOrPassword)(userId, email, password, applyPasswordPolicy, tenantIdForPasswordPolicy, userContext) - } - - return epmodels.RecipeInterface{ - SignUp: &signUp, - SignIn: &signIn, - GetUserByID: &getUserByID, - GetUserByEmail: &getUserByEmail, - CreateResetPasswordToken: &createResetPasswordToken, - ResetPasswordUsingToken: &resetPasswordUsingToken, - UpdateEmailOrPassword: &updateEmailOrPassword, - } -} diff --git a/recipe/thirdpartyemailpassword/recipeimplementation/main.go b/recipe/thirdpartyemailpassword/recipeimplementation/main.go deleted file mode 100644 index f5a2a3d7..00000000 --- a/recipe/thirdpartyemailpassword/recipeimplementation/main.go +++ /dev/null @@ -1,328 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package recipeimplementation - -import ( - "errors" - - "github.com/supertokens/supertokens-golang/recipe/emailpassword" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func MakeRecipeImplementation(emailPasswordQuerier supertokens.Querier, thirdPartyQuerier *supertokens.Querier, getEmailPasswordConfig func() epmodels.TypeNormalisedInput, providers []tpmodels.ProviderInput) tpepmodels.RecipeInterface { - result := tpepmodels.RecipeInterface{} - emailPasswordImplementation := emailpassword.MakeRecipeImplementation(emailPasswordQuerier, getEmailPasswordConfig) - var thirdPartyImplementation *tpmodels.RecipeInterface - if thirdPartyQuerier != nil { - thirdPartyImplementationTemp := thirdparty.MakeRecipeImplementation(*thirdPartyQuerier, providers) - thirdPartyImplementation = &thirdPartyImplementationTemp - } - - ogSignUp := *emailPasswordImplementation.SignUp - signUp := func(email, password string, tenantId string, userContext supertokens.UserContext) (tpepmodels.SignUpResponse, error) { - response, err := ogSignUp(email, password, tenantId, userContext) - if err != nil { - return tpepmodels.SignUpResponse{}, err - } - if response.EmailAlreadyExistsError != nil { - return tpepmodels.SignUpResponse{ - EmailAlreadyExistsError: &struct{}{}, - }, nil - } - return tpepmodels.SignUpResponse{ - OK: &struct { - User tpepmodels.User - }{ - User: tpepmodels.User{ - ID: response.OK.User.ID, - Email: response.OK.User.Email, - TimeJoined: response.OK.User.TimeJoined, - ThirdParty: nil, - }, - }, - }, nil - } - - ogSignIn := *emailPasswordImplementation.SignIn - signIn := func(email, password string, tenantId string, userContext supertokens.UserContext) (tpepmodels.SignInResponse, error) { - response, err := ogSignIn(email, password, tenantId, userContext) - if err != nil { - return tpepmodels.SignInResponse{}, err - } - if response.WrongCredentialsError != nil { - return tpepmodels.SignInResponse{ - WrongCredentialsError: &struct{}{}, - }, nil - } - return tpepmodels.SignInResponse{ - OK: &struct{ User tpepmodels.User }{ - User: tpepmodels.User{ - ID: response.OK.User.ID, - Email: response.OK.User.Email, - TimeJoined: response.OK.User.TimeJoined, - ThirdParty: nil, - }, - }, - }, nil - } - - var ogSignInUp func(thirdPartyID string, thirdPartyUserID string, email string, oAuthTokens tpmodels.TypeOAuthTokens, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (tpmodels.SignInUpResponse, error) = nil - if thirdPartyImplementation != nil { - ogSignInUp = *thirdPartyImplementation.SignInUp - } - signInUp := func(thirdPartyID string, thirdPartyUserID string, email string, oAuthTokens tpmodels.TypeOAuthTokens, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (tpepmodels.SignInUpResponse, error) { - if ogSignInUp == nil { - return tpepmodels.SignInUpResponse{}, errors.New("no thirdparty provider configured") - } - result, err := ogSignInUp(thirdPartyID, thirdPartyUserID, email, oAuthTokens, rawUserInfoFromProvider, tenantId, userContext) - if err != nil { - return tpepmodels.SignInUpResponse{}, err - } - - return tpepmodels.SignInUpResponse{ - OK: &struct { - CreatedNewUser bool - User tpepmodels.User - OAuthTokens map[string]interface{} - RawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider - }{ - CreatedNewUser: result.OK.CreatedNewUser, - User: tpepmodels.User{ - ID: result.OK.User.ID, - TimeJoined: result.OK.User.TimeJoined, - Email: result.OK.User.Email, - ThirdParty: &result.OK.User.ThirdParty, - }, - OAuthTokens: result.OK.OAuthTokens, - RawUserInfoFromProvider: result.OK.RawUserInfoFromProvider, - }, - }, nil - } - - var ogManuallyCreateOrUpdateUser func(thirdPartyID string, thirdPartyUserID string, email string, tenantId string, userContext supertokens.UserContext) (tpmodels.ManuallyCreateOrUpdateUserResponse, error) = nil - if thirdPartyImplementation != nil { - ogManuallyCreateOrUpdateUser = *thirdPartyImplementation.ManuallyCreateOrUpdateUser - } - manuallyCreateOrUpdateUser := func(thirdPartyID string, thirdPartyUserID string, email string, tenantId string, userContext supertokens.UserContext) (tpepmodels.ManuallyCreateOrUpdateUserResponse, error) { - if ogManuallyCreateOrUpdateUser == nil { - return tpepmodels.ManuallyCreateOrUpdateUserResponse{}, errors.New("no thirdparty provider configured") - } - result, err := ogManuallyCreateOrUpdateUser(thirdPartyID, thirdPartyUserID, email, tenantId, userContext) - if err != nil { - return tpepmodels.ManuallyCreateOrUpdateUserResponse{}, err - } - - return tpepmodels.ManuallyCreateOrUpdateUserResponse{ - OK: &struct { - CreatedNewUser bool - User tpepmodels.User - }{ - CreatedNewUser: result.OK.CreatedNewUser, - User: tpepmodels.User{ - ID: result.OK.User.ID, - Email: result.OK.User.Email, - TimeJoined: result.OK.User.TimeJoined, - ThirdParty: &result.OK.User.ThirdParty, - }, - }, - }, nil - } - - var ogGetProvider func(thirdPartyID string, clientType *string, tenantId string, userContext supertokens.UserContext) (*tpmodels.TypeProvider, error) - if thirdPartyImplementation != nil { - ogGetProvider = *thirdPartyImplementation.GetProvider - } - - getProvider := func(thirdPartyID string, clientType *string, tenantId string, userContext supertokens.UserContext) (*tpmodels.TypeProvider, error) { - if ogGetProvider == nil { - return nil, errors.New("no thirdparty provider configured") - } - - return ogGetProvider(thirdPartyID, clientType, tenantId, userContext) - } - - ogEPGetUserByID := *emailPasswordImplementation.GetUserByID - var ogTPGetUserById func(userID string, userContext supertokens.UserContext) (*tpmodels.User, error) = nil - if thirdPartyImplementation != nil { - ogTPGetUserById = *thirdPartyImplementation.GetUserByID - } - getUserByID := func(userID string, userContext supertokens.UserContext) (*tpepmodels.User, error) { - user, err := ogEPGetUserByID(userID, userContext) - if err != nil { - return nil, err - } - if user != nil { - return &tpepmodels.User{ - ID: user.ID, - Email: user.Email, - TimeJoined: user.TimeJoined, - TenantIds: user.TenantIds, - ThirdParty: nil, - }, nil - } - if ogTPGetUserById == nil { - return nil, nil - } - - userinfo, err := ogTPGetUserById(userID, userContext) - if err != nil { - return nil, err - } - - if userinfo != nil { - return &tpepmodels.User{ - ID: userinfo.ID, - Email: userinfo.Email, - TimeJoined: userinfo.TimeJoined, - ThirdParty: &userinfo.ThirdParty, - TenantIds: userinfo.TenantIds, - }, nil - } - return nil, nil - } - - ogEPGetUserByEmail := *emailPasswordImplementation.GetUserByEmail - var ogTPGetUsersByEmail func(email string, tenantId string, userContext supertokens.UserContext) ([]tpmodels.User, error) = nil - if thirdPartyImplementation != nil { - ogTPGetUsersByEmail = *thirdPartyImplementation.GetUsersByEmail - } - getUsersByEmail := func(email string, tenantId string, userContext supertokens.UserContext) ([]tpepmodels.User, error) { - fromEP, err := ogEPGetUserByEmail(email, tenantId, userContext) - if err != nil { - return []tpepmodels.User{}, err - } - - fromTP := []tpmodels.User{} - if ogTPGetUsersByEmail != nil { - fromTP, err = ogTPGetUsersByEmail(email, tenantId, userContext) - if err != nil { - return []tpepmodels.User{}, err - } - } - finalResult := []tpepmodels.User{} - - if fromEP != nil { - finalResult = append(finalResult, tpepmodels.User{ - ID: fromEP.ID, - TimeJoined: fromEP.TimeJoined, - Email: fromEP.Email, - ThirdParty: nil, - }) - } - - for _, tpUser := range fromTP { - finalResult = append(finalResult, tpepmodels.User{ - ID: tpUser.ID, - TimeJoined: tpUser.TimeJoined, - Email: tpUser.Email, - ThirdParty: &tpUser.ThirdParty, - }) - } - - return finalResult, nil - } - - var ogGetUserByThirdPartyInfo func(thirdPartyID string, thirdPartyUserID string, tenantId string, userContext supertokens.UserContext) (*tpmodels.User, error) = nil - if thirdPartyImplementation != nil { - ogGetUserByThirdPartyInfo = *thirdPartyImplementation.GetUserByThirdPartyInfo - } - getUserByThirdPartyInfo := func(thirdPartyID string, thirdPartyUserID string, tenantId string, userContext supertokens.UserContext) (*tpepmodels.User, error) { - if ogGetUserByThirdPartyInfo == nil { - return nil, nil - } - - userinfo, err := ogGetUserByThirdPartyInfo(thirdPartyID, thirdPartyUserID, tenantId, userContext) - if err != nil { - return nil, err - } - - if userinfo != nil { - return &tpepmodels.User{ - ID: userinfo.ID, - Email: userinfo.Email, - TimeJoined: userinfo.TimeJoined, - TenantIds: userinfo.TenantIds, - ThirdParty: &userinfo.ThirdParty, - }, nil - } - return nil, nil - } - - ogCreateResetPasswordToken := *emailPasswordImplementation.CreateResetPasswordToken - createResetPasswordToken := func(userID string, tenantId string, userContext supertokens.UserContext) (epmodels.CreateResetPasswordTokenResponse, error) { - return ogCreateResetPasswordToken(userID, tenantId, userContext) - } - - ogResetPasswordUsingToken := *emailPasswordImplementation.ResetPasswordUsingToken - resetPasswordUsingToken := func(token, newPassword string, tenantId string, userContext supertokens.UserContext) (epmodels.ResetPasswordUsingTokenResponse, error) { - return ogResetPasswordUsingToken(token, newPassword, tenantId, userContext) - } - - ogUpdateEmailOrPassword := *emailPasswordImplementation.UpdateEmailOrPassword - updateEmailOrPassword := func(userId string, email, password *string, applyPasswordPolicy *bool, tenantIdForPasswordPolicy string, userContext supertokens.UserContext) (epmodels.UpdateEmailOrPasswordResponse, error) { - user, err := (*result.GetUserByID)(userId, userContext) - if err != nil { - return epmodels.UpdateEmailOrPasswordResponse{}, err - } - - if user == nil { - return epmodels.UpdateEmailOrPasswordResponse{ - UnknownUserIdError: &struct{}{}, - }, nil - } else if user.ThirdParty != nil { - return epmodels.UpdateEmailOrPasswordResponse{}, errors.New("cannot update email or password of a user who signed up using third party login") - } - - return ogUpdateEmailOrPassword(userId, email, password, applyPasswordPolicy, tenantIdForPasswordPolicy, userContext) - } - - result.GetUserByID = &getUserByID - result.GetUsersByEmail = &getUsersByEmail - result.GetUserByThirdPartyInfo = &getUserByThirdPartyInfo - result.ThirdPartySignInUp = &signInUp - result.ThirdPartyManuallyCreateOrUpdateUser = &manuallyCreateOrUpdateUser - result.ThirdPartyGetProvider = &getProvider - result.EmailPasswordSignUp = &signUp - result.EmailPasswordSignIn = &signIn - result.CreateResetPasswordToken = &createResetPasswordToken - result.ResetPasswordUsingToken = &resetPasswordUsingToken - result.UpdateEmailOrPassword = &updateEmailOrPassword - - modifiedEp := MakeEmailPasswordRecipeImplementation(result) - (*emailPasswordImplementation.CreateResetPasswordToken) = *modifiedEp.CreateResetPasswordToken - (*emailPasswordImplementation.GetUserByEmail) = *modifiedEp.GetUserByEmail - (*emailPasswordImplementation.GetUserByID) = *modifiedEp.GetUserByID - (*emailPasswordImplementation.ResetPasswordUsingToken) = *modifiedEp.ResetPasswordUsingToken - (*emailPasswordImplementation.SignIn) = *modifiedEp.SignIn - (*emailPasswordImplementation.SignUp) = *modifiedEp.SignUp - (*emailPasswordImplementation.UpdateEmailOrPassword) = *modifiedEp.UpdateEmailOrPassword - - if thirdPartyImplementation != nil { - modifiedTp := MakeThirdPartyRecipeImplementation(result) - (*thirdPartyImplementation.GetUserByID) = *modifiedTp.GetUserByID - (*thirdPartyImplementation.GetUserByThirdPartyInfo) = *modifiedTp.GetUserByThirdPartyInfo - (*thirdPartyImplementation.GetUsersByEmail) = *modifiedTp.GetUsersByEmail - (*thirdPartyImplementation.SignInUp) = *modifiedTp.SignInUp - (*thirdPartyImplementation.ManuallyCreateOrUpdateUser) = *modifiedTp.ManuallyCreateOrUpdateUser - (*thirdPartyImplementation.GetProvider) = *modifiedTp.GetProvider - } - - return result -} diff --git a/recipe/thirdpartyemailpassword/recipeimplementation/thirdPartyRecipeImplementation.go b/recipe/thirdpartyemailpassword/recipeimplementation/thirdPartyRecipeImplementation.go deleted file mode 100644 index e1dd3b6e..00000000 --- a/recipe/thirdpartyemailpassword/recipeimplementation/thirdPartyRecipeImplementation.go +++ /dev/null @@ -1,149 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package recipeimplementation - -import ( - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func MakeThirdPartyRecipeImplementation(recipeImplementation tpepmodels.RecipeInterface) tpmodels.RecipeInterface { - - getUserByThirdPartyInfo := func(thirdPartyID string, thirdPartyUserID string, tenantId string, userContext supertokens.UserContext) (*tpmodels.User, error) { - user, err := (*recipeImplementation.GetUserByThirdPartyInfo)(thirdPartyID, thirdPartyUserID, tenantId, userContext) - if err != nil { - return nil, err - } - if user == nil || user.ThirdParty == nil { - return nil, nil - } - return &tpmodels.User{ - ID: user.ID, - Email: user.Email, - TimeJoined: user.TimeJoined, - TenantIds: user.TenantIds, - ThirdParty: *user.ThirdParty, - }, nil - } - - signInUp := func(thirdPartyID string, thirdPartyUserID string, email string, oAuthTokens tpmodels.TypeOAuthTokens, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (tpmodels.SignInUpResponse, error) { - result, err := (*recipeImplementation.ThirdPartySignInUp)(thirdPartyID, thirdPartyUserID, email, oAuthTokens, rawUserInfoFromProvider, tenantId, userContext) - if err != nil { - return tpmodels.SignInUpResponse{}, err - } - - return tpmodels.SignInUpResponse{ - OK: &struct { - CreatedNewUser bool - User tpmodels.User - OAuthTokens map[string]interface{} - RawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider - }{ - CreatedNewUser: result.OK.CreatedNewUser, - User: tpmodels.User{ - ID: result.OK.User.ID, - Email: result.OK.User.Email, - TimeJoined: result.OK.User.TimeJoined, - TenantIds: result.OK.User.TenantIds, - ThirdParty: *result.OK.User.ThirdParty, - }, - OAuthTokens: result.OK.OAuthTokens, - RawUserInfoFromProvider: result.OK.RawUserInfoFromProvider, - }, - }, nil - } - - manuallyCreateOrUpdateUser := func(thirdPartyID string, thirdPartyUserID string, email string, tenantId string, userContext supertokens.UserContext) (tpmodels.ManuallyCreateOrUpdateUserResponse, error) { - result, err := (*recipeImplementation.ThirdPartyManuallyCreateOrUpdateUser)(thirdPartyID, thirdPartyUserID, email, tenantId, userContext) - if err != nil { - return tpmodels.ManuallyCreateOrUpdateUserResponse{}, err - } - return tpmodels.ManuallyCreateOrUpdateUserResponse{ - OK: &struct { - CreatedNewUser bool - User tpmodels.User - }{ - CreatedNewUser: result.OK.CreatedNewUser, - User: tpmodels.User{ - ID: result.OK.User.ID, - Email: result.OK.User.Email, - TimeJoined: result.OK.User.TimeJoined, - TenantIds: result.OK.User.TenantIds, - ThirdParty: struct { - ID string "json:\"id\"" - UserID string "json:\"userId\"" - }{ - ID: result.OK.User.ThirdParty.ID, - UserID: result.OK.User.ThirdParty.UserID, - }, - }, - }, - }, nil - } - - getUserByID := func(userID string, userContext supertokens.UserContext) (*tpmodels.User, error) { - user, err := (*recipeImplementation.GetUserByID)(userID, userContext) - if err != nil { - return nil, err - } - if user == nil || user.ThirdParty == nil { - return nil, nil - } - return &tpmodels.User{ - ID: user.ID, - Email: user.Email, - TimeJoined: user.TimeJoined, - TenantIds: user.TenantIds, - ThirdParty: *user.ThirdParty, - }, nil - } - - getUserByEmail := func(email string, tenantId string, userContext supertokens.UserContext) ([]tpmodels.User, error) { - users, err := (*recipeImplementation.GetUsersByEmail)(email, tenantId, userContext) - if err != nil { - return nil, err - } - - finalResult := []tpmodels.User{} - - for _, tpepUser := range users { - if tpepUser.ThirdParty != nil { - finalResult = append(finalResult, tpmodels.User{ - ID: tpepUser.ID, - TimeJoined: tpepUser.TimeJoined, - Email: tpepUser.Email, - TenantIds: tpepUser.TenantIds, - ThirdParty: *tpepUser.ThirdParty, - }) - } - } - return finalResult, nil - } - - getProvider := func(thirdPartyID string, clientType *string, tenantId string, userContext supertokens.UserContext) (*tpmodels.TypeProvider, error) { - return (*recipeImplementation.ThirdPartyGetProvider)(thirdPartyID, clientType, tenantId, userContext) - } - - return tpmodels.RecipeInterface{ - GetUserByID: &getUserByID, - GetUsersByEmail: &getUserByEmail, - GetUserByThirdPartyInfo: &getUserByThirdPartyInfo, - SignInUp: &signInUp, - ManuallyCreateOrUpdateUser: &manuallyCreateOrUpdateUser, - GetProvider: &getProvider, - } -} diff --git a/recipe/thirdpartyemailpassword/signinFeature_test.go b/recipe/thirdpartyemailpassword/signinFeature_test.go deleted file mode 100644 index 21d36280..00000000 --- a/recipe/thirdpartyemailpassword/signinFeature_test.go +++ /dev/null @@ -1,458 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package thirdpartyemailpassword - -import ( - "bytes" - "encoding/json" - "io" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/session" - "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" - "github.com/supertokens/supertokens-golang/test/unittesting" - "gopkg.in/h2non/gock.v1" -) - -func TestAfterDisablingTheDefaultSigninupAPIdoesNotWork(t *testing.T) { - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - { - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "google", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: "test", - ClientSecret: "test-secret", - }, - }, - }, - }, - }, - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - *originalImplementation.ThirdPartySignInUpPOST = nil - return originalImplementation - }, - }, - }), - }, - } - - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) - if err != nil { - t.Error(err.Error()) - } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() - - signinupPostData := map[string]interface{}{ - "thirdPartyId": "google", - "redirectURIInfo": map[string]interface{}{ - "redirectURIOnProviderDashboard": "http://127.0.0.1/callback", - "redirectURIQueryParams": map[string]interface{}{ - "code": "abcdefghj", - }, - }, - } - - postBody, err := json.Marshal(signinupPostData) - if err != nil { - t.Error(err.Error()) - } - - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) - if err != nil { - t.Error(err.Error()) - } - assert.Equal(t, http.StatusNotFound, resp.StatusCode) -} - -func TestAfterDisablingTheDefaultSigninAPIdoesNotWork(t *testing.T) { - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - *originalImplementation.EmailPasswordSignInPOST = nil - return originalImplementation - }, - }, - }), - }, - } - - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) - if err != nil { - t.Error(err.Error()) - } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() - - resp, err := unittesting.SignInRequest("random@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - assert.Equal(t, http.StatusNotFound, resp.StatusCode) -} - -func TestHandlePostSignUpInGetsSetCorrectly(t *testing.T) { - userId := "" - loginType := "" - customAntiCsrfVal := "VIA_TOKEN" - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - originalSignInUpPost := *originalImplementation.ThirdPartySignInUpPOST - *originalImplementation.ThirdPartySignInUpPOST = func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.ThirdPartySignInUpPOSTResponse, error) { - resp, err := originalSignInUpPost(provider, input, tenantId, options, userContext) - if err != nil { - t.Error(err.Error()) - } - userId = resp.OK.User.ID - loginType = "thirdparty" - return resp, err - } - return originalImplementation - }, - }, - Providers: []tpmodels.ProviderInput{ - customProvider2, - }, - }), - session.Init(&sessmodels.TypeInput{ - AntiCsrf: &customAntiCsrfVal, - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - }, - } - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) - if err != nil { - t.Error(err.Error()) - } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() - - defer gock.OffAll() - gock.New("https://test.com/"). - Post("oauth/token"). - Reply(200). - JSON(map[string]string{}) - - postData := map[string]interface{}{ - "thirdPartyId": "custom", - "redirectURIInfo": map[string]interface{}{ - "redirectURIOnProviderDashboard": "http://127.0.0.1/callback", - "redirectURIQueryParams": map[string]interface{}{ - "code": "abcdefghj", - }, - }, - } - - postBody, err := json.Marshal(postData) - if err != nil { - t.Error(err.Error()) - } - - gock.New(testServer.URL).EnableNetworking().Persist() - gock.New("http://localhost:8080/").EnableNetworking().Persist() - - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) - if err != nil { - t.Error(err.Error()) - } - assert.Equal(t, http.StatusOK, resp.StatusCode) - dataInBytes, err := io.ReadAll(resp.Body) - if err != nil { - t.Error(err.Error()) - } - resp.Body.Close() - - var result map[string]interface{} - - err = json.Unmarshal(dataInBytes, &result) - if err != nil { - t.Error(err.Error()) - } - - user := result["user"].(map[string]interface{}) - - assert.Equal(t, userId, user["id"]) - assert.Equal(t, "thirdparty", loginType) -} - -func TestSignInAPIWorksWhenInputIsFine(t *testing.T) { - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(nil), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - }, - } - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) - if err != nil { - t.Error(err.Error()) - } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() - - resp, err := unittesting.SignupRequest("random@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - - assert.Equal(t, http.StatusOK, resp.StatusCode) - dataInBytes, err := io.ReadAll(resp.Body) - if err != nil { - t.Error(err.Error()) - } - var result map[string]interface{} - json.Unmarshal(dataInBytes, &result) - resp.Body.Close() - - assert.Equal(t, "OK", result["status"]) - - signupUserInfo := result["user"].(map[string]interface{}) - - resp1, err := unittesting.SignInRequest("random@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - - assert.Equal(t, http.StatusOK, resp1.StatusCode) - dataInBytes1, err := io.ReadAll(resp1.Body) - if err != nil { - t.Error(err.Error()) - } - var result1 map[string]interface{} - json.Unmarshal(dataInBytes1, &result1) - resp1.Body.Close() - - assert.Equal(t, "OK", result1["status"]) - - signInUserInfo := result1["user"].(map[string]interface{}) - - assert.Equal(t, signInUserInfo["id"], signupUserInfo["id"]) - assert.Equal(t, signInUserInfo["email"], signupUserInfo["email"]) -} - -func TestSigninAPIthrowsAnErrorWhenEmailDoesNotExist(t *testing.T) { - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(nil), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - }, - } - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) - if err != nil { - t.Error(err.Error()) - } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() - - resp, err := unittesting.SignupRequest("random@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - - assert.Equal(t, http.StatusOK, resp.StatusCode) - dataInBytes, err := io.ReadAll(resp.Body) - if err != nil { - t.Error(err.Error()) - } - var result map[string]interface{} - json.Unmarshal(dataInBytes, &result) - resp.Body.Close() - - assert.Equal(t, "OK", result["status"]) - - resp1, err := unittesting.SignInRequest("rand@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - - assert.Equal(t, http.StatusOK, resp1.StatusCode) - dataInBytes1, err := io.ReadAll(resp1.Body) - if err != nil { - t.Error(err.Error()) - } - var result1 map[string]interface{} - json.Unmarshal(dataInBytes1, &result1) - resp1.Body.Close() - - assert.Equal(t, "WRONG_CREDENTIALS_ERROR", result1["status"]) -} - -func TestCustomEmailValidatorsToSignupAndMakeSureTheyAreAppliedToSignIn(t *testing.T) { - configValue := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{ - Init(&tpepmodels.TypeInput{ - SignUpFeature: &epmodels.TypeInputSignUp{ - FormFields: []epmodels.TypeInputFormField{ - { - ID: "email", - Validate: func(value interface{}, tenantId string) *string { - customErrorMessage := "email does not start with test" - if strings.HasPrefix(value.(string), "test") { - return nil - } - return &customErrorMessage - }, - }, - }, - }, - }), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - }, - } - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - err := supertokens.Init(configValue) - if err != nil { - t.Error(err.Error()) - } - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - defer testServer.Close() - - resp, err := unittesting.SignupRequest("testrandom@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - - assert.Equal(t, http.StatusOK, resp.StatusCode) - dataInBytes, err := io.ReadAll(resp.Body) - if err != nil { - t.Error(err.Error()) - } - var result map[string]interface{} - json.Unmarshal(dataInBytes, &result) - resp.Body.Close() - - assert.Equal(t, "OK", result["status"]) - - resp1, err := unittesting.SignInRequest("rand@gmail.com", "validpass123", testServer.URL) - if err != nil { - t.Error(err.Error()) - } - - assert.Equal(t, http.StatusOK, resp1.StatusCode) - dataInBytes1, err := io.ReadAll(resp1.Body) - if err != nil { - t.Error(err.Error()) - } - var result1 map[string]interface{} - json.Unmarshal(dataInBytes1, &result1) - resp1.Body.Close() - - assert.Equal(t, "FIELD_ERROR", result1["status"]) - assert.Equal(t, "email does not start with test", result1["formFields"].([]interface{})[0].(map[string]interface{})["error"]) - assert.Equal(t, "email", result1["formFields"].([]interface{})[0].(map[string]interface{})["id"]) -} diff --git a/recipe/thirdpartyemailpassword/testingUtils.go b/recipe/thirdpartyemailpassword/testingUtils.go deleted file mode 100644 index aa81b282..00000000 --- a/recipe/thirdpartyemailpassword/testingUtils.go +++ /dev/null @@ -1,160 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package thirdpartyemailpassword - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/supertokens/supertokens-golang/recipe/emailpassword" - "github.com/supertokens/supertokens-golang/recipe/emailverification" - "github.com/supertokens/supertokens-golang/recipe/multitenancy" - "github.com/supertokens/supertokens-golang/recipe/session" - "github.com/supertokens/supertokens-golang/recipe/thirdparty" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/supertokens" - "github.com/supertokens/supertokens-golang/test/unittesting" -) - -func resetAll() { - supertokens.ResetForTest() - ResetForTest() - session.ResetForTest() - emailverification.ResetForTest() - thirdparty.ResetForTest() - emailpassword.ResetForTest() - multitenancy.ResetForTest() -} - -func BeforeEach() { - unittesting.KillAllST() - resetAll() - unittesting.SetUpST() -} - -func AfterEach() { - unittesting.KillAllST() - resetAll() - unittesting.CleanST() -} - -type PostDataForCustomProvider struct { - ThirdPartyId string `json:"thirdPartyId"` - OAuthTokens map[string]interface{} `json:"oAuthTokens"` -} - -var customProvider1 = tpmodels.ProviderInput{ - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "custom", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: "supertokens", - }, - }, - AuthorizationEndpoint: "https://test.com/oauth/auth", - AuthorizationEndpointQueryParams: map[string]interface{}{ - "scope": "test", - "client_id": "supertokens", - }, - TokenEndpoint: "https://test.com/oauth/token", - }, - Override: func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { - originalImplementation.GetUserInfo = func(oAuthTokens tpmodels.TypeOAuthTokens, userContext supertokens.UserContext) (tpmodels.TypeUserInfo, error) { - return tpmodels.TypeUserInfo{ - ThirdPartyUserId: "user", - Email: &tpmodels.EmailStruct{ - ID: "email@test.com", - IsVerified: true, - }, - }, nil - - } - return originalImplementation - }, -} - -var customProvider2 = tpmodels.ProviderInput{ - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "custom", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: "supertokens", - }, - }, - AuthorizationEndpoint: "https://test.com/oauth/auth", - TokenEndpoint: "https://test.com/oauth/token", - }, - Override: func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { - originalImplementation.GetUserInfo = func(oAuthTokens tpmodels.TypeOAuthTokens, userContext supertokens.UserContext) (tpmodels.TypeUserInfo, error) { - return tpmodels.TypeUserInfo{ - ThirdPartyUserId: "user", - Email: &tpmodels.EmailStruct{ - ID: "email@test.com", - IsVerified: true, - }, - }, nil - } - return originalImplementation - }, -} - -func supertokensInitForTest(t *testing.T, recipes ...supertokens.Recipe) *httptest.Server { - config := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: recipes, - } - - err := supertokens.Init(config) - assert.NoError(t, err) - - mux := http.NewServeMux() - testServer := httptest.NewServer(supertokens.Middleware(mux)) - return testServer -} - -var customProviderForEmailVerification = tpmodels.ProviderInput{ - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "custom", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: "supertokens", - }, - }, - AuthorizationEndpoint: "https://test.com/oauth/auth", - TokenEndpoint: "https://test.com/oauth/token", - }, - Override: func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { - originalImplementation.GetUserInfo = func(oAuthTokens tpmodels.TypeOAuthTokens, userContext supertokens.UserContext) (tpmodels.TypeUserInfo, error) { - return tpmodels.TypeUserInfo{ - ThirdPartyUserId: "user", - Email: &tpmodels.EmailStruct{ - ID: "test@example.com", - IsVerified: false, - }, - }, nil - } - return originalImplementation - }, -} diff --git a/recipe/thirdpartyemailpassword/tpep_email_test.go b/recipe/thirdpartyemailpassword/tpep_email_test.go deleted file mode 100644 index 828eeb8c..00000000 --- a/recipe/thirdpartyemailpassword/tpep_email_test.go +++ /dev/null @@ -1,968 +0,0 @@ -/* - * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package thirdpartyemailpassword - -import ( - "bytes" - "encoding/json" - "net/http" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - "github.com/supertokens/supertokens-golang/recipe/emailpassword" - "github.com/supertokens/supertokens-golang/recipe/emailverification" - "github.com/supertokens/supertokens-golang/recipe/emailverification/emaildelivery/smtpService" - "github.com/supertokens/supertokens-golang/recipe/emailverification/evmodels" - "github.com/supertokens/supertokens-golang/recipe/session" - "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" - "github.com/supertokens/supertokens-golang/test/unittesting" -) - -func TestDefaultBackwardCompatibilityPasswordResetForEmailPasswordUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(nil), - ) - defer testServer.Close() - - EmailPasswordSignUp("public", "test@example.com", "1234abcd") - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.True(t, emailpassword.PasswordResetEmailSentForTest) - assert.Equal(t, emailpassword.PasswordResetDataForTest.User.Email, "test@example.com") - assert.NotEmpty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) -} - -func TestDefaultBackwardCompatibilityPasswordResetForThirdpartyUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(nil), - ) - defer testServer.Close() - - ThirdPartyManuallyCreateOrUpdateUser("public", "custom", "user-id", "test@example.com") - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) -} - -func TestDefaultBackwardCompatibilityPasswordResetForNonExistantUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(nil), - ) - defer testServer.Close() - - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) -} - -func TestCustomOverrideResetPasswordForEmailPasswordUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - customCalled := false - email := "" - passwordResetLink := "" - - tpepConfig := &tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { - *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.PasswordReset != nil { - customCalled = true - email = input.PasswordReset.User.Email - passwordResetLink = input.PasswordReset.PasswordResetLink - } - return nil - } - return originalImplementation - }, - }, - } - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - EmailPasswordSignUp("public", "test@example.com", "1234abcd") - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler called - assert.Equal(t, email, "test@example.com") - assert.NotEmpty(t, passwordResetLink) - assert.True(t, customCalled) -} - -func TestCustomOverrideResetPasswordForThirdpartyUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - customCalled := false - email := "" - passwordResetLink := "" - - tpepConfig := &tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { - *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.PasswordReset != nil { - customCalled = true - email = input.PasswordReset.User.Email - passwordResetLink = input.PasswordReset.PasswordResetLink - } - return nil - } - return originalImplementation - }, - }, - } - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - ThirdPartyManuallyCreateOrUpdateUser("public", "custom", "user-id", "test@example.com") - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler not called - assert.Empty(t, email) - assert.Empty(t, passwordResetLink) - assert.False(t, customCalled) -} - -func TestCustomOverrideResetPasswordForNonExistantUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - customCalled := false - email := "" - passwordResetLink := "" - - tpepConfig := &tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { - *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.PasswordReset != nil { - customCalled = true - email = input.PasswordReset.User.Email - passwordResetLink = input.PasswordReset.PasswordResetLink - } - return nil - } - return originalImplementation - }, - }, - } - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler not called - assert.Empty(t, email) - assert.Empty(t, passwordResetLink) - assert.False(t, customCalled) -} - -func TestSMTPOverridePasswordResetForEmailPasswordUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - getContentCalled := false - sendRawEmailCalled := false - email := "" - passwordResetLink := "" - - smtpService := MakeSMTPService(emaildelivery.SMTPServiceConfig{ - Settings: emaildelivery.SMTPSettings{ - Host: "", - From: emaildelivery.SMTPFrom{ - Name: "Test User", - Email: "", - }, - Port: 123, - Password: "", - }, - Override: func(originalImplementation emaildelivery.SMTPInterface) emaildelivery.SMTPInterface { - (*originalImplementation.GetContent) = func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { - if input.PasswordReset != nil { - email = input.PasswordReset.User.Email - passwordResetLink = input.PasswordReset.PasswordResetLink - getContentCalled = true - } - return emaildelivery.EmailContent{}, nil - } - - (*originalImplementation.SendRawEmail) = func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { - sendRawEmailCalled = true - return nil - } - - return originalImplementation - }, - }) - tpepConfig := &tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Service: smtpService, - }, - } - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - EmailPasswordSignUp("public", "test@example.com", "1234abcd") - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - assert.Equal(t, email, "test@example.com") - assert.NotEmpty(t, passwordResetLink) - assert.Equal(t, getContentCalled, true) - assert.Equal(t, sendRawEmailCalled, true) -} - -func TestSMTPOverridePasswordResetForThirdpartyUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - getContentCalled := false - sendRawEmailCalled := false - email := "" - passwordResetLink := "" - - smtpService := MakeSMTPService(emaildelivery.SMTPServiceConfig{ - Settings: emaildelivery.SMTPSettings{ - Host: "", - From: emaildelivery.SMTPFrom{ - Name: "Test User", - Email: "", - }, - Port: 123, - Password: "", - }, - Override: func(originalImplementation emaildelivery.SMTPInterface) emaildelivery.SMTPInterface { - (*originalImplementation.GetContent) = func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { - if input.PasswordReset != nil { - email = input.PasswordReset.User.Email - passwordResetLink = input.PasswordReset.PasswordResetLink - getContentCalled = true - } - return emaildelivery.EmailContent{}, nil - } - - (*originalImplementation.SendRawEmail) = func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { - sendRawEmailCalled = true - return nil - } - - return originalImplementation - }, - }) - tpepConfig := &tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Service: smtpService, - }, - } - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - ThirdPartyManuallyCreateOrUpdateUser("public", "custom", "user-id", "test@example.com") - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler not called - assert.Empty(t, email) - assert.Empty(t, passwordResetLink) - assert.False(t, getContentCalled) - assert.False(t, sendRawEmailCalled) -} - -func TestSMTPOverridePasswordResetForNonExistantUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - getContentCalled := false - sendRawEmailCalled := false - email := "" - passwordResetLink := "" - - smtpService := MakeSMTPService(emaildelivery.SMTPServiceConfig{ - Settings: emaildelivery.SMTPSettings{ - Host: "", - From: emaildelivery.SMTPFrom{ - Name: "Test User", - Email: "", - }, - Port: 123, - Password: "", - }, - Override: func(originalImplementation emaildelivery.SMTPInterface) emaildelivery.SMTPInterface { - (*originalImplementation.GetContent) = func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { - if input.PasswordReset != nil { - email = input.PasswordReset.User.Email - passwordResetLink = input.PasswordReset.PasswordResetLink - getContentCalled = true - } - return emaildelivery.EmailContent{}, nil - } - - (*originalImplementation.SendRawEmail) = func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { - sendRawEmailCalled = true - return nil - } - - return originalImplementation - }, - }) - tpepConfig := &tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Service: smtpService, - }, - } - testServer := supertokensInitForTest( - t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - resp, err := unittesting.PasswordResetTokenRequest("test@example.com", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler not called - assert.Empty(t, email) - assert.Empty(t, passwordResetLink) - assert.False(t, getContentCalled) - assert.False(t, sendRawEmailCalled) -} - -func TestDefaultBackwardCompatibilityEmailVerifyForEmailPasswordUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - testServer := supertokensInitForTest( - t, - emailverification.Init(evmodels.TypeInput{Mode: evmodels.ModeOptional}), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(nil), - ) - defer testServer.Close() - - resp, err := unittesting.SignupRequest("test@example.com", "1234abcd", testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - cookies := resp.Cookies() - resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.True(t, emailverification.EmailVerificationEmailSentForTest) - assert.Equal(t, emailverification.EmailVerificationDataForTest.User.Email, "test@example.com") - assert.NotEmpty(t, emailverification.EmailVerificationDataForTest.EmailVerifyURLWithToken) -} - -func TestDefaultBackwardCompatibilityEmailVerifyForThirdpartyUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - tpepConfig := &tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - customProviderForEmailVerification, - }, - } - testServer := supertokensInitForTest(t, - emailverification.Init(evmodels.TypeInput{Mode: evmodels.ModeOptional}), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - signinupPostData := PostDataForCustomProvider{ - ThirdPartyId: "custom", - OAuthTokens: map[string]interface{}{ - "access_token": "saodiasjodai", - }, - } - - postBody, err := json.Marshal(signinupPostData) - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) - assert.NoError(t, err) - - cookies := resp.Cookies() - - resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - assert.True(t, emailverification.EmailVerificationEmailSentForTest) - assert.Equal(t, emailverification.EmailVerificationDataForTest.User.Email, "test@example.com") - assert.NotEmpty(t, emailverification.EmailVerificationDataForTest.EmailVerifyURLWithToken) -} - -// func TestBackwardCompatibilityEmailVerifyForEmailPasswordUser(t *testing.T) { -// BeforeEach() -// unittesting.StartUpST("localhost", "8080") -// defer AfterEach() - -// customCalled := false -// email := "" -// emailVerifyLink := "" - -// tpepConfig := &tpepmodels.TypeInput{ -// EmailVerificationFeature: &tpepmodels.TypeInputEmailVerificationFeature{ -// CreateAndSendCustomEmail: func(user tpepmodels.User, emailVerificationURLWithToken string, userContext supertokens.UserContext) { -// email = user.Email -// emailVerifyLink = emailVerificationURLWithToken -// customCalled = true -// }, -// }, -// } -// testServer := supertokensInitForTest(t, session.Init(nil), Init(tpepConfig)) -// defer testServer.Close() - -// resp, err := unittesting.SignupRequest("test@example.com", "1234abcd", testServer.URL) -// assert.NoError(t, err) - -// cookies := resp.Cookies() -// resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) -// assert.NoError(t, err) -// assert.Equal(t, http.StatusOK, resp.StatusCode) - -// // Default handler not called -// assert.False(t, emailpassword.PasswordResetEmailSentForTest) -// assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) -// assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - -// // Custom handler called -// assert.Equal(t, email, "test@example.com") -// assert.NotEmpty(t, emailVerifyLink) -// assert.True(t, customCalled) -// } - -// func TestBackwardCompatibilityEmailVerifyForThirdpartyUser(t *testing.T) { -// BeforeEach() -// unittesting.StartUpST("localhost", "8080") -// defer AfterEach() - -// customCalled := false -// email := "" -// emailVerifyLink := "" -// var thirdparty *struct { -// ID string `json:"id"` -// UserID string `json:"userId"` -// } - -// tpepConfig := &tpepmodels.TypeInput{ -// EmailVerificationFeature: &tpepmodels.TypeInputEmailVerificationFeature{ -// CreateAndSendCustomEmail: func(user tpepmodels.User, emailVerificationURLWithToken string, userContext supertokens.UserContext) { -// email = user.Email -// emailVerifyLink = emailVerificationURLWithToken -// thirdparty = user.ThirdParty -// customCalled = true -// }, -// }, -// Providers: []tpmodels.TypeProvider{customProviderForEmailVerification}, -// } -// testServer := supertokensInitForTest(t, session.Init(nil), Init(tpepConfig)) -// defer testServer.Close() - -// signinupPostData := PostDataForCustomProvider{ -// ThirdPartyId: "custom", -// AuthCodeResponse: map[string]string{ -// "access_token": "saodiasjodai", -// }, -// RedirectUri: "http://127.0.0.1/callback", -// } - -// postBody, err := json.Marshal(signinupPostData) -// resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) -// assert.NoError(t, err) - -// cookies := resp.Cookies() -// resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) -// assert.NoError(t, err) -// assert.Equal(t, http.StatusOK, resp.StatusCode) - -// // Default handler not called -// assert.False(t, emailpassword.PasswordResetEmailSentForTest) -// assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) -// assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - -// // Custom handler called -// assert.Equal(t, email, "test@example.com") -// assert.NotEmpty(t, emailVerifyLink) -// assert.NotNil(t, thirdparty) -// assert.True(t, customCalled) -// } - -func TestCustomOverrideEmailVerifyForEmailPasswordUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - customCalled := false - email := "" - emailVerifyLink := "" - - tpepConfig := &tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - customProviderForEmailVerification, - }, - } - testServer := supertokensInitForTest( - t, - emailverification.Init(evmodels.TypeInput{ - Mode: evmodels.ModeOptional, - EmailDelivery: &emaildelivery.TypeInput{ - Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { - *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.EmailVerification != nil { - customCalled = true - email = input.EmailVerification.User.Email - emailVerifyLink = input.EmailVerification.EmailVerifyLink - } - return nil - } - return originalImplementation - }, - }, - }), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - resp, err := unittesting.SignupRequest("test@example.com", "1234abcd", testServer.URL) - assert.NoError(t, err) - cookies := resp.Cookies() - resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler called - assert.Equal(t, email, "test@example.com") - assert.NotEmpty(t, emailVerifyLink) - assert.True(t, customCalled) -} - -func TestCustomOverrideEmailVerifyForThirdpartyUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - customCalled := false - email := "" - emailVerifyLink := "" - - tpepConfig := &tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - customProviderForEmailVerification, - }, - } - testServer := supertokensInitForTest( - t, - emailverification.Init(evmodels.TypeInput{ - Mode: evmodels.ModeOptional, - EmailDelivery: &emaildelivery.TypeInput{ - Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { - *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - if input.EmailVerification != nil { - customCalled = true - email = input.EmailVerification.User.Email - emailVerifyLink = input.EmailVerification.EmailVerifyLink - } - return nil - } - return originalImplementation - }, - }, - }), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - signinupPostData := PostDataForCustomProvider{ - ThirdPartyId: "custom", - OAuthTokens: map[string]interface{}{ - "access_token": "saodiasjodai", - }, - } - - postBody, err := json.Marshal(signinupPostData) - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) - assert.NoError(t, err) - - cookies := resp.Cookies() - resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - // Custom handler called - assert.Equal(t, email, "test@example.com") - assert.NotEmpty(t, emailVerifyLink) - assert.True(t, customCalled) -} - -func TestSMTPOverrideEmailVerifyForEmailPasswordUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - getContentCalled := false - sendRawEmailCalled := false - email := "" - emailVerifyLink := "" - - smtpService := smtpService.MakeSMTPService(emaildelivery.SMTPServiceConfig{ - Settings: emaildelivery.SMTPSettings{ - Host: "", - From: emaildelivery.SMTPFrom{ - Name: "Test User", - Email: "", - }, - Port: 123, - Password: "", - }, - Override: func(originalImplementation emaildelivery.SMTPInterface) emaildelivery.SMTPInterface { - (*originalImplementation.GetContent) = func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { - if input.EmailVerification != nil { - email = input.EmailVerification.User.Email - emailVerifyLink = input.EmailVerification.EmailVerifyLink - getContentCalled = true - } - return emaildelivery.EmailContent{}, nil - } - - (*originalImplementation.SendRawEmail) = func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { - sendRawEmailCalled = true - return nil - } - - return originalImplementation - }, - }) - tpepConfig := &tpepmodels.TypeInput{} - testServer := supertokensInitForTest( - t, - emailverification.Init(evmodels.TypeInput{ - Mode: evmodels.ModeOptional, - EmailDelivery: &emaildelivery.TypeInput{ - Service: smtpService, - }, - }), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - resp, err := unittesting.SignupRequest("test@example.com", "1234abcd", testServer.URL) - assert.NoError(t, err) - - cookies := resp.Cookies() - resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - assert.Equal(t, email, "test@example.com") - assert.NotEmpty(t, emailVerifyLink) - assert.Equal(t, getContentCalled, true) - assert.Equal(t, sendRawEmailCalled, true) -} - -func TestSMTPOverrideEmailVerifyForThirdpartyUser(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - getContentCalled := false - sendRawEmailCalled := false - email := "" - emailVerifyLink := "" - - smtpService := smtpService.MakeSMTPService(emaildelivery.SMTPServiceConfig{ - Settings: emaildelivery.SMTPSettings{ - Host: "", - From: emaildelivery.SMTPFrom{ - Name: "Test User", - Email: "", - }, - Port: 123, - Password: "", - }, - Override: func(originalImplementation emaildelivery.SMTPInterface) emaildelivery.SMTPInterface { - (*originalImplementation.GetContent) = func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { - if input.EmailVerification != nil { - email = input.EmailVerification.User.Email - emailVerifyLink = input.EmailVerification.EmailVerifyLink - getContentCalled = true - } - return emaildelivery.EmailContent{}, nil - } - - (*originalImplementation.SendRawEmail) = func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { - sendRawEmailCalled = true - return nil - } - - return originalImplementation - }, - }) - tpepConfig := &tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{customProviderForEmailVerification}, - } - testServer := supertokensInitForTest( - t, - emailverification.Init(evmodels.TypeInput{ - Mode: evmodels.ModeOptional, - EmailDelivery: &emaildelivery.TypeInput{ - Service: smtpService, - }, - }), - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(tpepConfig), - ) - defer testServer.Close() - - signinupPostData := PostDataForCustomProvider{ - ThirdPartyId: "custom", - OAuthTokens: map[string]interface{}{ - "access_token": "saodiasjodai", - }, - } - - postBody, err := json.Marshal(signinupPostData) - resp, err := http.Post(testServer.URL+"/auth/signinup", "application/json", bytes.NewBuffer(postBody)) - assert.NoError(t, err) - - cookies := resp.Cookies() - resp, err = unittesting.EmailVerificationTokenRequest(cookies, testServer.URL) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, resp.StatusCode) - - // Default handler not called - assert.False(t, emailpassword.PasswordResetEmailSentForTest) - assert.Empty(t, emailpassword.PasswordResetDataForTest.User.Email) - assert.Empty(t, emailpassword.PasswordResetDataForTest.PasswordResetURLWithToken) - - assert.Equal(t, email, "test@example.com") - assert.NotEmpty(t, emailVerifyLink) - assert.Equal(t, getContentCalled, true) - assert.Equal(t, sendRawEmailCalled, true) -} - -func TestSendResetPassworEmailFunction(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - resetLink := "" - - testServer := supertokensInitForTest(t, - session.Init(&sessmodels.TypeInput{ - GetTokenTransferMethod: func(req *http.Request, forCreateNewSession bool, userContext supertokens.UserContext) sessmodels.TokenTransferMethod { - return sessmodels.CookieTransferMethod - }, - }), - Init(&tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Override: func(originalImplementation emaildelivery.EmailDeliveryInterface) emaildelivery.EmailDeliveryInterface { - *originalImplementation.SendEmail = func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { - resetLink = input.PasswordReset.PasswordResetLink - return nil - } - return originalImplementation - }, - }, - }), - ) - defer testServer.Close() - - user, err := EmailPasswordSignUp("public", "test@example.com", "pass1234") - assert.NoError(t, err) - - resp, err := SendResetPasswordEmail("public", user.OK.User.ID) - assert.NoError(t, err) - assert.True(t, resp.OK != nil) - - assert.Contains(t, resetLink, "rid=thirdpartyemailpassword") - assert.Contains(t, resetLink, "tenantId=public") - assert.Contains(t, resetLink, "token=") -} diff --git a/recipe/thirdpartyemailpassword/tpep_userIdMapping_test.go b/recipe/thirdpartyemailpassword/tpep_userIdMapping_test.go deleted file mode 100644 index 34ecd32f..00000000 --- a/recipe/thirdpartyemailpassword/tpep_userIdMapping_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package thirdpartyemailpassword - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" - "github.com/supertokens/supertokens-golang/test/unittesting" -) - -func initForUserIdMappingTest(t *testing.T) { - - config := supertokens.TypeInput{ - Supertokens: &supertokens.ConnectionInfo{ - ConnectionURI: "http://localhost:8080", - }, - AppInfo: supertokens.AppInfo{ - APIDomain: "api.supertokens.io", - AppName: "SuperTokens", - WebsiteDomain: "supertokens.io", - }, - RecipeList: []supertokens.Recipe{Init(&tpepmodels.TypeInput{ - Providers: []tpmodels.ProviderInput{ - { - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "google", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: "test", - ClientSecret: "test-secret", - }, - }, - }, - }, - }, - })}, - } - - err := supertokens.Init(config) - assert.NoError(t, err) -} - -func TestCreateUserIdMappingUsingEmail(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - initForUserIdMappingTest(t) - - querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") - assert.NoError(t, err) - - cdiVersion, err := querier.GetQuerierAPIVersion() - assert.NoError(t, err) - - if unittesting.MaxVersion(cdiVersion, "2.14") == "2.14" { - return - } - - signUpResponse, err := ThirdPartyManuallyCreateOrUpdateUser("public", "google", "googleID", "test@example.com") - assert.NoError(t, err) - - externalUserId := "externalId" - externalUserIdInfo := "externalIdInfo" - createResp, err := supertokens.CreateUserIdMapping(signUpResponse.OK.User.ID, externalUserId, &externalUserIdInfo, nil) - assert.NoError(t, err) - assert.NotNil(t, createResp.OK) - - { // Using supertokens ID - userResp, err := GetUserById(signUpResponse.OK.User.ID) - assert.NoError(t, err) - assert.Equal(t, externalUserId, userResp.ID) - } - - { // Using external ID - userResp, err := GetUserById(externalUserId) - assert.NoError(t, err) - assert.Equal(t, externalUserId, userResp.ID) - } - - { // Using thirdparty info - userResp, err := GetUserByThirdPartyInfo("public", "google", "googleID") - assert.NoError(t, err) - assert.Equal(t, externalUserId, userResp.ID) - } -} - -func TestEPCreateUserIdMappingGetUserById(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - initForUserIdMappingTest(t) - - querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") - assert.NoError(t, err) - - cdiVersion, err := querier.GetQuerierAPIVersion() - assert.NoError(t, err) - - if unittesting.MaxVersion(cdiVersion, "2.14") == "2.14" { - return - } - - signUpResponse, err := EmailPasswordSignUp("public", "test@example.com", "testpass123") - assert.NoError(t, err) - - assert.NotNil(t, signUpResponse.OK) - - externalUserId := "externalId" - externalUserIdInfo := "externalIdInfo" - createResp, err := supertokens.CreateUserIdMapping(signUpResponse.OK.User.ID, externalUserId, &externalUserIdInfo, nil) - assert.NoError(t, err) - assert.NotNil(t, createResp.OK) - - { // Using supertokens ID - userResp, err := GetUserById(signUpResponse.OK.User.ID) - assert.NoError(t, err) - assert.Equal(t, externalUserId, userResp.ID) - } - - { // Using external ID - userResp, err := GetUserById(externalUserId) - assert.NoError(t, err) - assert.Equal(t, externalUserId, userResp.ID) - } -} - -func TestEPCreateUserIdMappingGetUserByEmail(t *testing.T) { - BeforeEach() - unittesting.StartUpST("localhost", "8080") - defer AfterEach() - - initForUserIdMappingTest(t) - - querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") - assert.NoError(t, err) - - cdiVersion, err := querier.GetQuerierAPIVersion() - assert.NoError(t, err) - - if unittesting.MaxVersion(cdiVersion, "2.14") == "2.14" { - return - } - - signUpResponse, err := EmailPasswordSignUp("public", "test@example.com", "testpass123") - assert.NoError(t, err) - - assert.NotNil(t, signUpResponse.OK) - - externalUserId := "externalId" - externalUserIdInfo := "externalIdInfo" - createResp, err := supertokens.CreateUserIdMapping(signUpResponse.OK.User.ID, externalUserId, &externalUserIdInfo, nil) - assert.NoError(t, err) - assert.NotNil(t, createResp.OK) - - userResp, err := GetUsersByEmail("public", "test@example.com") - assert.NoError(t, err) - assert.NotNil(t, userResp) - assert.Equal(t, 1, len(userResp)) - for _, user := range userResp { - assert.Equal(t, externalUserId, user.ID) - } -} diff --git a/recipe/thirdpartyemailpassword/tpepmodels/apiInterface.go b/recipe/thirdpartyemailpassword/tpepmodels/apiInterface.go deleted file mode 100644 index d2f7a758..00000000 --- a/recipe/thirdpartyemailpassword/tpepmodels/apiInterface.go +++ /dev/null @@ -1,80 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package tpepmodels - -import ( - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -type APIInterface struct { - AuthorisationUrlGET *func(provider *tpmodels.TypeProvider, redirectURIOnProviderDashboard string, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpmodels.AuthorisationUrlGETResponse, error) - AppleRedirectHandlerPOST *func(formPostInfoFromProvider map[string]interface{}, options tpmodels.APIOptions, userContext supertokens.UserContext) error - ThirdPartySignInUpPOST *func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (ThirdPartySignInUpPOSTResponse, error) - - EmailPasswordEmailExistsGET *func(email string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.EmailExistsGETResponse, error) - GeneratePasswordResetTokenPOST *func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.GeneratePasswordResetTokenPOSTResponse, error) - PasswordResetPOST *func(formFields []epmodels.TypeFormField, token string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.ResetPasswordPOSTResponse, error) - EmailPasswordSignInPOST *func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (SignInPOSTResponse, error) - EmailPasswordSignUpPOST *func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (SignUpPOSTResponse, error) -} - -type SignUpPOSTResponse struct { - OK *struct { - User User - Session sessmodels.SessionContainer - } - EmailAlreadyExistsError *struct{} - GeneralError *supertokens.GeneralErrorResponse -} - -type SignInPOSTResponse struct { - OK *struct { - User User - Session sessmodels.SessionContainer - } - WrongCredentialsError *struct{} - GeneralError *supertokens.GeneralErrorResponse -} - -type EmailpasswordInput struct { - IsSignIn bool - FormFields []epmodels.TypeFormField - Options epmodels.APIOptions -} - -type EmailpasswordOutput struct { - OK *struct { - User User - CreatedNewUser bool - } - EmailAlreadyExistsError *struct{} - WrongCredentialsError *struct{} -} - -type ThirdPartySignInUpPOSTResponse struct { - OK *struct { - CreatedNewUser bool - User User - Session sessmodels.SessionContainer - OAuthTokens tpmodels.TypeOAuthTokens - RawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider - } - NoEmailGivenByProviderError *struct{} - GeneralError *supertokens.GeneralErrorResponse -} diff --git a/recipe/thirdpartyemailpassword/tpepmodels/models.go b/recipe/thirdpartyemailpassword/tpepmodels/models.go deleted file mode 100644 index 369b4631..00000000 --- a/recipe/thirdpartyemailpassword/tpepmodels/models.go +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package tpepmodels - -import ( - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" -) - -type User struct { - ID string `json:"id"` - TimeJoined uint64 `json:"timeJoined"` - Email string `json:"email"` - ThirdParty *struct { - ID string `json:"id"` - UserID string `json:"userId"` - } `json:"thirdParty"` - TenantIds []string `json:"tenantIds"` -} - -type TypeContext struct { - FormFields []epmodels.TypeFormField - ThirdPartyAuthCodeResponse interface{} -} - -type TypeInput struct { - SignUpFeature *epmodels.TypeInputSignUp - Providers []tpmodels.ProviderInput - Override *OverrideStruct - EmailDelivery *emaildelivery.TypeInput -} - -type TypeNormalisedInput struct { - SignUpFeature *epmodels.TypeInputSignUp - Providers []tpmodels.ProviderInput - Override OverrideStruct - GetEmailDeliveryConfig func(recipeImpl RecipeInterface, epRecipeImpl epmodels.RecipeInterface) emaildelivery.TypeInputWithService -} - -type OverrideStruct struct { - Functions func(originalImplementation RecipeInterface) RecipeInterface - APIs func(originalImplementation APIInterface) APIInterface -} - -type EmailStruct struct { - ID string `json:"id"` - IsVerified bool `json:"isVerified"` -} diff --git a/recipe/thirdpartyemailpassword/tpepmodels/recipeInterface.go b/recipe/thirdpartyemailpassword/tpepmodels/recipeInterface.go deleted file mode 100644 index c99f7e00..00000000 --- a/recipe/thirdpartyemailpassword/tpepmodels/recipeInterface.go +++ /dev/null @@ -1,68 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package tpepmodels - -import ( - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -type RecipeInterface struct { - GetUserByID *func(userID string, userContext supertokens.UserContext) (*User, error) - GetUsersByEmail *func(email string, tenantId string, userContext supertokens.UserContext) ([]User, error) - GetUserByThirdPartyInfo *func(thirdPartyID string, thirdPartyUserID string, tenantId string, userContext supertokens.UserContext) (*User, error) - - ThirdPartySignInUp *func(thirdPartyID string, thirdPartyUserID string, email string, oAuthTokens tpmodels.TypeOAuthTokens, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (SignInUpResponse, error) - ThirdPartyManuallyCreateOrUpdateUser *func(thirdPartyID string, thirdPartyUserID string, email string, tenantId string, userContext supertokens.UserContext) (ManuallyCreateOrUpdateUserResponse, error) - ThirdPartyGetProvider *func(thirdPartyID string, clientType *string, tenantId string, userContext supertokens.UserContext) (*tpmodels.TypeProvider, error) - - EmailPasswordSignUp *func(email string, password string, tenantId string, userContext supertokens.UserContext) (SignUpResponse, error) - EmailPasswordSignIn *func(email string, password string, tenantId string, userContext supertokens.UserContext) (SignInResponse, error) - CreateResetPasswordToken *func(userID string, tenantId string, userContext supertokens.UserContext) (epmodels.CreateResetPasswordTokenResponse, error) - ResetPasswordUsingToken *func(token string, newPassword string, tenantId string, userContext supertokens.UserContext) (epmodels.ResetPasswordUsingTokenResponse, error) - UpdateEmailOrPassword *func(userId string, email *string, password *string, applyPasswordPolicy *bool, tenantIdForPasswordPolicy string, userContext supertokens.UserContext) (epmodels.UpdateEmailOrPasswordResponse, error) -} - -type SignInUpResponse struct { - OK *struct { - CreatedNewUser bool - User User - OAuthTokens map[string]interface{} - RawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider - } -} - -type ManuallyCreateOrUpdateUserResponse struct { - OK *struct { - CreatedNewUser bool - User User - } -} - -type SignUpResponse struct { - OK *struct { - User User - } - EmailAlreadyExistsError *struct{} -} - -type SignInResponse struct { - OK *struct { - User User - } - WrongCredentialsError *struct{} -} diff --git a/recipe/thirdpartyemailpassword/utils.go b/recipe/thirdpartyemailpassword/utils.go deleted file mode 100644 index 0f351079..00000000 --- a/recipe/thirdpartyemailpassword/utils.go +++ /dev/null @@ -1,79 +0,0 @@ -/* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. - * - * This software is licensed under the Apache License, Version 2.0 (the - * "License") as published by the Apache Software Foundation. - * - * You may not use this file except in compliance with the License. You may - * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package thirdpartyemailpassword - -import ( - "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" - "github.com/supertokens/supertokens-golang/recipe/emailpassword" - "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/emaildelivery/backwardCompatibilityService" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" - "github.com/supertokens/supertokens-golang/supertokens" -) - -func validateAndNormaliseUserInput(recipeInstance *Recipe, appInfo supertokens.NormalisedAppinfo, config *tpepmodels.TypeInput) (tpepmodels.TypeNormalisedInput, error) { - typeNormalisedInput := makeTypeNormalisedInput(recipeInstance) - - if config != nil && config.SignUpFeature != nil { - typeNormalisedInput.SignUpFeature = config.SignUpFeature - } - - if config != nil && config.Providers != nil { - typeNormalisedInput.Providers = config.Providers - } - - typeNormalisedInput.GetEmailDeliveryConfig = func(recipeImpl tpepmodels.RecipeInterface, epRecipeImpl epmodels.RecipeInterface) emaildelivery.TypeInputWithService { - sendPasswordResetEmail := emailpassword.DefaultCreateAndSendCustomPasswordResetEmail(appInfo) - emailService := backwardCompatibilityService.MakeBackwardCompatibilityService(recipeImpl, epRecipeImpl, appInfo, sendPasswordResetEmail) - if config != nil && config.EmailDelivery != nil && config.EmailDelivery.Service != nil { - emailService = *config.EmailDelivery.Service - } - result := emaildelivery.TypeInputWithService{ - Service: emailService, - } - if config != nil && config.EmailDelivery != nil && config.EmailDelivery.Override != nil { - result.Override = config.EmailDelivery.Override - } - - return result - } - - if config != nil && config.Override != nil { - if config.Override.Functions != nil { - typeNormalisedInput.Override.Functions = config.Override.Functions - } - if config.Override.APIs != nil { - typeNormalisedInput.Override.APIs = config.Override.APIs - } - } - - return typeNormalisedInput, nil -} - -func makeTypeNormalisedInput(recipeInstance *Recipe) tpepmodels.TypeNormalisedInput { - return tpepmodels.TypeNormalisedInput{ - SignUpFeature: nil, - Providers: nil, - Override: tpepmodels.OverrideStruct{ - Functions: func(originalImplementation tpepmodels.RecipeInterface) tpepmodels.RecipeInterface { - return originalImplementation - }, - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - return originalImplementation - }, - }, - } -} diff --git a/test/auth-react-server/main.go b/test/auth-react-server/main.go index 7f79e2e8..ef4418bc 100644 --- a/test/auth-react-server/main.go +++ b/test/auth-react-server/main.go @@ -44,8 +44,6 @@ import ( "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" "github.com/supertokens/supertokens-golang/recipe/thirdparty" "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword" - "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless/tplmodels" "github.com/supertokens/supertokens-golang/recipe/userroles" @@ -94,7 +92,6 @@ func callSTInit(passwordlessConfig *plessmodels.TypeInput) { passwordless.ResetForTest() session.ResetForTest() thirdparty.ResetForTest() - thirdpartyemailpassword.ResetForTest() thirdpartypasswordless.ResetForTest() userroles.ResetForTest() multitenancy.ResetForTest() @@ -332,134 +329,134 @@ func callSTInit(passwordlessConfig *plessmodels.TypeInput) { }, }, }), - thirdpartyemailpassword.Init(&tpepmodels.TypeInput{ - EmailDelivery: &emaildelivery.TypeInput{ - Service: &emaildelivery.EmailDeliveryInterface{ - SendEmail: &sendPasswordResetEmail, - }, - }, - Override: &tpepmodels.OverrideStruct{ - APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { - ogPasswordResetPOST := *originalImplementation.PasswordResetPOST - ogGeneratePasswordResetTokenPOST := *originalImplementation.GeneratePasswordResetTokenPOST - ogEmailExistsGET := *originalImplementation.EmailPasswordEmailExistsGET - ogSignUpPOST := *originalImplementation.EmailPasswordSignUpPOST - ogSignInPOST := *originalImplementation.EmailPasswordSignInPOST - ogAuthorisationUrlGET := *originalImplementation.AuthorisationUrlGET - ogSignInUpPOST := *originalImplementation.ThirdPartySignInUpPOST - - (*originalImplementation.AuthorisationUrlGET) = func(provider *tpmodels.TypeProvider, redirectURIOnProviderDashboard string, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpmodels.AuthorisationUrlGETResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API authorisation url get", true) - if gr != nil { - return tpmodels.AuthorisationUrlGETResponse{ - GeneralError: gr, - }, nil - } - return ogAuthorisationUrlGET(provider, redirectURIOnProviderDashboard, tenantId, options, userContext) - } - - (*originalImplementation.ThirdPartySignInUpPOST) = func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.ThirdPartySignInUpPOSTResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API sign in up", false) - if gr != nil { - return tpepmodels.ThirdPartySignInUpPOSTResponse{ - GeneralError: gr, - }, nil - } - return ogSignInUpPOST(provider, input, tenantId, options, userContext) - } - - (*originalImplementation.PasswordResetPOST) = func(formFields []epmodels.TypeFormField, token string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.ResetPasswordPOSTResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API reset password consume", false) - if gr != nil { - return epmodels.ResetPasswordPOSTResponse{ - GeneralError: gr, - }, nil - } - return ogPasswordResetPOST(formFields, token, tenantId, options, userContext) - } - - (*originalImplementation.GeneratePasswordResetTokenPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.GeneratePasswordResetTokenPOSTResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API reset password", false) - if gr != nil { - return epmodels.GeneratePasswordResetTokenPOSTResponse{ - GeneralError: gr, - }, nil - } - return ogGeneratePasswordResetTokenPOST(formFields, tenantId, options, userContext) - } - - (*originalImplementation.EmailPasswordEmailExistsGET) = func(email string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.EmailExistsGETResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API email exists", true) - if gr != nil { - return epmodels.EmailExistsGETResponse{ - GeneralError: gr, - }, nil - } - return ogEmailExistsGET(email, tenantId, options, userContext) - } - - (*originalImplementation.EmailPasswordSignUpPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.SignUpPOSTResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API sign up", false) - if gr != nil { - return tpepmodels.SignUpPOSTResponse{ - GeneralError: gr, - }, nil - } - return ogSignUpPOST(formFields, tenantId, options, userContext) - } - - (*originalImplementation.EmailPasswordSignInPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.SignInPOSTResponse, error) { - gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API sign in", false) - if gr != nil { - return tpepmodels.SignInPOSTResponse{ - GeneralError: gr, - }, nil - } - return ogSignInPOST(formFields, tenantId, options, userContext) - } - return originalImplementation - }, - }, - SignUpFeature: &epmodels.TypeInputSignUp{ - FormFields: formFields, - }, - Providers: []tpmodels.ProviderInput{ - { - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "google", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: os.Getenv("GOOGLE_CLIENT_ID"), - ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"), - }, - }, - }, - }, - { - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "github", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: os.Getenv("GITHUB_CLIENT_ID"), - ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"), - }, - }, - }, - }, - { - Config: tpmodels.ProviderConfig{ - ThirdPartyId: "facebook", - Clients: []tpmodels.ProviderClientConfig{ - { - ClientID: os.Getenv("FACEBOOK_CLIENT_ID"), - ClientSecret: os.Getenv("FACEBOOK_CLIENT_SECRET"), - }, - }, - }, - }, - customAuth0Provider(), - }, - }), + // thirdpartyemailpassword.Init(&tpepmodels.TypeInput{ + // EmailDelivery: &emaildelivery.TypeInput{ + // Service: &emaildelivery.EmailDeliveryInterface{ + // SendEmail: &sendPasswordResetEmail, + // }, + // }, + // Override: &tpepmodels.OverrideStruct{ + // APIs: func(originalImplementation tpepmodels.APIInterface) tpepmodels.APIInterface { + // ogPasswordResetPOST := *originalImplementation.PasswordResetPOST + // ogGeneratePasswordResetTokenPOST := *originalImplementation.GeneratePasswordResetTokenPOST + // ogEmailExistsGET := *originalImplementation.EmailPasswordEmailExistsGET + // ogSignUpPOST := *originalImplementation.EmailPasswordSignUpPOST + // ogSignInPOST := *originalImplementation.EmailPasswordSignInPOST + // ogAuthorisationUrlGET := *originalImplementation.AuthorisationUrlGET + // ogSignInUpPOST := *originalImplementation.ThirdPartySignInUpPOST + + // (*originalImplementation.AuthorisationUrlGET) = func(provider *tpmodels.TypeProvider, redirectURIOnProviderDashboard string, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpmodels.AuthorisationUrlGETResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API authorisation url get", true) + // if gr != nil { + // return tpmodels.AuthorisationUrlGETResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogAuthorisationUrlGET(provider, redirectURIOnProviderDashboard, tenantId, options, userContext) + // } + + // (*originalImplementation.ThirdPartySignInUpPOST) = func(provider *tpmodels.TypeProvider, input tpmodels.TypeSignInUpInput, tenantId string, options tpmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.ThirdPartySignInUpPOSTResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API sign in up", false) + // if gr != nil { + // return tpepmodels.ThirdPartySignInUpPOSTResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogSignInUpPOST(provider, input, tenantId, options, userContext) + // } + + // (*originalImplementation.PasswordResetPOST) = func(formFields []epmodels.TypeFormField, token string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.ResetPasswordPOSTResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API reset password consume", false) + // if gr != nil { + // return epmodels.ResetPasswordPOSTResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogPasswordResetPOST(formFields, token, tenantId, options, userContext) + // } + + // (*originalImplementation.GeneratePasswordResetTokenPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.GeneratePasswordResetTokenPOSTResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API reset password", false) + // if gr != nil { + // return epmodels.GeneratePasswordResetTokenPOSTResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogGeneratePasswordResetTokenPOST(formFields, tenantId, options, userContext) + // } + + // (*originalImplementation.EmailPasswordEmailExistsGET) = func(email string, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (epmodels.EmailExistsGETResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API email exists", true) + // if gr != nil { + // return epmodels.EmailExistsGETResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogEmailExistsGET(email, tenantId, options, userContext) + // } + + // (*originalImplementation.EmailPasswordSignUpPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.SignUpPOSTResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API sign up", false) + // if gr != nil { + // return tpepmodels.SignUpPOSTResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogSignUpPOST(formFields, tenantId, options, userContext) + // } + + // (*originalImplementation.EmailPasswordSignInPOST) = func(formFields []epmodels.TypeFormField, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) (tpepmodels.SignInPOSTResponse, error) { + // gr := returnGeneralErrorIfNeeded(*options.Req, "general error from API sign in", false) + // if gr != nil { + // return tpepmodels.SignInPOSTResponse{ + // GeneralError: gr, + // }, nil + // } + // return ogSignInPOST(formFields, tenantId, options, userContext) + // } + // return originalImplementation + // }, + // }, + // SignUpFeature: &epmodels.TypeInputSignUp{ + // FormFields: formFields, + // }, + // Providers: []tpmodels.ProviderInput{ + // { + // Config: tpmodels.ProviderConfig{ + // ThirdPartyId: "google", + // Clients: []tpmodels.ProviderClientConfig{ + // { + // ClientID: os.Getenv("GOOGLE_CLIENT_ID"), + // ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"), + // }, + // }, + // }, + // }, + // { + // Config: tpmodels.ProviderConfig{ + // ThirdPartyId: "github", + // Clients: []tpmodels.ProviderClientConfig{ + // { + // ClientID: os.Getenv("GITHUB_CLIENT_ID"), + // ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"), + // }, + // }, + // }, + // }, + // { + // Config: tpmodels.ProviderConfig{ + // ThirdPartyId: "facebook", + // Clients: []tpmodels.ProviderClientConfig{ + // { + // ClientID: os.Getenv("FACEBOOK_CLIENT_ID"), + // ClientSecret: os.Getenv("FACEBOOK_CLIENT_SECRET"), + // }, + // }, + // }, + // }, + // customAuth0Provider(), + // }, + // }), session.Init(&sessmodels.TypeInput{ Override: &sessmodels.OverrideStruct{ APIs: func(originalImplementation sessmodels.APIInterface) sessmodels.APIInterface {