├── examples ├── .gitignore ├── playground │ ├── main.go │ └── README.md ├── with-gin │ ├── .gitignore │ ├── README.md │ └── main.go ├── with-fiber │ └── README.MD ├── with-chi │ └── README.md ├── with-mux │ └── README.md ├── with-go-zero │ └── README.md ├── with-labstack-echo │ └── README.md ├── with-http │ └── README.md ├── with-chi-oso │ ├── models │ │ └── models.go │ ├── README.md │ ├── main.polar │ ├── auth.go │ └── database │ │ └── database.go ├── go.mod └── with-twirp │ ├── cmd │ ├── server │ │ └── README.md │ └── client │ │ └── main.go │ ├── haberdasher │ ├── haberdasher.proto │ └── gen.go │ ├── internal │ ├── interceptor │ │ └── errorHandler.go │ ├── hooks │ │ └── logging.go │ └── haberdasherserver │ │ └── random.go │ └── README.md ├── test ├── auth-react-server │ ├── .gitignore │ ├── README.md │ └── .env.example ├── frontendIntegration │ └── README.md ├── test-server │ ├── setup-for-test.sh │ ├── testFunctionMapper.go │ ├── go.mod │ ├── additional-files │ │ └── new_session_for_test_server.go │ └── utils.go └── docker │ └── Dockerfile ├── .github ├── helpers │ ├── .gitignore │ └── package.json ├── workflows │ ├── lint-pr-title.yml │ ├── github-actions-changelog.yml │ ├── pre-commit-hook-run.yml │ ├── enforce-go-mod-tidy.yml │ └── tests-pass-check-pr.yml └── PULL_REQUEST_TEMPLATE.md ├── supertokens ├── alwaysInitialisedRecipes.go ├── postInitCallbacks.go ├── errors.go ├── logger.go ├── constants.go ├── utils_test.go └── humanise_test.go ├── recipe ├── multitenancy │ ├── constants.go │ ├── multitenancyclaims │ │ └── claims.go │ ├── mterrors │ │ └── errors.go │ ├── testingUtils.go │ ├── api │ │ └── loginMethods.go │ ├── allowedDomainsClaim.go │ ├── multitenancymodels │ │ └── models.go │ └── utils.go ├── thirdparty │ ├── provider_config_test.go │ ├── tperrors │ │ └── errors.go │ ├── constants.go │ ├── api │ │ └── appleRedirect.go │ ├── providers │ │ ├── boxysaml.go │ │ ├── googleWorkspaces.go │ │ └── google.go │ └── tpmodels │ │ └── recipeInterface.go ├── dashboard │ ├── errors │ │ └── errors.go │ ├── api │ │ ├── usersCountGet.go │ │ ├── validateKey.go │ │ ├── signOutPost.go │ │ ├── dashboard.go │ │ ├── userdetails │ │ │ ├── userDelete.go │ │ │ ├── userMetaDataGet.go │ │ │ ├── userSessionsPost.go │ │ │ └── userEmailVerifyGet.go │ │ ├── search │ │ │ └── tagsGet.go │ │ ├── tenantsListGet.go │ │ └── signInPost.go │ ├── validationUtils │ │ └── main.go │ ├── main.go │ ├── apiKeyProtector.go │ ├── dashboardmodels │ │ ├── recipeInterface.go │ │ ├── apiInterface.go │ │ └── models.go │ ├── constants │ │ └── constants.go │ └── testingUtils.go ├── userroles │ ├── userrolesclaims │ │ └── claims.go │ ├── userrolesmodels │ │ ├── apiInterface.go │ │ └── models.go │ ├── config_test.go │ └── testingUtils.go ├── emailverification │ ├── evclaims │ │ └── claims.go │ ├── api │ │ └── utils.go │ ├── constants.go │ ├── testingUtils.go │ ├── emaildelivery │ │ ├── smtpService │ │ │ ├── serviceImplementation.go │ │ │ └── main.go │ │ └── backwardCompatibilityService │ │ │ └── main.go │ └── evmodels │ │ └── recipeInterface.go ├── session │ ├── sessmodels │ │ ├── claims.go │ │ └── apiInterface.go │ ├── claims │ │ ├── utils.go │ │ ├── booleanClaim.go │ │ └── booleanClaim_test.go │ ├── utils_test.go │ ├── refresh.go │ ├── constants.go │ ├── testingUtils.go │ ├── jwksMemory_test.go │ └── middleware.go ├── passwordless │ ├── api │ │ ├── utils.go │ │ ├── doesEmailExist.go │ │ └── doesPhoneNumberExist.go │ ├── constants.go │ ├── smsdelivery │ │ ├── twilioService │ │ │ ├── serviceImplementation.go │ │ │ └── main.go │ │ └── backwardCompatibilityService │ │ │ └── main.go │ ├── emaildelivery │ │ ├── smtpService │ │ │ ├── main.go │ │ │ └── serviceImplementation.go │ │ └── backwardCompatibilityService │ │ │ └── main.go │ └── testingUtils.go ├── jwt │ ├── constants.go │ ├── testingUtils.go │ ├── jwtmodels │ │ ├── models.go │ │ ├── recipeInterface.go │ │ └── apiInterface.go │ ├── api │ │ ├── implementation.go │ │ └── getJWKS.go │ ├── main.go │ ├── createJWTFeature_test.go │ └── utils.go ├── usermetadata │ ├── usermetadatamodels │ │ ├── apiInterface.go │ │ ├── models.go │ │ └── recipeInterface.go │ ├── testingUtils.go │ └── utils.go ├── openid │ ├── constants.go │ ├── testingUtils.go │ ├── openidmodels │ │ ├── models.go │ │ ├── recipeInterface.go │ │ └── apiInterface.go │ └── api │ │ ├── implementation.go │ │ └── getOpenIdDiscoveryConfiguration.go └── emailpassword │ ├── middleware_test.go │ ├── errors │ └── errors.go │ ├── constants │ └── constants.go │ ├── loginmethods_test.go │ ├── emaildelivery │ └── smtpService │ │ ├── serviceImplementation.go │ │ └── main.go │ ├── testingUtils.go │ └── api │ └── emailExists.go ├── coreDriverInterfaceSupported.json ├── frontendDriverInterfaceSupported.json ├── .gitignore ├── .circleci ├── generateConfig.sh ├── config.yml ├── doUnitTests.sh ├── doBackendSDKTests.sh ├── markAsSuccess.sh └── markDevTagAsTestNotPassed.sh ├── README.md ├── go.mod ├── .devcontainer ├── devcontainer.json └── Dockerfile ├── ingredients ├── emaildelivery │ ├── smtpmodels.go │ ├── models.go │ └── main.go └── smsdelivery │ ├── models.go │ ├── main.go │ └── twiliomodels.go └── addDevTag /examples/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /test/auth-react-server/.gitignore: -------------------------------------------------------------------------------- 1 | .env -------------------------------------------------------------------------------- /.github/helpers/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | package-lock.json -------------------------------------------------------------------------------- /examples/playground/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /test/auth-react-server/README.md: -------------------------------------------------------------------------------- 1 | # This is a test server for tests in the supertokens-auth-react repo -------------------------------------------------------------------------------- /test/frontendIntegration/README.md: -------------------------------------------------------------------------------- 1 | # This is a test server for tests in the supertokens-website repo -------------------------------------------------------------------------------- /supertokens/alwaysInitialisedRecipes.go: -------------------------------------------------------------------------------- 1 | package supertokens 2 | 3 | var DefaultMultitenancyRecipe Recipe 4 | -------------------------------------------------------------------------------- /examples/playground/README.md: -------------------------------------------------------------------------------- 1 | The `main.go` in this folder is used as a playground to write / test random code snippets. -------------------------------------------------------------------------------- /recipe/multitenancy/constants.go: -------------------------------------------------------------------------------- 1 | package multitenancy 2 | 3 | const ( 4 | LoginMethodsAPI = "/loginmethods" 5 | ) 6 | -------------------------------------------------------------------------------- /examples/with-gin/.gitignore: -------------------------------------------------------------------------------- 1 | config/prod.yaml 2 | config/dev.yaml 3 | config/stage.yaml 4 | .DS_Store 5 | build/* 6 | log.txt 7 | -------------------------------------------------------------------------------- /test/test-server/setup-for-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cp ./additional-files/new_session_for_test_server.go ../../recipe/session/ 4 | -------------------------------------------------------------------------------- /recipe/thirdparty/provider_config_test.go: -------------------------------------------------------------------------------- 1 | package thirdparty 2 | 3 | import "testing" 4 | 5 | func TestBuiltinProviderComputedConfig(t *testing.T) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /examples/with-fiber/README.MD: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Fiber](https://gofiber.io/) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /examples/with-chi/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Go-Chi](https://github.com/go-chi/chi) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /examples/with-gin/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Gin-Gonic](https://github.com/gin-gonic/gin) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /examples/with-mux/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Gorilla Mux](https://github.com/gorilla/mux) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /examples/with-go-zero/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [go-zero](https://github.com/zeromicro/go-zero) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /coreDriverInterfaceSupported.json: -------------------------------------------------------------------------------- 1 | { 2 | "_comment": "contains a list of core-driver interfaces branch names that this core supports", 3 | "versions": [ 4 | "3.1" 5 | ] 6 | } -------------------------------------------------------------------------------- /recipe/dashboard/errors/errors.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | type ForbiddenAccessError struct { 4 | Msg string 5 | } 6 | 7 | func (err ForbiddenAccessError) Error() string { 8 | return err.Msg 9 | } 10 | -------------------------------------------------------------------------------- /examples/with-labstack-echo/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Labstack Echo](https://github.com/labstack/echo) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /examples/with-http/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [net/http](https://github.com/golang/go/tree/master/src/net/http) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run main.go 6 | ``` -------------------------------------------------------------------------------- /recipe/thirdparty/tperrors/errors.go: -------------------------------------------------------------------------------- 1 | package tperrors 2 | 3 | type ClientTypeNotFoundError struct { 4 | Msg string 5 | } 6 | 7 | func (e ClientTypeNotFoundError) Error() string { 8 | return e.Msg 9 | } 10 | -------------------------------------------------------------------------------- /frontendDriverInterfaceSupported.json: -------------------------------------------------------------------------------- 1 | { 2 | "_comment": "contains a list of frontend-driver interfaces branch names that this core supports", 3 | "versions": [ 4 | "1.17", 5 | "2.0" 6 | ] 7 | } -------------------------------------------------------------------------------- /recipe/multitenancy/multitenancyclaims/claims.go: -------------------------------------------------------------------------------- 1 | package multitenancyclaims 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/session/claims" 5 | ) 6 | 7 | var AllowedDomainsClaim *claims.TypeSessionClaim 8 | var AllowedDomainsClaimValidators claims.PrimitiveArrayClaimValidators 9 | -------------------------------------------------------------------------------- /test/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rishabhpoddar/supertokens_website_sdk_testing 2 | RUN cd /tmp 3 | RUN wget https://dl.google.com/go/go1.17.linux-amd64.tar.gz 4 | RUN tar -xvf go1.17.linux-amd64.tar.gz 5 | RUN mv go /usr/local 6 | env GOROOT /usr/local/go 7 | env GOPATH $HOME/go 8 | env PATH $GOPATH/bin:$GOROOT/bin:$PATH -------------------------------------------------------------------------------- /test/auth-react-server/.env.example: -------------------------------------------------------------------------------- 1 | # Github 2 | GITHUB_CLIENT_ID= 3 | GITHUB_CLIENT_SECRET= 4 | 5 | # Google 6 | GOOGLE_CLIENT_ID= 7 | GOOGLE_CLIENT_SECRET= 8 | 9 | # Facebook 10 | FACEBOOK_CLIENT_ID= 11 | FACEBOOK_CLIENT_SECRET= 12 | 13 | # Auth0 14 | AUTH0_CLIENT_ID= 15 | AUTH0_CLIENT_SECRET= 16 | AUTH0_DOMAIN = -------------------------------------------------------------------------------- /examples/with-chi-oso/models/models.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | type Repository struct { 4 | Id int 5 | Name string 6 | IsPublic bool 7 | } 8 | 9 | type RepositoryRole struct { 10 | Role string 11 | RepoId int 12 | } 13 | 14 | type User struct { 15 | Roles []RepositoryRole 16 | Email string 17 | } 18 | -------------------------------------------------------------------------------- /examples/with-chi-oso/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Oso](https://github.com/osohq/go-oso) with SuperTokens (based on [Go-Chi](https://github.com/go-chi/chi)). 2 | 3 | The file `database\database.go` contains the pre-configured e-mails with different access rights from the osohq quickstarter. 4 | 5 | To start this server, run: 6 | ``` 7 | go run main.go 8 | ``` -------------------------------------------------------------------------------- /examples/with-gin/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/examples/with-gin/config" 5 | "github.com/supertokens/supertokens-golang/examples/with-gin/server" 6 | ) 7 | 8 | func main() { 9 | // supertokens init here 10 | config.Init() 11 | 12 | // adding of superotkens middleware, cors and APIs 13 | server.Init() 14 | } 15 | -------------------------------------------------------------------------------- /recipe/multitenancy/mterrors/errors.go: -------------------------------------------------------------------------------- 1 | package mterrors 2 | 3 | type TenantDoesNotExistError struct { 4 | Msg string 5 | } 6 | 7 | func (err TenantDoesNotExistError) Error() string { 8 | return err.Msg 9 | } 10 | 11 | type RecipeDisabledForTenantError struct { 12 | Msg string 13 | } 14 | 15 | func (err RecipeDisabledForTenantError) Error() string { 16 | return err.Msg 17 | } 18 | -------------------------------------------------------------------------------- /recipe/userroles/userrolesclaims/claims.go: -------------------------------------------------------------------------------- 1 | package userrolesclaims 2 | 3 | import "github.com/supertokens/supertokens-golang/recipe/session/claims" 4 | 5 | var UserRoleClaim *claims.TypeSessionClaim 6 | var UserRoleClaimValidators claims.PrimitiveArrayClaimValidators 7 | 8 | var PermissionClaim *claims.TypeSessionClaim 9 | var PermissionClaimValidators claims.PrimitiveArrayClaimValidators 10 | -------------------------------------------------------------------------------- /.github/helpers/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "helpers", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.26.1", 14 | "github-workflow-helpers": "github:supertokens/github-workflow-helpers" 15 | } 16 | } -------------------------------------------------------------------------------- /recipe/emailverification/evclaims/claims.go: -------------------------------------------------------------------------------- 1 | package evclaims 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/session/claims" 5 | ) 6 | 7 | type TypeEmailVerificationClaimValidators struct { 8 | claims.BooleanClaimValidators 9 | IsVerified func(refetchTimeOnFalseInSeconds *int64, maxAgeInSeconds *int64) claims.SessionClaimValidator 10 | } 11 | 12 | var EmailVerificationClaim *claims.TypeSessionClaim 13 | 14 | var EmailVerificationClaimValidators TypeEmailVerificationClaimValidators 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | vendor/ 16 | 17 | gin/ 18 | 19 | .DS_Store 20 | 21 | apiPassword 22 | releasePassword 23 | .vscode/ 24 | .idea/ 25 | /test_report 26 | 27 | build-errors.log 28 | main 29 | 30 | recipe/**/*_for_test_server.go 31 | -------------------------------------------------------------------------------- /supertokens/postInitCallbacks.go: -------------------------------------------------------------------------------- 1 | package supertokens 2 | 3 | var postInitCallbacks = []func() error{} 4 | 5 | func AddPostInitCallback(cb func() error) { 6 | postInitCallbacks = append(postInitCallbacks, cb) 7 | } 8 | 9 | func runPostInitCallbacks() error { 10 | for _, cb := range postInitCallbacks { 11 | err := cb() 12 | if err != nil { 13 | return err 14 | } 15 | } 16 | postInitCallbacks = []func() error{} 17 | return nil 18 | } 19 | 20 | func resetPostInitCallbackForTest() { 21 | postInitCallbacks = []func() error{} 22 | } 23 | -------------------------------------------------------------------------------- /.github/workflows/lint-pr-title.yml: -------------------------------------------------------------------------------- 1 | name: "Lint PR Title" 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - reopened 8 | - edited 9 | - synchronize 10 | 11 | jobs: 12 | pr-title: 13 | name: Lint PR title 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: amannn/action-semantic-pull-request@v3 17 | env: 18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 19 | with: 20 | validateSingleCommit: true -------------------------------------------------------------------------------- /.github/workflows/github-actions-changelog.yml: -------------------------------------------------------------------------------- 1 | name: "Enforcing changelog in PRs Workflow" 2 | on: 3 | pull_request: 4 | types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled] 5 | 6 | jobs: 7 | # Enforces the update of a changelog file on every pull request 8 | changelog: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: dangoslen/changelog-enforcer@v2 13 | with: 14 | changeLogPath: "CHANGELOG.md" 15 | skipLabels: "Skip-Changelog" 16 | -------------------------------------------------------------------------------- /examples/with-chi-oso/main.polar: -------------------------------------------------------------------------------- 1 | allow(actor, action, resource) if 2 | has_permission(actor, action, resource); 3 | 4 | actor User {} 5 | 6 | resource Repository { 7 | permissions = ["read", "push", "delete"]; 8 | roles = ["contributor", "maintainer", "admin"]; 9 | 10 | "read" if "contributor"; 11 | "push" if "maintainer"; 12 | "delete" if "admin"; 13 | 14 | "maintainer" if "admin"; 15 | "contributor" if "maintainer"; 16 | } 17 | 18 | has_role(user: User, roleName: String, repository: Repository) if 19 | role in user.Roles and 20 | role.Role = roleName and 21 | role.RepoId = repository.Id; -------------------------------------------------------------------------------- /recipe/session/sessmodels/claims.go: -------------------------------------------------------------------------------- 1 | package sessmodels 2 | 3 | import "github.com/supertokens/supertokens-golang/recipe/session/claims" 4 | 5 | type ValidateClaimsResult struct { 6 | InvalidClaims []claims.ClaimValidationError 7 | AccessTokenPayloadUpdate map[string]interface{} 8 | } 9 | 10 | type ValidateClaimsResponse struct { 11 | OK *struct { 12 | InvalidClaims []claims.ClaimValidationError 13 | } 14 | SessionDoesNotExistError *struct{} 15 | } 16 | 17 | type GetClaimValueResult struct { 18 | OK *struct { 19 | Value interface{} 20 | } 21 | SessionDoesNotExistError *struct{} 22 | } 23 | -------------------------------------------------------------------------------- /.circleci/generateConfig.sh: -------------------------------------------------------------------------------- 1 | coreDriverJson=`cat ../coreDriverInterfaceSupported.json` 2 | coreDriverArray=`echo $coreDriverJson | jq ".versions"` 3 | 4 | frontendDriverJson=`cat ../frontendDriverInterfaceSupported.json` 5 | frontendDriverArray=`echo $frontendDriverJson | jq ".versions"` 6 | 7 | if [ -z "$SUPERTOKENS_API_KEY" ]; then 8 | echo "SUPERTOKENS_API_KEY missing" 9 | exit 1; 10 | fi 11 | 12 | sed -i -e 's/cdi-version: placeholder/cdi-version: '`printf "%q" $coreDriverArray`'/' config_continue.yml 13 | sed -i -e 's/fdi-version: placeholder/fdi-version: '`printf "%q" $frontendDriverArray`'/' config_continue.yml 14 | -------------------------------------------------------------------------------- /test/test-server/testFunctionMapper.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "strings" 7 | 8 | "github.com/supertokens/supertokens-golang/supertokens" 9 | ) 10 | 11 | var info = struct { 12 | coreCallCount int 13 | }{} 14 | 15 | func GetFunc(evalStr string) (interface{}, error) { 16 | if strings.HasPrefix(evalStr, "supertokens.init.supertokens.networkInterceptor") { 17 | return func(request *http.Request, userContext supertokens.UserContext) (*http.Request, error) { 18 | info.coreCallCount += 1 19 | return request, nil 20 | }, nil 21 | } 22 | 23 | return nil, fmt.Errorf("Unknown eval string") 24 | } 25 | -------------------------------------------------------------------------------- /recipe/emailverification/api/utils.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | func GetEmailVerifyLink(appInfo supertokens.NormalisedAppinfo, token string, tenantId string, request *http.Request, userContext supertokens.UserContext) (string, error) { 11 | websiteDomain, err := appInfo.GetOrigin(request, userContext) 12 | if err != nil { 13 | return "", err 14 | } 15 | return fmt.Sprintf( 16 | "%s%s/verify-email?token=%s&tenantId=%s", 17 | websiteDomain.GetAsStringDangerous(), 18 | appInfo.WebsiteBasePath.GetAsStringDangerous(), 19 | token, 20 | tenantId, 21 | ), nil 22 | } 23 | -------------------------------------------------------------------------------- /examples/with-chi-oso/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "reflect" 7 | 8 | "github.com/osohq/go-oso" 9 | "github.com/supertokens/supertokens-golang/examples/with-chi-oso/models" 10 | ) 11 | 12 | func NewAuth() oso.Oso { 13 | osoClient, err := oso.NewOso() 14 | if err != nil { 15 | fmt.Sprintf("Failed to set up Oso: %v", err) 16 | os.Exit(1) 17 | } 18 | osoClient.RegisterClass(reflect.TypeOf(models.Repository{}), nil) 19 | osoClient.RegisterClass(reflect.TypeOf(models.User{}), nil) 20 | if err = osoClient.LoadFiles([]string{"main.polar"}); err != nil { 21 | fmt.Sprintf("Failed to start: %s", err) 22 | os.Exit(1) 23 | } 24 | return osoClient 25 | } 26 | -------------------------------------------------------------------------------- /recipe/passwordless/api/utils.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | func GetMagicLink(appInfo supertokens.NormalisedAppinfo, preAuthSessionID string, linkCode string, tenantId string, request *http.Request, userContext supertokens.UserContext) (string, error) { 11 | websiteDomain, err := appInfo.GetOrigin(request, userContext) 12 | if err != nil { 13 | return "", err 14 | } 15 | return fmt.Sprintf( 16 | "%s%s/verify?preAuthSessionId=%s&tenantId=%s#%s", 17 | websiteDomain.GetAsStringDangerous(), 18 | appInfo.WebsiteBasePath.GetAsStringDangerous(), 19 | preAuthSessionID, 20 | tenantId, 21 | linkCode, 22 | ), nil 23 | } 24 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit-hook-run.yml: -------------------------------------------------------------------------------- 1 | name: "Pre commit hook check" 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - reopened 8 | - edited 9 | - synchronize 10 | 11 | jobs: 12 | pr-title: 13 | name: Pre commit hook check 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up go 18 | uses: actions/setup-go@v5 19 | with: 20 | go-version: '1.18' 21 | - run: rm -rf .git && git init && git add --all && git -c user.name='test' -c user.email='test@example.com' commit -m 'init for pr action' 22 | - run: ./hooks/pre-commit.sh 23 | -------------------------------------------------------------------------------- /recipe/dashboard/api/usersCountGet.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 5 | "github.com/supertokens/supertokens-golang/supertokens" 6 | ) 7 | 8 | type usersCountGetResponse struct { 9 | Status string `json:"status"` 10 | Count float64 `json:"count"` 11 | } 12 | 13 | func UsersCountGet(apiImplementation dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (usersCountGetResponse, error) { 14 | count, err := supertokens.GetUserCount(nil, &tenantId) 15 | if err != nil { 16 | return usersCountGetResponse{}, err 17 | } 18 | 19 | return usersCountGetResponse{ 20 | Status: "OK", 21 | Count: count, 22 | }, nil 23 | } 24 | -------------------------------------------------------------------------------- /recipe/session/claims/utils.go: -------------------------------------------------------------------------------- 1 | package claims 2 | 3 | func includes(s []interface{}, e interface{}) bool { 4 | for _, a := range s { 5 | if a == e { 6 | return true 7 | } 8 | } 9 | return false 10 | } 11 | 12 | func includesAll(s []interface{}, e []interface{}) bool { 13 | valsMap := map[interface{}]bool{} 14 | for _, v := range s { 15 | valsMap[v] = true 16 | } 17 | for _, v := range e { 18 | if !valsMap[v] { 19 | return false 20 | } 21 | } 22 | return true 23 | } 24 | 25 | func excludesAll(s []interface{}, e []interface{}) bool { 26 | valsMap := map[interface{}]bool{} 27 | for _, v := range s { 28 | valsMap[v] = true 29 | } 30 | for _, v := range e { 31 | if valsMap[v] { 32 | return false 33 | } 34 | } 35 | return true 36 | } 37 | -------------------------------------------------------------------------------- /examples/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/supertokens/supertokens-golang/examples 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/gin-contrib/cors v1.3.1 7 | github.com/gin-gonic/gin v1.7.4 8 | github.com/go-chi/chi/v5 v5.0.4 9 | github.com/go-chi/cors v1.2.0 10 | github.com/gofiber/fiber/v2 v2.49.2 11 | github.com/gorilla/handlers v1.5.1 12 | github.com/gorilla/mux v1.8.0 13 | github.com/labstack/echo/v4 v4.6.1 14 | github.com/osohq/go-oso v0.21.0 15 | github.com/spf13/viper v1.8.1 16 | github.com/supertokens/supertokens-golang v0.0.0-20210909070424-b13c10ce5994 17 | github.com/twitchtv/twirp v8.1.0+incompatible 18 | github.com/zeromicro/go-zero v1.3.5 19 | google.golang.org/protobuf v1.28.0 20 | ) 21 | 22 | replace github.com/supertokens/supertokens-golang => ../ 23 | -------------------------------------------------------------------------------- /recipe/dashboard/validationUtils/main.go: -------------------------------------------------------------------------------- 1 | package validationUtils 2 | 3 | import ( 4 | "net/http" 5 | "strings" 6 | 7 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 8 | "github.com/supertokens/supertokens-golang/supertokens" 9 | ) 10 | 11 | func ValidateApiKey(req *http.Request, config dashboardmodels.TypeNormalisedInput, userContext ...supertokens.UserContext) (bool, error) { 12 | apiKeyHeaderValue := req.Header.Get("authorization") 13 | 14 | // We receive the api key as `Bearer API_KEY`, this retrieves just the key 15 | keyParts := strings.Split(apiKeyHeaderValue, " ") 16 | apiKeyHeaderValue = keyParts[len(keyParts)-1] 17 | 18 | if apiKeyHeaderValue == "" { 19 | return false, nil 20 | } 21 | 22 | return apiKeyHeaderValue == config.ApiKey, nil 23 | } 24 | -------------------------------------------------------------------------------- /recipe/session/utils_test.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package session 17 | -------------------------------------------------------------------------------- /recipe/dashboard/api/validateKey.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 5 | "github.com/supertokens/supertokens-golang/recipe/dashboard/validationUtils" 6 | "github.com/supertokens/supertokens-golang/supertokens" 7 | ) 8 | 9 | func ValidateKey(apiImplementation dashboardmodels.APIInterface, options dashboardmodels.APIOptions, userContext supertokens.UserContext) error { 10 | isKeyValid, err := validationUtils.ValidateApiKey(options.Req, options.Config, userContext) 11 | 12 | if err != nil { 13 | return err 14 | } 15 | 16 | if isKeyValid { 17 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 18 | "status": "OK", 19 | }) 20 | } else { 21 | return supertokens.SendUnauthorisedAccess(options.Res) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /recipe/jwt/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwt 17 | 18 | const ( 19 | GetJWKSAPI = "/jwt/jwks.json" 20 | ) 21 | -------------------------------------------------------------------------------- /recipe/userroles/userrolesmodels/apiInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userrolesmodels 17 | 18 | type APIInterface struct { 19 | } 20 | -------------------------------------------------------------------------------- /recipe/usermetadata/usermetadatamodels/apiInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package usermetadatamodels 17 | 18 | type APIInterface struct { 19 | } 20 | -------------------------------------------------------------------------------- /recipe/openid/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package openid 17 | 18 | const ( 19 | GetDiscoveryConfigUrl = "/.well-known/openid-configuration" 20 | ) 21 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | # this allows you to use CircleCI's dynamic configuration feature 4 | setup: true 5 | 6 | orbs: 7 | continuation: circleci/continuation@0.1.2 8 | slack: circleci/slack@3.4.2 9 | jq: circleci/jq@2.2.0 10 | jobs: 11 | setup: 12 | machine: 13 | image: ubuntu-2204:2024.04.4 14 | steps: 15 | - checkout 16 | - run: 17 | name: Generate config 18 | command: | 19 | cd .circleci && ./generateConfig.sh 20 | - continuation/continue: 21 | configuration_path: .circleci/config_continue.yml # use newly generated config to continue 22 | 23 | workflows: 24 | version: 2 25 | tagged-build: 26 | jobs: 27 | - setup: 28 | filters: 29 | tags: 30 | only: /dev-v[0-9]+(\.[0-9]+)*/ 31 | branches: 32 | only: /test-cicd\/.*/ 33 | -------------------------------------------------------------------------------- /examples/with-twirp/cmd/server/README.md: -------------------------------------------------------------------------------- 1 | # twirp example server # 2 | 3 | This binary is an example twirp server. It's meant mostly to be read 4 | and to be used in conjunction with the neighboring client binary. 5 | 6 | When a request is made, the server will log the statsd messages it 7 | would have sent, so you'll see stuff like this: 8 | 9 | -> % ./server 10 | incr twirp.total.requests: 1 @ 1.000000 11 | incr twirp.MakeHat.requests: 1 @ 1.000000 12 | incr twirp.total.responses: 1 @ 1.000000 13 | incr twirp.MakeHat.responses: 1 @ 1.000000 14 | incr twirp.status_codes.total.200: 1 @ 1.000000 15 | incr twirp.status_codes.MakeHat.200: 1 @ 1.000000 16 | time twirp.all_methods.response: 370.695µs @ 1.000000 17 | time twirp.MakeHat.response: 370.695µs @ 1.000000 18 | time twirp.status_codes.all_methods.200: 370.695µs @ 1.000000 19 | time twirp.status_codes.MakeHat.200: 370.695µs @ 1.000000 20 | -------------------------------------------------------------------------------- /recipe/emailverification/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package emailverification 17 | 18 | const ( 19 | generateEmailVerifyTokenAPI = "/user/email/verify/token" 20 | emailVerifyAPI = "/user/email/verify" 21 | ) 22 | -------------------------------------------------------------------------------- /recipe/thirdparty/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package thirdparty 17 | 18 | const ( 19 | AuthorisationAPI = "/authorisationurl" 20 | SignInUpAPI = "/signinup" 21 | AppleRedirectHandlerAPI = "/callback/apple" 22 | ) 23 | -------------------------------------------------------------------------------- /examples/with-twirp/haberdasher/haberdasher.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package twitch.twirp.example.haberdasher; 4 | option go_package = "github.com/supertokens/supertokens-golang/examples/with-twirp/haberdasher;haberdasher"; 5 | 6 | // A Hat is a piece of headwear made by a Haberdasher. 7 | message Hat { 8 | // The size of a hat should always be in inches. 9 | int32 size = 1; 10 | 11 | // The color of a hat will never be 'invisible', but other than 12 | // that, anything is fair game. 13 | string color = 2; 14 | 15 | // The name of a hat is it's type. Like, 'bowler', or something. 16 | string name = 3; 17 | } 18 | 19 | // Size is passed when requesting a new hat to be made. It's always measured in 20 | // inches. 21 | message Size { 22 | int32 inches = 1; 23 | } 24 | 25 | // A Haberdasher makes hats for clients. 26 | service Haberdasher { 27 | // MakeHat produces a hat of mysterious, randomly-selected color! 28 | rpc MakeHat(Size) returns (Hat); 29 | } 30 | -------------------------------------------------------------------------------- /recipe/emailpassword/middleware_test.go: -------------------------------------------------------------------------------- 1 | package emailpassword 2 | 3 | import ( 4 | "io/ioutil" 5 | "net/http" 6 | "net/http/httptest" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/supertokens/supertokens-golang/supertokens" 11 | ) 12 | 13 | func TestAPIWithSupertokensMiddlewareButNotInitialized(t *testing.T) { 14 | BeforeEach() 15 | defer AfterEach() 16 | 17 | mux := http.NewServeMux() 18 | testServer := httptest.NewServer(supertokens.Middleware(mux)) 19 | defer testServer.Close() 20 | 21 | resp, err := http.Post(testServer.URL+"/auth/signup", "application/json", nil) 22 | if err != nil { 23 | t.Error(err.Error()) 24 | } 25 | 26 | assert.Equal(t, 500, resp.StatusCode) 27 | defer resp.Body.Close() 28 | bodyBytes, err := ioutil.ReadAll(resp.Body) 29 | assert.NoError(t, err) 30 | 31 | bodyStr := string(bodyBytes) 32 | assert.Equal(t, "initialisation not done. Did you forget to call the SuperTokens.init function?\n", bodyStr) 33 | } 34 | -------------------------------------------------------------------------------- /supertokens/errors.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package supertokens 17 | 18 | // BadInputError used for non specific exceptions 19 | type BadInputError struct { 20 | Msg string 21 | } 22 | 23 | func (err BadInputError) Error() string { 24 | return err.Msg 25 | } 26 | -------------------------------------------------------------------------------- /.github/workflows/enforce-go-mod-tidy.yml: -------------------------------------------------------------------------------- 1 | name: "Enforcing go mod tidy in PRs Workflow" 2 | on: [pull_request] 3 | jobs: 4 | go_mod_tidy_job: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2 8 | - name: Set up go 9 | uses: actions/setup-go@v5 10 | - name: Create a new git repository 11 | run: rm -rf .git && git init && git add --all && git -c user.name='test' -c user.email='test@example.com' commit -m 'init for pr action' 12 | - name: Go mod tidy for root project 13 | run: go mod tidy 14 | - name: Go mod tidy for example apps 15 | working-directory: ./examples 16 | run: go mod tidy 17 | - name: Go mod tidy for test server 18 | working-directory: ./test/test-server 19 | run: go mod tidy 20 | - name: git status 21 | run: git status 22 | - name: Check for file changes by go mod tidy 23 | run: git status | grep -q 'nothing to commit, working tree clean' && exit 0 || exit 1 -------------------------------------------------------------------------------- /recipe/session/claims/booleanClaim.go: -------------------------------------------------------------------------------- 1 | package claims 2 | 3 | func BooleanClaim(key string, fetchValue FetchValueFunc, defaultMaxAgeInSeconds *int64) (*TypeSessionClaim, BooleanClaimValidators) { 4 | claim, primitiveClaimValidators := PrimitiveClaim(key, fetchValue, defaultMaxAgeInSeconds) 5 | 6 | validators := BooleanClaimValidators{ 7 | PrimitiveClaimValidators: primitiveClaimValidators, 8 | 9 | IsTrue: func(maxAgeInSeconds *int64, id *string) SessionClaimValidator { 10 | return primitiveClaimValidators.HasValue(true, maxAgeInSeconds, id) 11 | }, 12 | 13 | IsFalse: func(maxAgeInSeconds *int64, id *string) SessionClaimValidator { 14 | return primitiveClaimValidators.HasValue(false, maxAgeInSeconds, id) 15 | }, 16 | } 17 | 18 | return claim, validators 19 | } 20 | 21 | type BooleanClaimValidators struct { 22 | PrimitiveClaimValidators 23 | IsTrue func(maxAgeInSeconds *int64, id *string) SessionClaimValidator 24 | IsFalse func(maxAgeInSeconds *int64, id *string) SessionClaimValidator 25 | } 26 | -------------------------------------------------------------------------------- /recipe/session/claims/booleanClaim_test.go: -------------------------------------------------------------------------------- 1 | package claims 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/supertokens/supertokens-golang/supertokens" 9 | ) 10 | 11 | func TestBooleanClaim(t *testing.T) { 12 | boolClaim, validators := BooleanClaim( 13 | "test", 14 | func(userId string, tenantId string, userContext supertokens.UserContext) (interface{}, error) { 15 | return map[string]interface{}{}, nil 16 | }, 17 | nil, 18 | ) 19 | 20 | payload := map[string]interface{}{} 21 | payload = boolClaim.AddToPayload_internal(payload, true, nil) 22 | 23 | assert.True(t, validators.IsTrue(nil, nil).Validate(payload, nil).IsValid) 24 | assert.False(t, validators.IsFalse(nil, nil).Validate(payload, nil).IsValid) 25 | 26 | maxAge := int64(1) 27 | assert.True(t, validators.IsTrue(&maxAge, nil).Validate(payload, nil).IsValid) 28 | time.Sleep(2 * time.Second) 29 | assert.False(t, validators.IsTrue(&maxAge, nil).Validate(payload, nil).IsValid) 30 | } 31 | -------------------------------------------------------------------------------- /supertokens/logger.go: -------------------------------------------------------------------------------- 1 | package supertokens 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "runtime" 8 | "time" 9 | ) 10 | 11 | const supertokens_namespace = "com.supertokens" 12 | 13 | /* 14 | The debug logger below can be used to log debug messages in the following format 15 | com.supertokens {t: "2022-03-21T17:10:42+05:30", message: "Test Message", file: "/home/supertokens-golang/supertokens/supertokens.go:51" sdkVer: "0.5.2"} 16 | */ 17 | 18 | var ( 19 | Logger = log.New(os.Stdout, supertokens_namespace, 0) 20 | DebugEnabled = false 21 | ) 22 | 23 | func formatMessage(message string) string { 24 | _, file, line, _ := runtime.Caller(2) 25 | return fmt.Sprintf(" {t: \"%s\", message: \"%s\", file: \"%s:%d\" sdkVer: \"%s\"}\n\n", time.Now().Format(time.RFC3339), message, file, line, VERSION) 26 | } 27 | 28 | func LogDebugMessage(message string) { 29 | _, exists := os.LookupEnv("SUPERTOKENS_DEBUG") 30 | if exists || DebugEnabled == true { 31 | Logger.Printf(formatMessage(message)) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.circleci/doUnitTests.sh: -------------------------------------------------------------------------------- 1 | echo "Starting tests for CDI $1"; 2 | 3 | if [ -z "$SUPERTOKENS_API_KEY" ]; then 4 | echo "SUPERTOKENS_API_KEY not set" 5 | exit 1 6 | fi 7 | 8 | coreDriverVersion=$1 9 | coreDriverVersion=`echo $coreDriverVersion | tr -d '"'` 10 | 11 | coreFree=`curl -s -X GET \ 12 | "https://api.supertokens.io/0/core-driver-interface/dependency/core/latest?password=$SUPERTOKENS_API_KEY&planType=FREE&mode=DEV&version=$coreDriverVersion&driverName=golang" \ 13 | -H 'api-version: 1'` 14 | if [[ `echo $coreFree | jq .core` == "null" ]] 15 | then 16 | echo "fetching latest X.Y version for core given core-driver-interface X.Y version: $coreDriverVersion, planType: FREE gave response: $coreFree. Please make sure all relevant cores have been pushed." 17 | exit 1 18 | fi 19 | coreFree=$(echo $coreFree | jq .core | tr -d '"') 20 | 21 | ./setupAndTestWithFreeCore.sh $coreFree $coreDriverVersion 22 | if [[ $? -ne 0 ]] 23 | then 24 | echo "test failed... exiting!" 25 | exit 1 26 | fi 27 | rm -rf ../../supertokens-root -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![SuperTokens banner](https://raw.githubusercontent.com/supertokens/supertokens-logo/master/images/Artboard%20%E2%80%93%2027%402x.png) 2 | 3 | # SuperTokens Golang sdk 4 | 5 | 6 | chat on Discord 8 | 9 | ## About 10 | This is a Golang library that is used to interface between a Go API process and the SuperTokens http service. 11 | 12 | Learn more at https://supertokens.io 13 | 14 | ## Documentation 15 | 16 | To see documentation, please click [here](https://supertokens.io/docs/community/introduction). 17 | 18 | ## Contributing 19 | 20 | Please see the [CONTRIBUTING.md](https://github.com/supertokens/supertokens-golang/blob/master/CONTRIBUTING.md) file for instructions. 21 | 22 | ## Contact us 23 | 24 | For any queries, or support requests, please email us at team@supertokens.io, or join our [Discord](supertokens.io/discord) server. 25 | 26 | ## Authors 27 | 28 | Created with :heart: by the folks at SuperTokens.io. 29 | -------------------------------------------------------------------------------- /recipe/dashboard/main.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package dashboard 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func Init(config *dashboardmodels.TypeInput) supertokens.Recipe { 24 | return recipeInit(config) 25 | } 26 | -------------------------------------------------------------------------------- /test/test-server/go.mod: -------------------------------------------------------------------------------- 1 | module test-server 2 | 3 | go 1.18 4 | 5 | require ( 6 | github.com/gorilla/mux v1.8.1 7 | github.com/supertokens/supertokens-golang v0.0.0-00010101000000-000000000000 8 | ) 9 | 10 | require ( 11 | github.com/MicahParks/keyfunc/v2 v2.1.0 // indirect 12 | github.com/davecgh/go-spew v1.1.1 // indirect 13 | github.com/derekstavis/go-qs v0.0.0-20180720192143-9eef69e6c4e7 // indirect 14 | github.com/golang-jwt/jwt/v5 v5.0.0 // indirect 15 | github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect 16 | github.com/pmezard/go-difflib v1.0.0 // indirect 17 | github.com/stretchr/testify v1.7.0 // indirect 18 | golang.org/x/crypto v0.2.0 // indirect 19 | golang.org/x/net v0.2.0 // indirect 20 | gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect 21 | gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df // indirect 22 | gopkg.in/h2non/gock.v1 v1.1.2 // indirect 23 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect 24 | ) 25 | 26 | replace github.com/supertokens/supertokens-golang => ../.. 27 | -------------------------------------------------------------------------------- /recipe/emailpassword/errors/errors.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package errors 17 | 18 | type FieldError struct { 19 | Msg string 20 | Payload []ErrorPayload 21 | } 22 | 23 | type ErrorPayload struct { 24 | ID string `json:"id"` 25 | ErrorMsg string `json:"error"` 26 | } 27 | 28 | func (err FieldError) Error() string { 29 | return err.Msg 30 | } 31 | -------------------------------------------------------------------------------- /.github/workflows/tests-pass-check-pr.yml: -------------------------------------------------------------------------------- 1 | name: 'Check if "Run tests" action succeeded' 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - reopened 8 | - edited 9 | - synchronize 10 | 11 | jobs: 12 | pr-run-test-action: 13 | name: Check if "Run tests" action succeeded 14 | timeout-minutes: 60 15 | concurrency: 16 | group: ${{ github.head_ref }} 17 | cancel-in-progress: true 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: node install 22 | run: cd ./.github/helpers && npm i 23 | - name: Calling github API 24 | run: cd ./.github/helpers && GITHUB_TOKEN=${{ github.token }} REPO=${{ github.repository }} RUN_ID=${{ github.run_id }} BRANCH=${{ github.head_ref }} JOB_ID=${{ github.job }} SOURCE_OWNER=${{ github.event.pull_request.head.repo.owner.login }} CURRENT_SHA=${{ github.event.pull_request.head.sha }} node node_modules/github-workflow-helpers/test-pass-check-pr.js -------------------------------------------------------------------------------- /.circleci/doBackendSDKTests.sh: -------------------------------------------------------------------------------- 1 | echo "Starting tests for CDI $1, FDI $2"; 2 | 3 | if [ -z "$SUPERTOKENS_API_KEY" ]; then 4 | echo "SUPERTOKENS_API_KEY not set" 5 | exit 1 6 | fi 7 | 8 | coreDriverVersion=$1 9 | coreDriverVersion=`echo $coreDriverVersion | tr -d '"'` 10 | 11 | frontendDriverVersion=$2 12 | 13 | coreFree=`curl -s -X GET \ 14 | "https://api.supertokens.io/0/core-driver-interface/dependency/core/latest?password=$SUPERTOKENS_API_KEY&planType=FREE&mode=DEV&version=$coreDriverVersion&driverName=golang" \ 15 | -H 'api-version: 1'` 16 | if [[ `echo $coreFree | jq .core` == "null" ]] 17 | then 18 | echo "fetching latest X.Y version for core given core-driver-interface X.Y version: $coreDriverVersion, planType: FREE gave response: $coreFree. Please make sure all relevant cores have been pushed." 19 | exit 1 20 | fi 21 | coreFree=$(echo $coreFree | jq .core | tr -d '"') 22 | 23 | ./setupAndTestBackendSDKWithFreeCore.sh $coreFree $coreDriverVersion $frontendDriverVersion 24 | if [[ $? -ne 0 ]] 25 | then 26 | echo "test failed... exiting!" 27 | exit 1 28 | fi 29 | rm -rf ../../supertokens-root -------------------------------------------------------------------------------- /recipe/dashboard/apiKeyProtector.go: -------------------------------------------------------------------------------- 1 | package dashboard 2 | 3 | import ( 4 | "errors" 5 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 6 | errors2 "github.com/supertokens/supertokens-golang/recipe/dashboard/errors" 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | func apiKeyProtector(apiImpl dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext, call func() (interface{}, error)) error { 11 | shouldAllowAccess, err := (*options.RecipeImplementation.ShouldAllowAccess)(options.Req, options.Config, userContext) 12 | if err != nil { 13 | if errors.As(err, &errors2.ForbiddenAccessError{}) { 14 | return supertokens.SendNon200Response(options.Res, 403, map[string]interface{}{ 15 | "message": err.Error(), 16 | }) 17 | } 18 | 19 | return err 20 | } 21 | 22 | if !shouldAllowAccess { 23 | return supertokens.SendUnauthorisedAccess(options.Res) 24 | } 25 | 26 | resp, err := call() 27 | if err != nil { 28 | return err 29 | } 30 | 31 | return supertokens.Send200Response(options.Res, resp) 32 | } 33 | -------------------------------------------------------------------------------- /supertokens/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package supertokens 17 | 18 | const ( 19 | HeaderRID = "rid" 20 | HeaderFDI = "fdi-version" 21 | ) 22 | 23 | // VERSION current version of the lib 24 | const VERSION = "0.25.1" 25 | 26 | var ( 27 | cdiSupported = []string{"3.1"} 28 | ) 29 | 30 | const DashboardVersion = "0.7" 31 | 32 | const DefaultTenantId string = "public" 33 | 34 | const RateLimitStatusCode = 429 35 | -------------------------------------------------------------------------------- /recipe/usermetadata/usermetadatamodels/models.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package usermetadatamodels 17 | 18 | type TypeInput struct { 19 | Override *OverrideStruct 20 | } 21 | 22 | type TypeNormalisedInput struct { 23 | Override OverrideStruct 24 | } 25 | 26 | type OverrideStruct struct { 27 | Functions func(originalImplementation RecipeInterface) RecipeInterface 28 | APIs func(originalImplementation APIInterface) APIInterface 29 | } 30 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/supertokens/supertokens-golang 2 | 3 | go 1.18 4 | 5 | // TODO: add go mod tidy in a build process 6 | 7 | require ( 8 | github.com/MicahParks/keyfunc/v2 v2.1.0 9 | github.com/derekstavis/go-qs v0.0.0-20180720192143-9eef69e6c4e7 10 | github.com/golang-jwt/jwt/v5 v5.0.0 11 | github.com/joho/godotenv v1.3.0 12 | github.com/nyaruka/phonenumbers v1.0.73 13 | github.com/stretchr/testify v1.7.0 14 | github.com/twilio/twilio-go v0.26.0 15 | golang.org/x/crypto v0.2.0 16 | golang.org/x/net v0.2.0 17 | gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df 18 | gopkg.in/h2non/gock.v1 v1.1.2 19 | ) 20 | 21 | require ( 22 | github.com/davecgh/go-spew v1.1.1 // indirect 23 | github.com/golang/mock v1.6.0 // indirect 24 | github.com/golang/protobuf v1.3.2 // indirect 25 | github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect 26 | github.com/pkg/errors v0.9.1 // indirect 27 | github.com/pmezard/go-difflib v1.0.0 // indirect 28 | golang.org/x/text v0.4.0 // indirect 29 | gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect 30 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect 31 | ) 32 | -------------------------------------------------------------------------------- /recipe/emailpassword/constants/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package constants 17 | 18 | const ( 19 | SignUpAPI = "/signup" 20 | SignInAPI = "/signin" 21 | GeneratePasswordResetTokenAPI = "/user/password/reset/token" 22 | PasswordResetAPI = "/user/password/reset" 23 | SignupEmailExistsAPIOld = "/signup/email/exists" 24 | SignupEmailExistsAPI = "/emailpassword/email/exists" 25 | ) 26 | -------------------------------------------------------------------------------- /recipe/dashboard/dashboardmodels/recipeInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package dashboardmodels 17 | 18 | import ( 19 | "net/http" 20 | 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | type RecipeInterface struct { 25 | GetDashboardBundleLocation *func(userContext supertokens.UserContext) (string, error) 26 | ShouldAllowAccess *func(req *http.Request, config TypeNormalisedInput, userContext supertokens.UserContext) (bool, error) 27 | } 28 | -------------------------------------------------------------------------------- /recipe/jwt/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwt 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/supertokens" 20 | "github.com/supertokens/supertokens-golang/test/unittesting" 21 | ) 22 | 23 | func resetAll() { 24 | supertokens.ResetForTest() 25 | } 26 | 27 | func BeforeEach() { 28 | unittesting.KillAllST() 29 | resetAll() 30 | unittesting.SetUpST() 31 | } 32 | 33 | func AfterEach() { 34 | unittesting.KillAllST() 35 | resetAll() 36 | unittesting.CleanST() 37 | } 38 | -------------------------------------------------------------------------------- /recipe/openid/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package openid 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/supertokens" 20 | "github.com/supertokens/supertokens-golang/test/unittesting" 21 | ) 22 | 23 | func resetAll() { 24 | supertokens.ResetForTest() 25 | } 26 | 27 | func BeforeEach() { 28 | unittesting.KillAllST() 29 | resetAll() 30 | unittesting.SetUpST() 31 | } 32 | 33 | func AfterEach() { 34 | unittesting.KillAllST() 35 | resetAll() 36 | unittesting.CleanST() 37 | } 38 | -------------------------------------------------------------------------------- /recipe/multitenancy/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package multitenancy 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/supertokens" 20 | "github.com/supertokens/supertokens-golang/test/unittesting" 21 | ) 22 | 23 | func resetAll() { 24 | supertokens.ResetForTest() 25 | } 26 | 27 | func BeforeEach() { 28 | unittesting.KillAllST() 29 | resetAll() 30 | unittesting.SetUpST() 31 | } 32 | 33 | func AfterEach() { 34 | unittesting.KillAllST() 35 | resetAll() 36 | unittesting.CleanST() 37 | } 38 | -------------------------------------------------------------------------------- /recipe/passwordless/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package passwordless 17 | 18 | const ( 19 | createCodeAPI = "/signinup/code" 20 | resendCodeAPI = "/signinup/code/resend" 21 | consumeCodeAPI = "/signinup/code/consume" 22 | doesEmailExistAPIOld = "/signup/email/exists" 23 | doesPhoneNumberExistAPIOld = "/signup/phonenumber/exists" 24 | doesEmailExistAPI = "/passwordless/email/exists" 25 | doesPhoneNumberExistAPI = "/passwordless/phonenumber/exists" 26 | ) 27 | -------------------------------------------------------------------------------- /recipe/usermetadata/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package usermetadata 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/supertokens" 20 | "github.com/supertokens/supertokens-golang/test/unittesting" 21 | ) 22 | 23 | func resetAll() { 24 | supertokens.ResetForTest() 25 | } 26 | 27 | func BeforeEach() { 28 | unittesting.KillAllST() 29 | resetAll() 30 | unittesting.SetUpST() 31 | } 32 | 33 | func AfterEach() { 34 | unittesting.KillAllST() 35 | resetAll() 36 | unittesting.CleanST() 37 | } 38 | -------------------------------------------------------------------------------- /recipe/emailverification/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package emailverification 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/supertokens" 20 | "github.com/supertokens/supertokens-golang/test/unittesting" 21 | ) 22 | 23 | func resetAll() { 24 | supertokens.ResetForTest() 25 | } 26 | 27 | func BeforeEach() { 28 | unittesting.KillAllST() 29 | resetAll() 30 | unittesting.SetUpST() 31 | } 32 | 33 | func AfterEach() { 34 | unittesting.KillAllST() 35 | resetAll() 36 | unittesting.CleanST() 37 | } 38 | -------------------------------------------------------------------------------- /examples/with-twirp/internal/interceptor/errorHandler.go: -------------------------------------------------------------------------------- 1 | package interceptor 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | 7 | "github.com/supertokens/supertokens-golang/recipe/session" 8 | sessionError "github.com/supertokens/supertokens-golang/recipe/session/errors" 9 | "github.com/twitchtv/twirp" 10 | ) 11 | 12 | func NewSuperTokensErrorHandlerInterceptor() twirp.Interceptor { 13 | return func(next twirp.Method) twirp.Method { 14 | return func(ctx context.Context, req interface{}) (interface{}, error) { 15 | resp, err := next(ctx, req) 16 | if err != nil { 17 | var sessionErr sessionError.TokenTheftDetectedError 18 | if errors.As(err, &sessionError.TryRefreshTokenError{}) { 19 | return resp, twirp.NewError(twirp.Unauthenticated, "try refresh token") 20 | } else if errors.As(err, &sessionError.UnauthorizedError{}) { 21 | return resp, twirp.NewError(twirp.Unauthenticated, "unauthorized") 22 | } else if errors.As(err, &sessionErr) { 23 | _, err = session.RevokeSession(sessionErr.Payload.SessionHandle) 24 | if err != nil { 25 | return resp, err 26 | } 27 | return resp, twirp.NewError(twirp.Unauthenticated, "token theft detected") 28 | } 29 | } 30 | return resp, err 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /recipe/usermetadata/usermetadatamodels/recipeInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package usermetadatamodels 17 | 18 | import "github.com/supertokens/supertokens-golang/supertokens" 19 | 20 | type RecipeInterface struct { 21 | GetUserMetadata *func(userID string, userContext supertokens.UserContext) (map[string]interface{}, error) 22 | UpdateUserMetadata *func(userID string, metadataUpdate map[string]interface{}, userContext supertokens.UserContext) (map[string]interface{}, error) 23 | ClearUserMetadata *func(userID string, userContext supertokens.UserContext) error 24 | } 25 | -------------------------------------------------------------------------------- /recipe/multitenancy/api/loginMethods.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/multitenancy/multitenancymodels" 5 | "github.com/supertokens/supertokens-golang/supertokens" 6 | ) 7 | 8 | func LoginMethodsAPI(apiImplementation multitenancymodels.APIInterface, tenantId string, options multitenancymodels.APIOptions, userContext supertokens.UserContext) error { 9 | if apiImplementation.LoginMethodsGET == nil || (*apiImplementation.LoginMethodsGET) == nil { 10 | options.OtherHandler(options.Res, options.Req) 11 | return nil 12 | } 13 | 14 | queryParams := options.Req.URL.Query() 15 | 16 | var clientType *string = nil 17 | if clientTypeStrFromQueryParams := queryParams.Get("clientType"); clientTypeStrFromQueryParams != "" { 18 | clientType = &clientTypeStrFromQueryParams 19 | } 20 | 21 | result, err := (*apiImplementation.LoginMethodsGET)(tenantId, clientType, options, userContext) 22 | if err != nil { 23 | return err 24 | } 25 | 26 | if result.OK != nil { 27 | return supertokens.Send200Response(options.Res, result.OK) 28 | } else if result.GeneralError != nil { 29 | return supertokens.Send200Response(options.Res, supertokens.ConvertGeneralErrorToJsonResponse(*result.GeneralError)) 30 | } 31 | return supertokens.ErrorIfNoResponse(options.Res) 32 | } 33 | -------------------------------------------------------------------------------- /examples/with-chi-oso/database/database.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/supertokens/supertokens-golang/examples/with-chi-oso/models" 7 | ) 8 | 9 | type Db struct { 10 | users map[string]models.User 11 | repos map[string]models.Repository 12 | } 13 | 14 | func NewDb() *Db { 15 | return &Db{ 16 | users: map[string]models.User{ 17 | "larry@supertokens.io": {Roles: []models.RepositoryRole{{Role: "admin", RepoId: 0}}}, 18 | "anne@supertokens.io": {Roles: []models.RepositoryRole{{Role: "maintainer", RepoId: 1}}}, 19 | "graham@supertokens.io": {Roles: []models.RepositoryRole{{Role: "contributor", RepoId: 2}}}, 20 | }, 21 | repos: map[string]models.Repository{ 22 | "gmail": {Id: 0, Name: "gmail"}, 23 | "react": {Id: 0, Name: "react", IsPublic: true}, 24 | "oso": {Id: 0, Name: "oso"}, 25 | }, 26 | } 27 | } 28 | 29 | func (d *Db) GetRepositoryByName(name string) (models.Repository, error) { 30 | if r, ok := d.repos[name]; ok { 31 | return r, nil 32 | } 33 | return models.Repository{}, fmt.Errorf("repository not found: %s", name) 34 | } 35 | 36 | func (d *Db) GetCurrentUser(email string) (models.User, error) { 37 | if u, ok := d.users[email]; ok { 38 | return u, nil 39 | } 40 | return models.User{}, fmt.Errorf("user not found: %s", email) 41 | } 42 | -------------------------------------------------------------------------------- /examples/with-twirp/haberdasher/gen.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Twitch Interactive, Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may not 4 | // use this file except in compliance with the License. A copy of the License is 5 | // located at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed on 10 | // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package haberdasher 15 | 16 | // Go generate directives are a convenient way to describe compilation of proto 17 | // files. They let users run 'go generate ./...', no Makefile necessary. 18 | // 19 | // This particular particular one invokes protoc using '$GOPATH/src'. 20 | // 21 | // This is used to tell protoc where to look up .proto files, through 22 | // --proto_path. 23 | // 24 | // It is also used to tell protoc where to put output generated files, through 25 | // --twirp_out and --go_out. 26 | 27 | //go:generate protoc --proto_path=$GOPATH/src --twirp_out=$GOPATH/src --go_out=$GOPATH/src github.com/twitchtv/twirp-example/rpc/haberdasher/haberdasher.proto 28 | -------------------------------------------------------------------------------- /recipe/userroles/userrolesmodels/models.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userrolesmodels 17 | 18 | type TypeInput struct { 19 | SkipAddingRolesToAccessToken bool 20 | SkipAddingPermissionsToAccessToken bool 21 | 22 | Override *OverrideStruct 23 | } 24 | 25 | type TypeNormalisedInput struct { 26 | SkipAddingRolesToAccessToken bool 27 | SkipAddingPermissionsToAccessToken bool 28 | 29 | Override OverrideStruct 30 | } 31 | 32 | type OverrideStruct struct { 33 | Functions func(originalImplementation RecipeInterface) RecipeInterface 34 | APIs func(originalImplementation APIInterface) APIInterface 35 | } 36 | -------------------------------------------------------------------------------- /.circleci/markAsSuccess.sh: -------------------------------------------------------------------------------- 1 | coreDriverJson=`cat ../coreDriverInterfaceSupported.json` 2 | coreDriverLength=`echo $coreDriverJson | jq ".versions | length"` 3 | coreDriverArray=`echo $coreDriverJson | jq ".versions"` 4 | echo "got core driver relations" 5 | 6 | frontendDriverJson=`cat ../frontendDriverInterfaceSupported.json` 7 | frontendDriverLength=`echo $frontendDriverJson | jq ".versions | length"` 8 | frontendDriverArray=`echo $frontendDriverJson | jq ".versions"` 9 | echo "got frontend driver relations" 10 | 11 | # get driver version 12 | version=`cat ../supertokens/constants.go | grep -e 'const VERSION'` 13 | while IFS='"' read -ra ADDR; do 14 | counter=0 15 | for i in "${ADDR[@]}"; do 16 | if [ $counter == 1 ] 17 | then 18 | version=$i 19 | fi 20 | counter=$(($counter+1)) 21 | done 22 | done <<< "$version" 23 | 24 | echo "calling /driver PATCH to make testing passed" 25 | responseStatus=`curl -s -o /dev/null -w "%{http_code}" -X PATCH \ 26 | https://api.supertokens.io/0/driver \ 27 | -H 'Content-Type: application/json' \ 28 | -H 'api-version: 0' \ 29 | -d "{ 30 | \"password\": \"$SUPERTOKENS_API_KEY\", 31 | \"version\":\"$version\", 32 | \"name\": \"golang\", 33 | \"testPassed\": true 34 | }"` 35 | if [ $responseStatus -ne "200" ] 36 | then 37 | echo "patch api failed" 38 | exit 1 39 | fi -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.236.0/containers/java 3 | { 4 | "name": "Java", 5 | "build": { 6 | "dockerfile": "Dockerfile", 7 | "args": { 8 | "VARIANT": "15", 9 | // Options 10 | "INSTALL_MAVEN": "false", 11 | "INSTALL_GRADLE": "true", 12 | "NODE_VERSION": "lts/*" 13 | } 14 | }, 15 | // Configure tool-specific properties. 16 | "customizations": { 17 | // Configure properties specific to VS Code. 18 | "vscode": { 19 | // Set *default* container specific settings.json values on container create. 20 | "settings": { 21 | "java.home": "/docker-java-home", 22 | "terminal.integrated.shell.linux": "zsh", 23 | }, 24 | // Add the IDs of extensions you want installed when the container is created. 25 | "extensions": [ 26 | "vscjava.vscode-java-pack" 27 | ] 28 | } 29 | }, 30 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 31 | // "forwardPorts": [], 32 | // Use 'postCreateCommand' to run commands after the container is created. 33 | // "postCreateCommand": "java -version", 34 | // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 35 | "remoteUser": "vscode", 36 | "features": { 37 | "golang": "latest" 38 | } 39 | } -------------------------------------------------------------------------------- /recipe/dashboard/dashboardmodels/apiInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package dashboardmodels 17 | 18 | import ( 19 | "net/http" 20 | 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | type APIOptions struct { 25 | RecipeImplementation RecipeInterface 26 | AppInfo supertokens.NormalisedAppinfo 27 | Config TypeNormalisedInput 28 | RecipeID string 29 | Req *http.Request 30 | Res http.ResponseWriter 31 | OtherHandler http.HandlerFunc 32 | } 33 | 34 | type APIInterface struct { 35 | DashboardGET *func(options APIOptions, userContext supertokens.UserContext) (string, error) 36 | } 37 | -------------------------------------------------------------------------------- /recipe/multitenancy/allowedDomainsClaim.go: -------------------------------------------------------------------------------- 1 | package multitenancy 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/session/claims" 5 | "github.com/supertokens/supertokens-golang/supertokens" 6 | ) 7 | 8 | func NewAllowedDomainsClaim() (*claims.TypeSessionClaim, claims.PrimitiveArrayClaimValidators) { 9 | fetchDomains := func(userId string, tenantId string, userContext supertokens.UserContext) (interface{}, error) { 10 | instance, err := GetRecipeInstanceOrThrowError() 11 | if err != nil { 12 | return nil, err 13 | } 14 | 15 | if instance.GetAllowedDomainsForTenantId == nil { 16 | return nil, nil // User did not provide a function to get allowed domains, but is using a validator. So we don't allow any domains by default 17 | } 18 | 19 | domains, err := instance.GetAllowedDomainsForTenantId(tenantId, userContext) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | // Need this conversion because the array claim expects an array of type []interface{} 25 | domainsArray := make([]interface{}, len(domains)) 26 | for i, domain := range domains { 27 | domainsArray[i] = domain 28 | } 29 | return domainsArray, nil 30 | } 31 | 32 | var defaultMaxAge int64 = 3600 33 | allowedDomainsClaim, allowedDomainsClaimValidators := claims.PrimitiveArrayClaim("st-t-dmns", fetchDomains, &defaultMaxAge) 34 | 35 | return allowedDomainsClaim, allowedDomainsClaimValidators 36 | } 37 | -------------------------------------------------------------------------------- /.circleci/markDevTagAsTestNotPassed.sh: -------------------------------------------------------------------------------- 1 | coreDriverJson=`cat ../coreDriverInterfaceSupported.json` 2 | coreDriverLength=`echo $coreDriverJson | jq ".versions | length"` 3 | coreDriverArray=`echo $coreDriverJson | jq ".versions"` 4 | echo "got core driver relations" 5 | 6 | frontendDriverJson=`cat ../frontendDriverInterfaceSupported.json` 7 | frontendDriverLength=`echo $frontendDriverJson | jq ".versions | length"` 8 | frontendDriverArray=`echo $frontendDriverJson | jq ".versions"` 9 | echo "got frontend driver relations" 10 | 11 | # get driver version 12 | version=`cat ../supertokens/constants.go | grep -e 'const VERSION'` 13 | while IFS='"' read -ra ADDR; do 14 | counter=0 15 | for i in "${ADDR[@]}"; do 16 | if [ $counter == 1 ] 17 | then 18 | version=$i 19 | fi 20 | counter=$(($counter+1)) 21 | done 22 | done <<< "$version" 23 | 24 | responseStatus=`curl -s -o /dev/null -w "%{http_code}" -X PUT \ 25 | https://api.supertokens.io/0/driver \ 26 | -H 'Content-Type: application/json' \ 27 | -H 'api-version: 0' \ 28 | -d "{ 29 | \"password\": \"$SUPERTOKENS_API_KEY\", 30 | \"version\":\"$version\", 31 | \"name\": \"golang\", 32 | \"frontendDriverInterfaces\": $frontendDriverArray, 33 | \"coreDriverInterfaces\": $coreDriverArray 34 | }"` 35 | if [ $responseStatus -ne "200" ] 36 | then 37 | echo "failed core PUT API status code: $responseStatus. Exiting!" 38 | exit 1 39 | fi -------------------------------------------------------------------------------- /supertokens/utils_test.go: -------------------------------------------------------------------------------- 1 | package supertokens 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type GetTopLevelDomainForSameSiteResolutionTest struct { 10 | Input string 11 | Output string 12 | } 13 | 14 | func TestGetTopLevelDomainForSameSiteResolution(t *testing.T) { 15 | input := []GetTopLevelDomainForSameSiteResolutionTest{{ 16 | Input: "http://a.b.test.com", 17 | Output: "test.com", 18 | }, { 19 | Input: "https://a.b.test.com", 20 | Output: "test.com", 21 | }, { 22 | Input: "http://a.b.test.co.uk", 23 | Output: "test.co.uk", 24 | }, { 25 | Input: "http://test.com", 26 | Output: "test.com", 27 | }, { 28 | Input: "https://test.com", 29 | Output: "test.com", 30 | }, { 31 | Input: "http://localhost", 32 | Output: "localhost", 33 | }, { 34 | Input: "http://localhost.org", 35 | Output: "localhost", 36 | }, { 37 | Input: "http://8.8.8.8", 38 | Output: "localhost", 39 | }, { 40 | Input: "http://8.8.8.8:8080", 41 | Output: "localhost", 42 | }, { 43 | Input: "http://localhost:3000", 44 | Output: "localhost", 45 | }, { 46 | Input: "http://test.com:3567", 47 | Output: "test.com", 48 | }, { 49 | Input: "https://test.com:3567", 50 | Output: "test.com", 51 | }} 52 | for _, val := range input { 53 | domain, _ := GetTopLevelDomainForSameSiteResolution(val.Input) 54 | assert.Equal(t, val.Output, domain, val.Input) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /recipe/jwt/jwtmodels/models.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwtmodels 17 | 18 | type JsonWebKeys struct { 19 | Kty string `json:"kty"` 20 | Kid string `json:"kid"` 21 | N string `json:"n"` 22 | E string `json:"e"` 23 | Alg string `json:"alg"` 24 | Use string `json:"use"` 25 | } 26 | 27 | type TypeInput struct { 28 | JwtValiditySeconds *uint64 29 | Override *OverrideStruct 30 | } 31 | 32 | type TypeNormalisedInput struct { 33 | JwtValiditySeconds uint64 34 | Override OverrideStruct 35 | } 36 | 37 | type OverrideStruct struct { 38 | Functions func(originalImplementation RecipeInterface) RecipeInterface 39 | APIs func(originalImplementation APIInterface) APIInterface 40 | } 41 | -------------------------------------------------------------------------------- /recipe/dashboard/api/signOutPost.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "strings" 5 | 6 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | type signOutPostResponse struct { 11 | Status string `json:"status"` 12 | } 13 | 14 | func SignOutPost(apiInterface dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (signOutPostResponse, error) { 15 | if options.Config.AuthMode == dashboardmodels.AuthModeAPIKey { 16 | return signOutPostResponse{ 17 | Status: "OK", 18 | }, nil 19 | } 20 | 21 | sessionIdFromHeader := options.Req.Header.Get("authorization") 22 | 23 | // We receive the api key as `Bearer API_KEY`, this retrieves just the key 24 | keyParts := strings.Split(sessionIdFromHeader, " ") 25 | sessionIdFromHeader = keyParts[len(keyParts)-1] 26 | 27 | querier, querierErr := supertokens.GetNewQuerierInstanceOrThrowError("dashboard") 28 | 29 | if querierErr != nil { 30 | return signOutPostResponse{}, querierErr 31 | } 32 | 33 | _, apiError := querier.SendDeleteRequest("/recipe/dashboard/session", map[string]interface{}{}, map[string]string{ 34 | "sessionId": sessionIdFromHeader, 35 | }, userContext) 36 | 37 | if apiError != nil { 38 | return signOutPostResponse{}, apiError 39 | } 40 | 41 | return signOutPostResponse{ 42 | Status: "OK", 43 | }, nil 44 | } 45 | -------------------------------------------------------------------------------- /recipe/jwt/jwtmodels/recipeInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwtmodels 17 | 18 | import "github.com/supertokens/supertokens-golang/supertokens" 19 | 20 | type RecipeInterface struct { 21 | CreateJWT *func(payload map[string]interface{}, validitySeconds *uint64, useStaticSigningKey *bool, userContext supertokens.UserContext) (CreateJWTResponse, error) 22 | GetJWKS *func(userContext supertokens.UserContext) (GetJWKSResponse, error) 23 | } 24 | 25 | type CreateJWTResponse struct { 26 | OK *struct { 27 | Jwt string 28 | } 29 | UnsupportedAlgorithmError *struct{} 30 | } 31 | 32 | type GetJWKSResponse struct { 33 | OK *struct { 34 | Keys []JsonWebKeys 35 | ValidityInSeconds int 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /recipe/session/refresh.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package session 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func HandleRefreshAPI(apiImplementation sessmodels.APIInterface, options sessmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.RefreshPOST == nil || (*apiImplementation.RefreshPOST) == nil { 25 | options.OtherHandler.ServeHTTP(options.Res, options.Req) 26 | return nil 27 | } 28 | _, err := (*apiImplementation.RefreshPOST)(options, userContext) 29 | if err != nil { 30 | return err 31 | } 32 | return supertokens.Send200Response(options.Res, nil) 33 | } 34 | -------------------------------------------------------------------------------- /recipe/dashboard/api/dashboard.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func Dashboard(apiImplementation dashboardmodels.APIInterface, options dashboardmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.DashboardGET == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | 29 | htmlString, err := (*apiImplementation.DashboardGET)(options, userContext) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | supertokens.SendHTMLResponse(options.Res, 200, htmlString) 35 | 36 | return err 37 | } 38 | -------------------------------------------------------------------------------- /recipe/jwt/jwtmodels/apiInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwtmodels 17 | 18 | import ( 19 | "net/http" 20 | 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | type APIOptions struct { 25 | RecipeImplementation RecipeInterface 26 | Config TypeNormalisedInput 27 | RecipeID string 28 | Req *http.Request 29 | Res http.ResponseWriter 30 | OtherHandler http.HandlerFunc 31 | } 32 | 33 | type APIInterface struct { 34 | GetJWKSGET *func(options APIOptions, userContext supertokens.UserContext) (GetJWKSAPIResponse, error) 35 | } 36 | 37 | type GetJWKSAPIResponse struct { 38 | OK *struct { 39 | Keys []JsonWebKeys 40 | } 41 | GeneralError *supertokens.GeneralErrorResponse 42 | } 43 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.236.0/containers/java/.devcontainer/base.Dockerfile 2 | 3 | # [Choice] Java version (use -bullseye variants on local arm64/Apple Silicon): 11, 17, 11-bullseye, 17-bullseye, 11-buster, 17-buster 4 | ARG VARIANT="17-bullseye" 5 | FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT} 6 | 7 | # [Option] Install Maven 8 | ARG INSTALL_MAVEN="false" 9 | ARG MAVEN_VERSION="" 10 | # [Option] Install Gradle 11 | ARG INSTALL_GRADLE="false" 12 | ARG GRADLE_VERSION="" 13 | RUN if [ "${INSTALL_MAVEN}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install maven \"${MAVEN_VERSION}\""; fi \ 14 | && if [ "${INSTALL_GRADLE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install gradle \"${GRADLE_VERSION}\""; fi 15 | 16 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 17 | ARG NODE_VERSION="none" 18 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 19 | 20 | # [Optional] Uncomment this section to install additional OS packages. 21 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 22 | # && apt-get -y install --no-install-recommends 23 | 24 | # [Optional] Uncomment this line to install global node packages. 25 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /recipe/dashboard/constants/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2023, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | package constants 16 | 17 | const DashboardAPI = "/dashboard" 18 | const DashboardAPIBasePath = "/dashboard" 19 | const SignInAPI = "/api/signin" 20 | const SignOutAPI = "/api/signout" 21 | const ValidateKeyAPI = "/api/key/validate" 22 | const UsersListGetAPI = "/api/users" 23 | const UsersCountAPI = "/api/users/count" 24 | const UserAPI = "/api/user" 25 | const UserEmailVerifyAPI = "/api/user/email/verify" 26 | const UserMetadataAPI = "/api/user/metadata" 27 | const UserSessionsAPI = "/api/user/sessions" 28 | const UserPasswordAPI = "/api/user/password" 29 | const UserEmailVerifyTokenAPI = "/api/user/email/verify/token" 30 | const SearchTagsAPI = "/api/search/tags" 31 | const DashboardAnalyticsAPI = "/api/analytics" 32 | const TenantsListAPI = "/api/tenants/list" 33 | -------------------------------------------------------------------------------- /recipe/multitenancy/multitenancymodels/models.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package multitenancymodels 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/supertokens" 20 | ) 21 | 22 | const DefaultTenantId string = "public" 23 | 24 | type TypeInput struct { 25 | GetAllowedDomainsForTenantId func(tenantId string, userContext supertokens.UserContext) ([]string, error) 26 | Override *OverrideStruct 27 | } 28 | 29 | type TypeNormalisedInput struct { 30 | GetAllowedDomainsForTenantId func(tenantId string, userContext supertokens.UserContext) ([]string, error) 31 | Override OverrideStruct 32 | } 33 | 34 | type OverrideStruct struct { 35 | Functions func(originalImplementation RecipeInterface) RecipeInterface 36 | APIs func(originalImplementation APIInterface) APIInterface 37 | } 38 | -------------------------------------------------------------------------------- /examples/with-twirp/README.md: -------------------------------------------------------------------------------- 1 | This is an example of how to integrate [Twirp](https://github.com/twitchtv/twirp) with SuperTokens. 2 | 3 | To start this server, run: 4 | ``` 5 | go run cmd/server/main.go 6 | ``` 7 | 8 | ## Few important points 9 | - The code [here](https://github.com/supertokens/supertokens-golang/blob/master/examples/with-twirp/cmd/server/main.go#L58) does `CORS(supertokens.Middleware(verifySession(twirpServer)))`. 10 | - The middleware exposes all the APIs for the frontend to work. Like sign up / sign in etc. 11 | - We use `verifySession` in optional mode (`SessionRequired` is `false`). This means that all API requests will go through session verification, but sessions won't be enforced. If a session exists, the `SessionContainer` object will be available to the API, else not. 12 | - We can fetch the `SessionContainer` object in an API like shown [here](https://github.com/supertokens/supertokens-golang/blob/master/examples/with-twirp/internal/haberdasherserver/random.go#L38). The API must check if this object is `nil` or not. If a session exists, this object will not be `nil`, and then one can retrieve session info like the userId, or any session data. They can even revoke the session if needed. 13 | - We need to add a request interceptor defined [here](https://github.com/supertokens/supertokens-golang/blob/master/examples/with-twirp/internal/interceptor/errorHandler.go). Some functions provided by SuperTokens (like getting session information) might throw an error which will be caught by this interceptor and a `401` reply will be sent to the frontend client. 14 | -------------------------------------------------------------------------------- /recipe/openid/openidmodels/models.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package openidmodels 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/jwt/jwtmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | type TypeInput struct { 24 | Issuer *string 25 | JwtValiditySeconds *uint64 26 | Override *OverrideStruct 27 | } 28 | 29 | type TypeNormalisedInput struct { 30 | IssuerDomain supertokens.NormalisedURLDomain 31 | IssuerPath supertokens.NormalisedURLPath 32 | JwtValiditySeconds *uint64 33 | Override OverrideStruct 34 | } 35 | 36 | type OverrideStruct struct { 37 | Functions func(originalImplementation RecipeInterface) RecipeInterface 38 | APIs func(originalImplementation APIInterface) APIInterface 39 | JwtFeature *jwtmodels.OverrideStruct 40 | } 41 | -------------------------------------------------------------------------------- /supertokens/humanise_test.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package supertokens 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/stretchr/testify/assert" 22 | ) 23 | 24 | func TestHumaniseMilliseconds(t *testing.T) { 25 | assert.Equal(t, "1 second", HumaniseMilliseconds(1000)) 26 | assert.Equal(t, "59 seconds", HumaniseMilliseconds(59000)) 27 | assert.Equal(t, "1 minute", HumaniseMilliseconds(60000)) 28 | assert.Equal(t, "1 minute", HumaniseMilliseconds(119000)) 29 | assert.Equal(t, "2 minutes", HumaniseMilliseconds(120000)) 30 | assert.Equal(t, "1 hour", HumaniseMilliseconds(3600000)) 31 | assert.Equal(t, "1 hour", HumaniseMilliseconds(3660000)) 32 | assert.Equal(t, "1.1 hours", HumaniseMilliseconds(3960000)) 33 | assert.Equal(t, "2 hours", HumaniseMilliseconds(7260000)) 34 | assert.Equal(t, "5 hours", HumaniseMilliseconds(18000000)) 35 | } 36 | -------------------------------------------------------------------------------- /recipe/openid/openidmodels/recipeInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package openidmodels 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/jwt/jwtmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | type RecipeInterface struct { 24 | GetOpenIdDiscoveryConfiguration *func(userContext supertokens.UserContext) (GetOpenIdDiscoveryConfigurationResponse, error) 25 | CreateJWT *func(payload map[string]interface{}, validitySeconds *uint64, useStaticSigningKey *bool, userContext supertokens.UserContext) (jwtmodels.CreateJWTResponse, error) 26 | GetJWKS *func(userContext supertokens.UserContext) (jwtmodels.GetJWKSResponse, error) 27 | } 28 | 29 | type GetOpenIdDiscoveryConfigurationResponse struct { 30 | OK *struct { 31 | Issuer string 32 | Jwks_uri string 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /recipe/openid/openidmodels/apiInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package openidmodels 17 | 18 | import ( 19 | "net/http" 20 | 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | type APIOptions struct { 25 | RecipeImplementation RecipeInterface 26 | Config TypeNormalisedInput 27 | RecipeID string 28 | Req *http.Request 29 | Res http.ResponseWriter 30 | OtherHandler http.HandlerFunc 31 | } 32 | 33 | type APIInterface struct { 34 | GetOpenIdDiscoveryConfigurationGET *func(options APIOptions, userContext supertokens.UserContext) (GetOpenIdDiscoveryConfigurationAPIResponse, error) 35 | } 36 | 37 | type GetOpenIdDiscoveryConfigurationAPIResponse struct { 38 | OK *struct { 39 | Issuer string 40 | Jwks_uri string 41 | } 42 | GeneralError *supertokens.GeneralErrorResponse 43 | } 44 | -------------------------------------------------------------------------------- /recipe/passwordless/smsdelivery/twilioService/serviceImplementation.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package twilioService 18 | 19 | import ( 20 | "github.com/supertokens/supertokens-golang/ingredients/smsdelivery" 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | func MakeServiceImplementation(config smsdelivery.TwilioSettings) smsdelivery.TwilioInterface { 25 | sendRawSms := func(input smsdelivery.SMSContent, userContext supertokens.UserContext) error { 26 | return smsdelivery.SendTwilioSms(config, input) 27 | } 28 | 29 | getContent := func(input smsdelivery.SmsType, userContext supertokens.UserContext) (smsdelivery.SMSContent, error) { 30 | result := getPasswordlessLoginSmsContent(*input.PasswordlessLogin) 31 | return result, nil 32 | } 33 | 34 | return smsdelivery.TwilioInterface{ 35 | SendRawSms: &sendRawSms, 36 | GetContent: &getContent, 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /test/test-server/additional-files/new_session_for_test_server.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" 5 | ) 6 | 7 | func NewSessionContainerFromSessionContainerInputForTestServer(sessionMap map[string]interface{}) (sessmodels.SessionContainer, error) { 8 | recipe, err := getRecipeInstanceOrThrowError() 9 | if err != nil { 10 | return nil, err 11 | } 12 | 13 | session := &SessionContainerInput{ 14 | sessionHandle: sessionMap["sessionHandle"].(string), 15 | userID: sessionMap["userId"].(string), 16 | tenantId: sessionMap["tenantId"].(string), 17 | userDataInAccessToken: sessionMap["userDataInAccessToken"].(map[string]interface{}), 18 | accessToken: sessionMap["accessToken"].(string), 19 | frontToken: sessionMap["frontToken"].(string), 20 | refreshToken: nil, 21 | antiCSRFToken: nil, 22 | accessTokenUpdated: sessionMap["accessTokenUpdated"].(bool), 23 | } 24 | 25 | if refreshToken, ok := sessionMap["refreshToken"].(map[string]interface{}); ok { 26 | session.refreshToken = &sessmodels.CreateOrRefreshAPIResponseToken{ 27 | Token: refreshToken["token"].(string), 28 | Expiry: uint64(refreshToken["expiry"].(float64)), 29 | CreatedTime: uint64(refreshToken["createdTime"].(float64)), 30 | } 31 | } 32 | 33 | if antiCsrfToken, ok := sessionMap["antiCsrfToken"].(string); ok { 34 | session.antiCSRFToken = &antiCsrfToken 35 | } 36 | 37 | session.recipeImpl = recipe.RecipeImpl 38 | 39 | return newSessionContainer(recipe.Config, session), nil 40 | } 41 | -------------------------------------------------------------------------------- /recipe/session/constants.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package session 17 | 18 | import "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" 19 | 20 | var AvailableTokenTransferMethods = []sessmodels.TokenTransferMethod{sessmodels.CookieTransferMethod, sessmodels.HeaderTransferMethod} 21 | 22 | const ( 23 | RefreshAPIPath = "/session/refresh" 24 | SignoutAPIPath = "/signout" 25 | 26 | AntiCSRF_VIA_TOKEN = "VIA_TOKEN" 27 | AntiCSRF_VIA_CUSTOM_HEADER = "VIA_CUSTOM_HEADER" 28 | AntiCSRF_NONE = "NONE" 29 | 30 | CookieSameSite_NONE = "none" 31 | CookieSameSite_LAX = "lax" 32 | CookieSameSite_STRICT = "strict" 33 | ) 34 | 35 | var JWKRefreshRateLimit = 500 36 | var protectedProps = []string{ 37 | "sub", 38 | "iat", 39 | "exp", 40 | "sessionHandle", 41 | "parentRefreshTokenHash1", 42 | "refreshTokenHash1", 43 | "antiCsrfToken", 44 | "rsub", 45 | "tId", 46 | } 47 | -------------------------------------------------------------------------------- /recipe/session/sessmodels/apiInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package sessmodels 17 | 18 | import "github.com/supertokens/supertokens-golang/supertokens" 19 | 20 | /** 21 | * We do not add a GeneralErrorResponse response to the refresh API 22 | * since it's not something that is directly called by the user on the 23 | * frontend anyway 24 | */ 25 | type APIInterface struct { 26 | RefreshPOST *func(options APIOptions, userContext supertokens.UserContext) (SessionContainer, error) 27 | SignOutPOST *func(sessionContainer SessionContainer, options APIOptions, userContext supertokens.UserContext) (SignOutPOSTResponse, error) 28 | VerifySession *func(verifySessionOptions *VerifySessionOptions, options APIOptions, userContext supertokens.UserContext) (SessionContainer, error) 29 | } 30 | 31 | type SignOutPOSTResponse struct { 32 | OK *struct{} 33 | GeneralError *supertokens.GeneralErrorResponse 34 | } 35 | -------------------------------------------------------------------------------- /recipe/dashboard/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package dashboard 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | "github.com/supertokens/supertokens-golang/test/unittesting" 23 | ) 24 | 25 | func resetAll() { 26 | supertokens.ResetForTest() 27 | } 28 | 29 | func BeforeEach() { 30 | unittesting.KillAllST() 31 | resetAll() 32 | unittesting.SetUpST() 33 | } 34 | 35 | func AfterEach() { 36 | unittesting.KillAllST() 37 | resetAll() 38 | unittesting.CleanST() 39 | } 40 | 41 | func canRunTest(t *testing.T) bool { 42 | querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") 43 | if err != nil { 44 | t.Error(err.Error()) 45 | } 46 | cdiVersion, err := querier.GetQuerierAPIVersion() 47 | if err != nil { 48 | t.Error(err.Error()) 49 | } 50 | if unittesting.MaxVersion("2.13", cdiVersion) == "2.13" { 51 | return false 52 | } 53 | return true 54 | } 55 | -------------------------------------------------------------------------------- /recipe/emailpassword/loginmethods_test.go: -------------------------------------------------------------------------------- 1 | package emailpassword 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "net/http" 7 | "net/http/httptest" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/assert" 11 | "github.com/supertokens/supertokens-golang/supertokens" 12 | "github.com/supertokens/supertokens-golang/test/unittesting" 13 | ) 14 | 15 | func TestLoginMethodsReturnEmptyProviderArray(t *testing.T) { 16 | configValue := supertokens.TypeInput{ 17 | Supertokens: &supertokens.ConnectionInfo{ 18 | ConnectionURI: "http://localhost:8080", 19 | }, 20 | AppInfo: supertokens.AppInfo{ 21 | APIDomain: "api.supertokens.io", 22 | AppName: "SuperTokens", 23 | WebsiteDomain: "supertokens.io", 24 | }, 25 | RecipeList: []supertokens.Recipe{ 26 | Init(nil), 27 | }, 28 | } 29 | 30 | BeforeEach() 31 | unittesting.StartUpST("localhost", "8080") 32 | defer AfterEach() 33 | err := supertokens.Init(configValue) 34 | if err != nil { 35 | t.Error(err.Error()) 36 | } 37 | mux := http.NewServeMux() 38 | testServer := httptest.NewServer(supertokens.Middleware(mux)) 39 | defer testServer.Close() 40 | 41 | resp, err := http.Get(testServer.URL + "/auth/loginmethods") 42 | if err != nil { 43 | t.Error(err.Error()) 44 | } 45 | assert.Equal(t, http.StatusOK, resp.StatusCode) 46 | 47 | respObj := map[string]interface{}{} 48 | respBytes, err := ioutil.ReadAll(resp.Body) 49 | assert.Nil(t, err) 50 | err = json.Unmarshal(respBytes, &respObj) 51 | assert.Nil(t, err) 52 | providersArr, ok := respObj["thirdParty"].(map[string]interface{})["providers"] 53 | assert.True(t, ok) 54 | assert.NotNil(t, providersArr) 55 | } 56 | -------------------------------------------------------------------------------- /recipe/openid/api/implementation.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/openid/openidmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func MakeAPIImplementation() openidmodels.APIInterface { 24 | 25 | getOpenIdDiscoveryConfigurationGET := func(options openidmodels.APIOptions, userContext supertokens.UserContext) (openidmodels.GetOpenIdDiscoveryConfigurationAPIResponse, error) { 26 | resp, err := (*options.RecipeImplementation.GetOpenIdDiscoveryConfiguration)(userContext) 27 | if err != nil { 28 | return openidmodels.GetOpenIdDiscoveryConfigurationAPIResponse{}, err 29 | } 30 | return openidmodels.GetOpenIdDiscoveryConfigurationAPIResponse{ 31 | OK: resp.OK, 32 | }, nil 33 | } 34 | 35 | return openidmodels.APIInterface{ 36 | GetOpenIdDiscoveryConfigurationGET: &getOpenIdDiscoveryConfigurationGET, 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /recipe/jwt/api/implementation.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "fmt" 20 | "github.com/supertokens/supertokens-golang/recipe/jwt/jwtmodels" 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | func MakeAPIImplementation() jwtmodels.APIInterface { 25 | getJWKSGET := func(options jwtmodels.APIOptions, userContext supertokens.UserContext) (jwtmodels.GetJWKSAPIResponse, error) { 26 | resp, err := (*options.RecipeImplementation.GetJWKS)(userContext) 27 | if err != nil { 28 | return jwtmodels.GetJWKSAPIResponse{}, err 29 | } 30 | options.Res.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, must-revalidate", resp.OK.ValidityInSeconds)) 31 | return jwtmodels.GetJWKSAPIResponse{ 32 | OK: &struct { 33 | Keys []jwtmodels.JsonWebKeys 34 | }{ 35 | Keys: resp.OK.Keys, 36 | }, 37 | }, nil 38 | } 39 | return jwtmodels.APIInterface{ 40 | GetJWKSGET: &getJWKSGET, 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /recipe/thirdparty/api/appleRedirect.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func AppleRedirectHandler(apiImplementation tpmodels.APIInterface, options tpmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.AppleRedirectHandlerPOST == nil || (*apiImplementation.AppleRedirectHandlerPOST) == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | 29 | err := options.Req.ParseForm() 30 | if err != nil { 31 | return err 32 | } 33 | 34 | formPostInfoFromProvider := map[string]interface{}{} 35 | 36 | for key, value := range options.Req.PostForm { 37 | formPostInfoFromProvider[key] = value[0] 38 | } 39 | 40 | return (*apiImplementation.AppleRedirectHandlerPOST)(formPostInfoFromProvider, options, userContext) 41 | } 42 | -------------------------------------------------------------------------------- /recipe/dashboard/api/userdetails/userDelete.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userdetails 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | type userDeleteResponse struct { 24 | Status string `json:"status"` 25 | } 26 | 27 | func UserDelete(apiInterface dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (userDeleteResponse, error) { 28 | req := options.Req 29 | userId := req.URL.Query().Get("userId") 30 | 31 | if userId == "" { 32 | return userDeleteResponse{}, supertokens.BadInputError{ 33 | Msg: "Missing required parameter 'userId'", 34 | } 35 | } 36 | 37 | deleteError := supertokens.DeleteUser(userId) 38 | 39 | if deleteError != nil { 40 | return userDeleteResponse{}, deleteError 41 | } 42 | 43 | return userDeleteResponse{ 44 | Status: "OK", 45 | }, nil 46 | } 47 | -------------------------------------------------------------------------------- /ingredients/emaildelivery/smtpmodels.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package emaildelivery 18 | 19 | import ( 20 | "crypto/tls" 21 | 22 | "github.com/supertokens/supertokens-golang/supertokens" 23 | ) 24 | 25 | type SMTPSettings struct { 26 | Host string 27 | From SMTPFrom 28 | Port int 29 | Username *string 30 | Password string 31 | Secure bool 32 | TLSConfig *tls.Config 33 | } 34 | 35 | type SMTPFrom struct { 36 | Name string 37 | Email string 38 | } 39 | 40 | type EmailContent struct { 41 | Body string 42 | IsHtml bool 43 | Subject string 44 | ToEmail string 45 | } 46 | 47 | type SMTPInterface struct { 48 | SendRawEmail *func(input EmailContent, userContext supertokens.UserContext) error 49 | GetContent *func(input EmailType, userContext supertokens.UserContext) (EmailContent, error) 50 | } 51 | 52 | type SMTPServiceConfig struct { 53 | Settings SMTPSettings 54 | Override func(originalImplementation SMTPInterface) SMTPInterface 55 | } 56 | -------------------------------------------------------------------------------- /ingredients/smsdelivery/models.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smsdelivery 18 | 19 | import "github.com/supertokens/supertokens-golang/supertokens" 20 | 21 | type SmsDeliveryInterface struct { 22 | SendSms *func(input SmsType, userContext supertokens.UserContext) error 23 | } 24 | 25 | type TypeInput struct { 26 | Service *SmsDeliveryInterface 27 | Override func(originalImplementation SmsDeliveryInterface) SmsDeliveryInterface 28 | } 29 | 30 | type TypeInputWithService struct { 31 | Service SmsDeliveryInterface 32 | Override func(originalImplementation SmsDeliveryInterface) SmsDeliveryInterface 33 | } 34 | 35 | type SmsType struct { 36 | PasswordlessLogin *PasswordlessLoginType 37 | } 38 | 39 | type PasswordlessLoginType struct { 40 | PhoneNumber string 41 | UserInputCode *string 42 | UrlWithLinkCode *string 43 | CodeLifetime uint64 44 | PreAuthSessionId string 45 | TenantId string 46 | } 47 | 48 | type User struct { 49 | ID string 50 | PhoneNumber string 51 | } 52 | -------------------------------------------------------------------------------- /recipe/userroles/config_test.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userroles 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/stretchr/testify/assert" 22 | "github.com/supertokens/supertokens-golang/supertokens" 23 | "github.com/supertokens/supertokens-golang/test/unittesting" 24 | ) 25 | 26 | func TestRecipeWithoutConfig(t *testing.T) { 27 | BeforeEach() 28 | unittesting.StartUpST("localhost", "8080") 29 | defer AfterEach() 30 | 31 | supertokens.Init(supertokens.TypeInput{ 32 | Supertokens: &supertokens.ConnectionInfo{ 33 | ConnectionURI: "http://localhost:8080", 34 | }, 35 | AppInfo: supertokens.AppInfo{ 36 | AppName: "Supertokens Demo", 37 | APIDomain: "https://api.supertokens.io", 38 | WebsiteDomain: "supertokens.io", 39 | }, 40 | RecipeList: []supertokens.Recipe{ 41 | Init(nil), 42 | }, 43 | }) 44 | 45 | if !canRunTest(t) { 46 | return 47 | } 48 | 49 | instance, err := getRecipeInstanceOrThrowError() 50 | assert.NoError(t, err) 51 | assert.NotNil(t, instance) 52 | } 53 | -------------------------------------------------------------------------------- /recipe/dashboard/api/search/tagsGet.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package search 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | type searchTagsResponse struct { 24 | Status string `json:"status"` 25 | Tags []interface{} `json:"tags"` 26 | } 27 | 28 | func SearchTagsGet(apiImplementation dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (searchTagsResponse, error) { 29 | querier, querierErr := supertokens.GetNewQuerierInstanceOrThrowError("dashboard") 30 | 31 | if querierErr != nil { 32 | return searchTagsResponse{}, querierErr 33 | } 34 | 35 | apiResponse, apiErr := querier.SendGetRequest("/user/search/tags", nil, userContext) 36 | if apiErr != nil { 37 | return searchTagsResponse{}, apiErr 38 | } 39 | 40 | return searchTagsResponse{ 41 | Status: "OK", 42 | Tags: apiResponse["tags"].([]interface{}), 43 | }, nil 44 | } 45 | -------------------------------------------------------------------------------- /recipe/emailpassword/emaildelivery/smtpService/serviceImplementation.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smtpService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeServiceImplementation(settings emaildelivery.SMTPSettings) emaildelivery.SMTPInterface { 27 | sendRawEmail := func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { 28 | return emaildelivery.SendSMTPEmail(settings, input) 29 | } 30 | 31 | getContent := func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { 32 | if input.PasswordReset != nil { 33 | return getPasswordResetEmailContent(*input.PasswordReset) 34 | } else { 35 | return emaildelivery.EmailContent{}, errors.New("should never come here") 36 | } 37 | } 38 | 39 | return emaildelivery.SMTPInterface{ 40 | SendRawEmail: &sendRawEmail, 41 | GetContent: &getContent, 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /recipe/emailverification/emaildelivery/smtpService/serviceImplementation.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smtpService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeServiceImplementation(settings emaildelivery.SMTPSettings) emaildelivery.SMTPInterface { 27 | sendRawEmail := func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { 28 | return emaildelivery.SendSMTPEmail(settings, input) 29 | } 30 | 31 | getContent := func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { 32 | if input.EmailVerification != nil { 33 | return getEmailVerifyEmailContent(*input.EmailVerification) 34 | } else { 35 | return emaildelivery.EmailContent{}, errors.New("should never come here") 36 | } 37 | } 38 | 39 | return emaildelivery.SMTPInterface{ 40 | SendRawEmail: &sendRawEmail, 41 | GetContent: &getContent, 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /recipe/passwordless/emaildelivery/smtpService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smtpService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeSMTPService(config emaildelivery.SMTPServiceConfig) *emaildelivery.EmailDeliveryInterface { 27 | serviceImpl := MakeServiceImplementation(config.Settings) 28 | 29 | if config.Override != nil { 30 | serviceImpl = config.Override(serviceImpl) 31 | } 32 | 33 | sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { 34 | if input.PasswordlessLogin != nil { 35 | content, err := (*serviceImpl.GetContent)(input, userContext) 36 | if err != nil { 37 | return err 38 | } 39 | return (*serviceImpl.SendRawEmail)(content, userContext) 40 | } else { 41 | return errors.New("should never come here") 42 | } 43 | } 44 | 45 | return &emaildelivery.EmailDeliveryInterface{ 46 | SendEmail: &sendEmail, 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /recipe/emailpassword/emaildelivery/smtpService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smtpService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeSMTPService(config emaildelivery.SMTPServiceConfig) *emaildelivery.EmailDeliveryInterface { 27 | serviceImpl := MakeServiceImplementation(config.Settings) 28 | 29 | if config.Override != nil { 30 | serviceImpl = config.Override(serviceImpl) 31 | } 32 | 33 | sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { 34 | if input.PasswordReset != nil { 35 | content, err := (*serviceImpl.GetContent)(input, userContext) 36 | if err != nil { 37 | return err 38 | } 39 | return (*serviceImpl.SendRawEmail)(content, userContext) 40 | 41 | } else { 42 | return errors.New("should never come here") 43 | } 44 | } 45 | 46 | return &emaildelivery.EmailDeliveryInterface{ 47 | SendEmail: &sendEmail, 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /recipe/emailverification/emaildelivery/smtpService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smtpService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeSMTPService(config emaildelivery.SMTPServiceConfig) *emaildelivery.EmailDeliveryInterface { 27 | serviceImpl := MakeServiceImplementation(config.Settings) 28 | 29 | if config.Override != nil { 30 | serviceImpl = config.Override(serviceImpl) 31 | } 32 | 33 | sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { 34 | if input.EmailVerification != nil { 35 | content, err := (*serviceImpl.GetContent)(input, userContext) 36 | if err != nil { 37 | return err 38 | } 39 | return (*serviceImpl.SendRawEmail)(content, userContext) 40 | } else { 41 | return errors.New("should never come here") 42 | } 43 | } 44 | 45 | return &emaildelivery.EmailDeliveryInterface{ 46 | SendEmail: &sendEmail, 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /recipe/passwordless/emaildelivery/smtpService/serviceImplementation.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smtpService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeServiceImplementation(settings emaildelivery.SMTPSettings) emaildelivery.SMTPInterface { 27 | sendRawEmail := func(input emaildelivery.EmailContent, userContext supertokens.UserContext) error { 28 | return emaildelivery.SendSMTPEmail(settings, input) 29 | } 30 | 31 | getContent := func(input emaildelivery.EmailType, userContext supertokens.UserContext) (emaildelivery.EmailContent, error) { 32 | if input.PasswordlessLogin != nil { 33 | return getPasswordlessLoginEmailContent(*input.PasswordlessLogin) 34 | } else { 35 | return emaildelivery.EmailContent{}, errors.New("should never come here") 36 | } 37 | } 38 | 39 | return emaildelivery.SMTPInterface{ 40 | SendRawEmail: &sendRawEmail, 41 | GetContent: &getContent, 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /recipe/jwt/api/getJWKS.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/jwt/jwtmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func GetJWKS(apiImplementation jwtmodels.APIInterface, options jwtmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.GetJWKSGET == nil || (*apiImplementation.GetJWKSGET) == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | 29 | response, err := (*apiImplementation.GetJWKSGET)(options, userContext) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | if response.GeneralError != nil { 35 | return supertokens.Send200Response(options.Res, supertokens.ConvertGeneralErrorToJsonResponse(*response.GeneralError)) 36 | } else if response.OK != nil { 37 | options.Res.Header().Set("Access-Control-Allow-Origin", "*") 38 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 39 | "keys": response.OK.Keys, 40 | }) 41 | } 42 | return supertokens.ErrorIfNoResponse(options.Res) 43 | } 44 | -------------------------------------------------------------------------------- /recipe/session/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package session 17 | 18 | import ( 19 | "net/http" 20 | 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | "github.com/supertokens/supertokens-golang/test/unittesting" 23 | ) 24 | 25 | // Testing constants 26 | var didGetSessionCallCore = false 27 | var returnedFromCache chan bool = make(chan bool, 1000) 28 | var urlsAttemptedForJWKSFetch []string 29 | 30 | func resetAll() { 31 | supertokens.ResetForTest() 32 | didGetSessionCallCore = false 33 | returnedFromCache = make(chan bool, 1000) 34 | urlsAttemptedForJWKSFetch = []string{} 35 | jwksCache = nil 36 | } 37 | 38 | func BeforeEach() { 39 | unittesting.KillAllST() 40 | resetAll() 41 | unittesting.SetUpST() 42 | } 43 | 44 | func AfterEach() { 45 | unittesting.KillAllST() 46 | resetAll() 47 | unittesting.CleanST() 48 | } 49 | 50 | type fakeRes struct{} 51 | 52 | func (f fakeRes) Header() http.Header { 53 | return http.Header{} 54 | } 55 | 56 | func (f fakeRes) Write(body []byte) (int, error) { 57 | return len(body), nil 58 | } 59 | 60 | func (f fakeRes) WriteHeader(statusCode int) {} 61 | -------------------------------------------------------------------------------- /recipe/thirdparty/providers/boxysaml.go: -------------------------------------------------------------------------------- 1 | package providers 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" 5 | "github.com/supertokens/supertokens-golang/supertokens" 6 | ) 7 | 8 | func BoxySaml(input tpmodels.ProviderInput) *tpmodels.TypeProvider { 9 | if input.Config.Name == "" { 10 | input.Config.Name = "SAML" 11 | } 12 | 13 | if input.Config.UserInfoMap.FromUserInfoAPI.UserId == "" { 14 | input.Config.UserInfoMap.FromUserInfoAPI.UserId = "id" 15 | } 16 | if input.Config.UserInfoMap.FromUserInfoAPI.Email == "" { 17 | input.Config.UserInfoMap.FromUserInfoAPI.Email = "email" 18 | } 19 | 20 | oOverride := input.Override 21 | 22 | input.Override = func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { 23 | oGetConfig := originalImplementation.GetConfigForClientType 24 | originalImplementation.GetConfigForClientType = func(clientType *string, userContext supertokens.UserContext) (tpmodels.ProviderConfigForClientType, error) { 25 | config, err := oGetConfig(clientType, userContext) 26 | if err != nil { 27 | return tpmodels.ProviderConfigForClientType{}, err 28 | } 29 | 30 | boxyURL, ok := config.AdditionalConfig["boxyURL"].(string) 31 | if ok { 32 | if config.AuthorizationEndpoint == "" { 33 | config.AuthorizationEndpoint = boxyURL + "/api/oauth/authorize" 34 | } 35 | 36 | if config.TokenEndpoint == "" { 37 | config.TokenEndpoint = boxyURL + "/api/oauth/token" 38 | } 39 | 40 | if config.UserInfoEndpoint == "" { 41 | config.UserInfoEndpoint = boxyURL + "/api/oauth/userinfo" 42 | } 43 | } 44 | 45 | return config, nil 46 | } 47 | 48 | if oOverride != nil { 49 | originalImplementation = oOverride(originalImplementation) 50 | } 51 | return originalImplementation 52 | } 53 | 54 | return NewProvider(input) 55 | } 56 | -------------------------------------------------------------------------------- /recipe/session/jwksMemory_test.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "runtime" 5 | "testing" 6 | "time" 7 | 8 | "github.com/stretchr/testify/assert" 9 | "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" 10 | "github.com/supertokens/supertokens-golang/supertokens" 11 | "github.com/supertokens/supertokens-golang/test/unittesting" 12 | ) 13 | 14 | func TestThatThereIsNoMemoryLeakWithJWKSCache(t *testing.T) { 15 | configValue := supertokens.TypeInput{ 16 | Supertokens: &supertokens.ConnectionInfo{ 17 | ConnectionURI: "http://localhost:8080", 18 | }, 19 | AppInfo: supertokens.AppInfo{ 20 | AppName: "SuperTokens", 21 | WebsiteDomain: "supertokens.io", 22 | APIDomain: "api.supertokens.io", 23 | }, 24 | RecipeList: []supertokens.Recipe{ 25 | Init(&sessmodels.TypeInput{ 26 | JWKSRefreshIntervalSec: &[]uint64{0}[0], 27 | }), 28 | }, 29 | } 30 | BeforeEach() 31 | unittesting.StartUpST("localhost", "8080") 32 | defer AfterEach() 33 | err := supertokens.Init(configValue) 34 | if err != nil { 35 | t.Error(err.Error()) 36 | } 37 | 38 | testServer := GetTestServer(t) 39 | defer func() { 40 | testServer.Close() 41 | }() 42 | 43 | sess, err := CreateNewSessionWithoutRequestResponse("public", "testuser", map[string]interface{}{}, map[string]interface{}{}, nil) 44 | assert.NoError(t, err) 45 | 46 | accessToken := sess.GetAccessToken() 47 | 48 | _, err = GetSessionWithoutRequestResponse(accessToken, nil, nil) 49 | assert.NoError(t, err) 50 | 51 | numGoroutinesBeforeJWKSRefresh := runtime.NumGoroutine() 52 | 53 | for i := 0; i < 100; i++ { 54 | _, err = GetSessionWithoutRequestResponse(accessToken, nil, nil) 55 | assert.NoError(t, err) 56 | 57 | time.Sleep(10 * time.Millisecond) 58 | } 59 | 60 | time.Sleep(1 * time.Second) 61 | assert.Equal(t, numGoroutinesBeforeJWKSRefresh, runtime.NumGoroutine()) 62 | } 63 | -------------------------------------------------------------------------------- /recipe/passwordless/smsdelivery/backwardCompatibilityService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package backwardCompatibilityService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/smsdelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeBackwardCompatibilityService(createAndSendCustomSms func(phoneNumber string, userInputCode *string, urlWithLinkCode *string, codeLifetime uint64, preAuthSessionId string, userContext supertokens.UserContext) error) smsdelivery.SmsDeliveryInterface { 27 | sendSms := func(input smsdelivery.SmsType, userContext supertokens.UserContext) error { 28 | if input.PasswordlessLogin != nil { 29 | return createAndSendCustomSms( 30 | input.PasswordlessLogin.PhoneNumber, 31 | input.PasswordlessLogin.UserInputCode, 32 | input.PasswordlessLogin.UrlWithLinkCode, 33 | input.PasswordlessLogin.CodeLifetime, 34 | input.PasswordlessLogin.PreAuthSessionId, 35 | userContext, 36 | ) 37 | } else { 38 | return errors.New("should never come here") 39 | } 40 | } 41 | 42 | return smsdelivery.SmsDeliveryInterface{ 43 | SendSms: &sendSms, 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /examples/with-twirp/cmd/client/main.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Twitch Interactive, Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may not 4 | // use this file except in compliance with the License. A copy of the License is 5 | // located at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed on 10 | // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package main 15 | 16 | import ( 17 | "context" 18 | "fmt" 19 | "log" 20 | "net/http" 21 | 22 | "github.com/supertokens/supertokens-golang/examples/with-twirp/haberdasher" 23 | "github.com/twitchtv/twirp" 24 | ) 25 | 26 | func main() { 27 | // Create a client capable of talking to a Haberdasher server running on 28 | // localhost. This is a generated function call. 29 | client := haberdasher.NewHaberdasherJSONClient("http://localhost:3001", &http.Client{}) 30 | 31 | var ( 32 | hat *haberdasher.Hat 33 | err error 34 | ) 35 | 36 | // Call the client's 'MakeHat' method, retrying up to five times. 37 | for i := 0; i < 5; i++ { 38 | hat, err = client.MakeHat(context.Background(), &haberdasher.Size{Inches: 12}) 39 | if err != nil { 40 | // We got an error. Is it a twirp Error? 41 | if twerr, ok := err.(twirp.Error); ok { 42 | // Twirp errors support custom, arbitrary metadata. For example, a 43 | // server could inform a client that a particular error is retryable. 44 | if twerr.Meta("retryable") != "" { 45 | log.Printf("got error %q, retrying", twerr) 46 | continue 47 | } 48 | } 49 | log.Fatal(err) 50 | } else { 51 | break 52 | } 53 | } 54 | 55 | // Print out the response. 56 | fmt.Printf("%+v\n", hat) 57 | } 58 | -------------------------------------------------------------------------------- /recipe/emailverification/emaildelivery/backwardCompatibilityService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package backwardCompatibilityService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/recipe/emailverification/evmodels" 24 | "github.com/supertokens/supertokens-golang/supertokens" 25 | ) 26 | 27 | func MakeBackwardCompatibilityService(appInfo supertokens.NormalisedAppinfo, createAndSendCustomEmail func(user evmodels.User, emailVerificationURLWithToken string, userContext supertokens.UserContext)) emaildelivery.EmailDeliveryInterface { 28 | sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { 29 | if input.EmailVerification != nil { 30 | createAndSendCustomEmail(evmodels.User{ 31 | ID: input.EmailVerification.User.ID, 32 | Email: input.EmailVerification.User.Email, 33 | }, input.EmailVerification.EmailVerifyLink, userContext) 34 | } else { 35 | return errors.New("should never come here") 36 | } 37 | return nil 38 | } 39 | 40 | return emaildelivery.EmailDeliveryInterface{ 41 | SendEmail: &sendEmail, 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /recipe/passwordless/smsdelivery/twilioService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package twilioService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/smsdelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeTwilioService(config smsdelivery.TwilioServiceConfig) (*smsdelivery.SmsDeliveryInterface, error) { 27 | config, err := smsdelivery.NormaliseTwilioServiceConfig(config) 28 | 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | serviceImpl := MakeServiceImplementation(config.Settings) 34 | 35 | if config.Override != nil { 36 | serviceImpl = config.Override(serviceImpl) 37 | } 38 | 39 | sendSms := func(input smsdelivery.SmsType, userContext supertokens.UserContext) error { 40 | if input.PasswordlessLogin != nil { 41 | content, err := (*serviceImpl.GetContent)(input, userContext) 42 | if err != nil { 43 | return err 44 | } 45 | return (*serviceImpl.SendRawSms)(content, userContext) 46 | 47 | } else { 48 | return errors.New("should never come here") 49 | } 50 | } 51 | 52 | return &smsdelivery.SmsDeliveryInterface{ 53 | SendSms: &sendSms, 54 | }, nil 55 | } 56 | -------------------------------------------------------------------------------- /test/test-server/utils.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/emailverification/evclaims" 5 | "github.com/supertokens/supertokens-golang/recipe/session/claims" 6 | ) 7 | 8 | var testClaimSetups map[string]*claims.TypeSessionClaim 9 | var testClaimValidators map[string]map[string]func(args ...any) claims.SessionClaimValidator 10 | 11 | func init() { 12 | testClaimSetups = make(map[string]*claims.TypeSessionClaim) 13 | testClaimValidators = make(map[string]map[string]func(args ...any) claims.SessionClaimValidator) 14 | 15 | addBuiltinClaimValidators() 16 | } 17 | 18 | func addBuiltinClaimValidators() { 19 | addEmailVerificationClaimAndValidators() 20 | } 21 | 22 | func addEmailVerificationClaimAndValidators() { 23 | evClaim := evclaims.EmailVerificationClaim 24 | testClaimSetups[evClaim.Key] = evClaim 25 | testClaimValidators[evClaim.Key] = map[string]func(args ...any) claims.SessionClaimValidator{} 26 | 27 | testClaimValidators[evClaim.Key]["isVerified"] = func(args ...any) claims.SessionClaimValidator { 28 | if len(args) == 0 { 29 | return evclaims.EmailVerificationClaimValidators.IsVerified(nil, nil) 30 | } else if len(args) == 1 { 31 | arg1 := int64(args[0].(float64)) 32 | return evclaims.EmailVerificationClaimValidators.IsVerified(&arg1, nil) 33 | } else { 34 | arg1 := int64(args[0].(float64)) 35 | arg2 := int64(args[1].(float64)) 36 | return evclaims.EmailVerificationClaimValidators.IsVerified(&arg1, &arg2) 37 | } 38 | } 39 | } 40 | 41 | func deserializeValidator(serializedValidator map[string]interface{}) func(args ...any) claims.SessionClaimValidator { 42 | key := serializedValidator["key"].(string) 43 | if validators, ok := testClaimValidators[key]; ok { 44 | validatorName := serializedValidator["validatorName"].(string) 45 | if validator, ok := validators[validatorName]; ok { 46 | return validator 47 | } 48 | } 49 | return nil 50 | } 51 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Summary of change 2 | 3 | (A few sentences about this PR) 4 | 5 | ## Related issues 6 | 7 | - Link to issue1 here 8 | - Link to issue1 here 9 | 10 | ## Test Plan 11 | 12 | (Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Bonus points for screenshots and videos!) 13 | 14 | ## Documentation changes 15 | 16 | (If relevant, please create a PR in our [docs repo](https://github.com/supertokens/docs), or create a checklist here highlighting the necessary changes) 17 | 18 | ## Checklist for important updates 19 | 20 | - [ ] Changelog has been updated 21 | - [ ] `coreDriverInterfaceSupported.json` file has been updated (if needed) 22 | - Along with the associated array in `supertokens/constants.go` 23 | - [ ] `frontendDriverInterfaceSupported.json` file has been updated (if needed) 24 | - [ ] Changes to the version if needed 25 | - In `supertokens/constants.go > version variable` 26 | - [ ] Had installed and ran the pre-commit hook 27 | - [ ] If new thirdparty provider is added, 28 | - [ ] update switch statement in `recipe/thirdparty/providers/config_utils.go` file, `createProvider` function. 29 | - [ ] add an icon on the user management dashboard. 30 | - [ ] Issue this PR against the latest non released version branch. 31 | - To know which one it is, run find the latest released tag (`git tag`) in the format `vX.Y.Z`, and then find the latest branch (`git branch --all`) whose `X.Y` is greater than the latest released tag. 32 | - If no such branch exists, then create one from the latest released branch. 33 | - [ ] If access token structure has changed 34 | - Modified test in `session/accessTokenVersions_test.go` to account for any new claims that are optional or omitted by the core 35 | 36 | ## Remaining TODOs for this PR 37 | 38 | - [ ] Item1 39 | - [ ] Item2 40 | -------------------------------------------------------------------------------- /examples/with-twirp/internal/hooks/logging.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Twitch Interactive, Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may not 4 | // use this file except in compliance with the License. A copy of the License is 5 | // located at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed on 10 | // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package hooks 15 | 16 | import ( 17 | "context" 18 | "fmt" 19 | "io" 20 | "time" 21 | 22 | "github.com/twitchtv/twirp" 23 | ) 24 | 25 | var ctxKey = new(int) 26 | 27 | // LoggingHooks creates a new twirp.ServerHooks which logs requests as they are 28 | // routed to Twirp, and logs responses (including response time) when they are 29 | // sent. 30 | // 31 | // This is a demonstration showing how you can use context accessors with hooks. 32 | func LoggingHooks(w io.Writer) *twirp.ServerHooks { 33 | return &twirp.ServerHooks{ 34 | RequestReceived: func(ctx context.Context) (context.Context, error) { 35 | startTime := time.Now() 36 | ctx = context.WithValue(ctx, ctxKey, startTime) 37 | return ctx, nil 38 | }, 39 | RequestRouted: func(ctx context.Context) (context.Context, error) { 40 | svc, _ := twirp.ServiceName(ctx) 41 | meth, _ := twirp.MethodName(ctx) 42 | fmt.Fprintf(w, "received req svc=%q method=%q\n", svc, meth) 43 | return ctx, nil 44 | }, 45 | ResponseSent: func(ctx context.Context) { 46 | startTime := ctx.Value(ctxKey).(time.Time) 47 | svc, _ := twirp.ServiceName(ctx) 48 | meth, _ := twirp.MethodName(ctx) 49 | fmt.Fprintf(w, "response sent svc=%q method=%q time=%q\n", svc, meth, time.Since(startTime)) 50 | }, 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /recipe/userroles/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userroles 17 | 18 | import ( 19 | "net/http" 20 | "testing" 21 | 22 | "github.com/supertokens/supertokens-golang/supertokens" 23 | "github.com/supertokens/supertokens-golang/test/unittesting" 24 | ) 25 | 26 | func resetAll() { 27 | supertokens.ResetForTest() 28 | } 29 | 30 | func BeforeEach() { 31 | unittesting.KillAllST() 32 | resetAll() 33 | unittesting.SetUpST() 34 | } 35 | 36 | func AfterEach() { 37 | unittesting.KillAllST() 38 | resetAll() 39 | unittesting.CleanST() 40 | } 41 | 42 | func canRunTest(t *testing.T) bool { 43 | querier, err := supertokens.GetNewQuerierInstanceOrThrowError("") 44 | if err != nil { 45 | t.Error(err.Error()) 46 | } 47 | cdiVersion, err := querier.GetQuerierAPIVersion() 48 | if err != nil { 49 | t.Error(err.Error()) 50 | } 51 | if unittesting.MaxVersion("2.13", cdiVersion) == "2.13" { 52 | return false 53 | } 54 | return true 55 | } 56 | 57 | type fakeRes struct{} 58 | 59 | func (f fakeRes) Header() http.Header { 60 | return http.Header{} 61 | } 62 | 63 | func (f fakeRes) Write(body []byte) (int, error) { 64 | return len(body), nil 65 | } 66 | 67 | func (f fakeRes) WriteHeader(statusCode int) {} 68 | -------------------------------------------------------------------------------- /recipe/passwordless/emaildelivery/backwardCompatibilityService/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package backwardCompatibilityService 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/ingredients/emaildelivery" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func MakeBackwardCompatibilityService(appInfo supertokens.NormalisedAppinfo, createAndSendCustomEmail func(email string, userInputCode *string, urlWithLinkCode *string, codeLifetime uint64, preAuthSessionId string, userContext supertokens.UserContext) error) emaildelivery.EmailDeliveryInterface { 27 | sendEmail := func(input emaildelivery.EmailType, userContext supertokens.UserContext) error { 28 | if input.PasswordlessLogin != nil { 29 | return createAndSendCustomEmail( 30 | input.PasswordlessLogin.Email, 31 | input.PasswordlessLogin.UserInputCode, 32 | input.PasswordlessLogin.UrlWithLinkCode, 33 | input.PasswordlessLogin.CodeLifetime, 34 | input.PasswordlessLogin.PreAuthSessionId, 35 | userContext, 36 | ) 37 | } else { 38 | return errors.New("should never come here") 39 | } 40 | } 41 | 42 | return emaildelivery.EmailDeliveryInterface{ 43 | SendEmail: &sendEmail, 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /recipe/jwt/main.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwt 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/jwt/jwtmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func Init(config *jwtmodels.TypeInput) supertokens.Recipe { 24 | return recipeInit(config) 25 | } 26 | 27 | func CreateJWT(payload map[string]interface{}, validitySecondsPointer *uint64, useStaticSigningKey *bool, userContext ...supertokens.UserContext) (jwtmodels.CreateJWTResponse, error) { 28 | instance, err := getRecipeInstanceOrThrowError() 29 | if err != nil { 30 | return jwtmodels.CreateJWTResponse{}, err 31 | } 32 | if len(userContext) == 0 { 33 | userContext = append(userContext, &map[string]interface{}{}) 34 | } 35 | return (*instance.RecipeImpl.CreateJWT)(payload, validitySecondsPointer, useStaticSigningKey, userContext[0]) 36 | } 37 | 38 | func GetJWKS(userContext ...supertokens.UserContext) (jwtmodels.GetJWKSResponse, error) { 39 | instance, err := getRecipeInstanceOrThrowError() 40 | if err != nil { 41 | return jwtmodels.GetJWKSResponse{}, err 42 | } 43 | if len(userContext) == 0 { 44 | userContext = append(userContext, &map[string]interface{}{}) 45 | } 46 | return (*instance.RecipeImpl.GetJWKS)(userContext[0]) 47 | } 48 | -------------------------------------------------------------------------------- /recipe/emailpassword/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package emailpassword 17 | 18 | import ( 19 | "net/http" 20 | "net/http/httptest" 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | "github.com/supertokens/supertokens-golang/supertokens" 25 | "github.com/supertokens/supertokens-golang/test/unittesting" 26 | ) 27 | 28 | func resetAll() { 29 | supertokens.ResetForTest() 30 | } 31 | 32 | func BeforeEach() { 33 | unittesting.KillAllST() 34 | resetAll() 35 | unittesting.SetUpST() 36 | } 37 | 38 | func AfterEach() { 39 | unittesting.KillAllST() 40 | resetAll() 41 | unittesting.CleanST() 42 | } 43 | 44 | func supertokensInitForTest(t *testing.T, recipes ...supertokens.Recipe) *httptest.Server { 45 | config := supertokens.TypeInput{ 46 | Supertokens: &supertokens.ConnectionInfo{ 47 | ConnectionURI: "http://localhost:8080", 48 | }, 49 | AppInfo: supertokens.AppInfo{ 50 | APIDomain: "api.supertokens.io", 51 | AppName: "SuperTokens", 52 | WebsiteDomain: "supertokens.io", 53 | }, 54 | RecipeList: recipes, 55 | } 56 | 57 | err := supertokens.Init(config) 58 | assert.NoError(t, err) 59 | 60 | mux := http.NewServeMux() 61 | testServer := httptest.NewServer(supertokens.Middleware(mux)) 62 | return testServer 63 | } 64 | -------------------------------------------------------------------------------- /recipe/passwordless/testingUtils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package passwordless 17 | 18 | import ( 19 | "net/http" 20 | "net/http/httptest" 21 | "testing" 22 | 23 | "github.com/stretchr/testify/assert" 24 | "github.com/supertokens/supertokens-golang/supertokens" 25 | "github.com/supertokens/supertokens-golang/test/unittesting" 26 | ) 27 | 28 | func resetAll() { 29 | supertokens.ResetForTest() 30 | } 31 | 32 | func BeforeEach() { 33 | unittesting.KillAllST() 34 | resetAll() 35 | unittesting.SetUpST() 36 | } 37 | 38 | func AfterEach() { 39 | unittesting.KillAllST() 40 | resetAll() 41 | unittesting.CleanST() 42 | } 43 | 44 | func supertokensInitForTest(t *testing.T, recipes ...supertokens.Recipe) *httptest.Server { 45 | config := supertokens.TypeInput{ 46 | Supertokens: &supertokens.ConnectionInfo{ 47 | ConnectionURI: "http://localhost:8080", 48 | }, 49 | AppInfo: supertokens.AppInfo{ 50 | APIDomain: "api.supertokens.io", 51 | AppName: "SuperTokens", 52 | WebsiteDomain: "supertokens.io", 53 | }, 54 | RecipeList: recipes, 55 | } 56 | 57 | err := supertokens.Init(config) 58 | assert.NoError(t, err) 59 | 60 | mux := http.NewServeMux() 61 | testServer := httptest.NewServer(supertokens.Middleware(mux)) 62 | return testServer 63 | } 64 | -------------------------------------------------------------------------------- /recipe/openid/api/getOpenIdDiscoveryConfiguration.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/openid/openidmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func GetOpenIdDiscoveryConfiguration(apiImplementation openidmodels.APIInterface, options openidmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.GetOpenIdDiscoveryConfigurationGET == nil || (*apiImplementation.GetOpenIdDiscoveryConfigurationGET) == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | 29 | response, err := (*apiImplementation.GetOpenIdDiscoveryConfigurationGET)(options, userContext) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | if response.OK != nil { 35 | options.Res.Header().Set("Access-Control-Allow-Origin", "*") 36 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 37 | "issuer": response.OK.Issuer, 38 | "jwks_uri": response.OK.Jwks_uri, 39 | }) 40 | } else if response.GeneralError != nil { 41 | return supertokens.Send200Response(options.Res, supertokens.ConvertGeneralErrorToJsonResponse(*response.GeneralError)) 42 | } 43 | return supertokens.ErrorIfNoResponse(options.Res) 44 | } 45 | -------------------------------------------------------------------------------- /recipe/emailpassword/api/emailExists.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/emailpassword/epmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func EmailExists(apiImplementation epmodels.APIInterface, tenantId string, options epmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.EmailExistsGET == nil || (*apiImplementation.EmailExistsGET) == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | email := options.Req.URL.Query().Get("email") 29 | if email == "" { 30 | return supertokens.BadInputError{Msg: "Please provide the email as a GET param"} 31 | } 32 | result, err := (*apiImplementation.EmailExistsGET)(email, tenantId, options, userContext) 33 | if err != nil { 34 | return err 35 | } 36 | if result.OK != nil { 37 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 38 | "status": "OK", 39 | "exists": result.OK.Exists, 40 | }) 41 | } else if result.GeneralError != nil { 42 | return supertokens.Send200Response(options.Res, supertokens.ConvertGeneralErrorToJsonResponse(*result.GeneralError)) 43 | } 44 | 45 | return supertokens.ErrorIfNoResponse(options.Res) 46 | } 47 | -------------------------------------------------------------------------------- /recipe/passwordless/api/doesEmailExist.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/passwordless/plessmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func DoesEmailExist(apiImplementation plessmodels.APIInterface, tenantId string, options plessmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.EmailExistsGET == nil || (*apiImplementation.EmailExistsGET) == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | email := options.Req.URL.Query().Get("email") 29 | if email == "" { 30 | return supertokens.BadInputError{Msg: "Please provide the email as a GET param"} 31 | } 32 | result, err := (*apiImplementation.EmailExistsGET)(email, tenantId, options, userContext) 33 | if err != nil { 34 | return err 35 | } 36 | if result.OK != nil { 37 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 38 | "status": "OK", 39 | "exists": result.OK.Exists, 40 | }) 41 | } else if result.GeneralError != nil { 42 | return supertokens.Send200Response(options.Res, supertokens.ConvertGeneralErrorToJsonResponse(*result.GeneralError)) 43 | } 44 | return supertokens.ErrorIfNoResponse(options.Res) 45 | } 46 | -------------------------------------------------------------------------------- /recipe/dashboard/dashboardmodels/models.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package dashboardmodels 17 | 18 | type TypeInput struct { 19 | ApiKey string 20 | Admins *[]string 21 | Override *OverrideStruct 22 | } 23 | 24 | type TypeAuthMode string 25 | 26 | const ( 27 | AuthModeEmailPassword TypeAuthMode = "email-password" 28 | AuthModeAPIKey TypeAuthMode = "api-key" 29 | ) 30 | 31 | type TypeNormalisedInput struct { 32 | ApiKey string 33 | Admins *[]string 34 | AuthMode TypeAuthMode 35 | Override OverrideStruct 36 | } 37 | 38 | type OverrideStruct struct { 39 | Functions func(originalImplementation RecipeInterface) RecipeInterface 40 | APIs func(originalImplementation APIInterface) APIInterface 41 | } 42 | 43 | type ThirdParty struct { 44 | Id string `json:"id"` 45 | UserId string `json:"userId"` 46 | } 47 | 48 | type UserType struct { 49 | Id string `json:"id,omitempty"` 50 | TimeJoined uint64 `json:"timeJoined,omitempty"` 51 | FirstName string `json:"firstName,omitempty"` 52 | LastName string `json:"lastName,omitempty"` 53 | Email string `json:"email,omitempty"` 54 | ThirdParty *ThirdParty `json:"thirdParty,omitempty"` 55 | Phone string `json:"phoneNumber,omitempty"` 56 | TenantIds []string `json:"tenantIds,omitempty"` 57 | } 58 | -------------------------------------------------------------------------------- /ingredients/smsdelivery/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smsdelivery 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/twilio/twilio-go" 23 | openapi "github.com/twilio/twilio-go/rest/api/v2010" 24 | ) 25 | 26 | type Ingredient struct { 27 | IngredientInterfaceImpl SmsDeliveryInterface 28 | } 29 | 30 | func MakeIngredient(config TypeInputWithService) Ingredient { 31 | result := Ingredient{ 32 | IngredientInterfaceImpl: config.Service, 33 | } 34 | 35 | if config.Override != nil { 36 | result.IngredientInterfaceImpl = config.Override(result.IngredientInterfaceImpl) 37 | } 38 | 39 | return result 40 | } 41 | 42 | func SendTwilioSms(settings TwilioSettings, content SMSContent) error { 43 | client := twilio.NewRestClientWithParams(twilio.ClientParams{ 44 | Username: settings.AccountSid, 45 | Password: settings.AuthToken, 46 | }) 47 | 48 | params := &openapi.CreateMessageParams{} 49 | params.SetTo(content.ToPhoneNumber) 50 | params.SetBody(content.Body) 51 | 52 | if settings.From != "" { 53 | params.SetFrom(settings.From) 54 | } else if settings.MessagingServiceSid != "" { 55 | params.SetMessagingServiceSid(settings.MessagingServiceSid) 56 | } else { 57 | return errors.New("should not come here") 58 | } 59 | 60 | _, err := client.Api.CreateMessage(params) 61 | 62 | return err 63 | } 64 | -------------------------------------------------------------------------------- /recipe/thirdparty/providers/googleWorkspaces.go: -------------------------------------------------------------------------------- 1 | package providers 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | func GoogleWorkspaces(input tpmodels.ProviderInput) *tpmodels.TypeProvider { 11 | if input.Config.Name == "" { 12 | input.Config.Name = "Google Workspaces" 13 | } 14 | 15 | if input.Config.ValidateIdTokenPayload == nil { 16 | input.Config.ValidateIdTokenPayload = func(idTokenPayload map[string]interface{}, clientConfig tpmodels.ProviderConfigForClientType, userContext supertokens.UserContext) error { 17 | if clientConfig.AdditionalConfig != nil && clientConfig.AdditionalConfig["hd"] != nil && clientConfig.AdditionalConfig["hd"] != "*" && idTokenPayload["hd"] != clientConfig.AdditionalConfig["hd"] { 18 | return errors.New("the value for hd claim in the id token does not match the value provided in the config") 19 | } 20 | return nil 21 | } 22 | } 23 | 24 | oOverride := input.Override 25 | 26 | input.Override = func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { 27 | oGetConfig := originalImplementation.GetConfigForClientType 28 | originalImplementation.GetConfigForClientType = func(clientType *string, userContext supertokens.UserContext) (tpmodels.ProviderConfigForClientType, error) { 29 | config, err := oGetConfig(clientType, userContext) 30 | if err != nil { 31 | return tpmodels.ProviderConfigForClientType{}, err 32 | } 33 | 34 | if config.AdditionalConfig == nil || config.AdditionalConfig["hd"] == nil || config.AdditionalConfig["hd"] == "" { 35 | config.AuthorizationEndpointQueryParams["hd"] = "*" 36 | } else { 37 | config.AuthorizationEndpointQueryParams["hd"] = config.AdditionalConfig["hd"] 38 | } 39 | 40 | return config, nil 41 | } 42 | 43 | if oOverride != nil { 44 | originalImplementation = oOverride(originalImplementation) 45 | } 46 | return originalImplementation 47 | } 48 | 49 | return Google(input) 50 | } 51 | -------------------------------------------------------------------------------- /ingredients/smsdelivery/twiliomodels.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package smsdelivery 18 | 19 | import ( 20 | "errors" 21 | 22 | "github.com/supertokens/supertokens-golang/supertokens" 23 | ) 24 | 25 | type TwilioSettings struct { 26 | AccountSid string 27 | AuthToken string 28 | From string 29 | MessagingServiceSid string 30 | } 31 | 32 | type SMSContent struct { 33 | Body string 34 | ToPhoneNumber string 35 | } 36 | 37 | type TwilioInterface struct { 38 | SendRawSms *func(input SMSContent, userContext supertokens.UserContext) error 39 | GetContent *func(input SmsType, userContext supertokens.UserContext) (SMSContent, error) 40 | } 41 | 42 | type TwilioServiceConfig struct { 43 | Settings TwilioSettings 44 | Override func(originalImplementation TwilioInterface) TwilioInterface 45 | } 46 | 47 | func NormaliseTwilioServiceConfig(input TwilioServiceConfig) (TwilioServiceConfig, error) { 48 | if input.Settings.From == "" && input.Settings.MessagingServiceSid == "" { 49 | return TwilioServiceConfig{}, errors.New("either 'From' or 'MessagingServiceSid' must be set") 50 | } 51 | if input.Settings.From != "" && input.Settings.MessagingServiceSid != "" { 52 | return TwilioServiceConfig{}, errors.New("only one of 'From' or 'MessagingServiceSid' must be set") 53 | } 54 | return input, nil 55 | } 56 | -------------------------------------------------------------------------------- /recipe/passwordless/api/doesPhoneNumberExist.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package api 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/passwordless/plessmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func DoesPhoneNumberExist(apiImplementation plessmodels.APIInterface, tenantId string, options plessmodels.APIOptions, userContext supertokens.UserContext) error { 24 | if apiImplementation.PhoneNumberExistsGET == nil || (*apiImplementation.PhoneNumberExistsGET) == nil { 25 | options.OtherHandler(options.Res, options.Req) 26 | return nil 27 | } 28 | phoneNumber := options.Req.URL.Query().Get("phoneNumber") 29 | if phoneNumber == "" { 30 | return supertokens.BadInputError{Msg: "Please provide the phoneNumber as a GET param"} 31 | } 32 | result, err := (*apiImplementation.PhoneNumberExistsGET)(phoneNumber, tenantId, options, userContext) 33 | if err != nil { 34 | return err 35 | } 36 | if result.OK != nil { 37 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 38 | "status": "OK", 39 | "exists": result.OK.Exists, 40 | }) 41 | } else if result.GeneralError != nil { 42 | return supertokens.Send200Response(options.Res, supertokens.ConvertGeneralErrorToJsonResponse(*result.GeneralError)) 43 | } 44 | return supertokens.ErrorIfNoResponse(options.Res) 45 | } 46 | -------------------------------------------------------------------------------- /addDevTag: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # check if we need to merge master into this branch------------ 4 | if [[ $(git log origin/master ^HEAD) ]]; then 5 | echo "You need to merge master into this branch. Exiting" 6 | exit 1 7 | fi 8 | 9 | # get version------------ 10 | version=`cat ./supertokens/constants.go | grep -e 'const VERSION'` 11 | while IFS='"' read -ra ADDR; do 12 | counter=0 13 | for i in "${ADDR[@]}"; do 14 | if [ $counter == 1 ] 15 | then 16 | version=$i 17 | fi 18 | counter=$(($counter+1)) 19 | done 20 | done <<< "$version" 21 | 22 | branch_name="$(git symbolic-ref HEAD 2>/dev/null)" || 23 | branch_name="(unnamed branch)" # detached HEAD 24 | 25 | branch_name=${branch_name##refs/heads/} 26 | 27 | # check if branch is correct based on the version----------- 28 | 29 | if ! [[ $version == $branch_name* ]] 30 | then 31 | RED='\033[0;31m' 32 | NC='\033[0m' # No Color 33 | printf "${RED}Adding tag to wrong branch. Stopping process${NC}\n" 34 | exit 1 35 | fi 36 | 37 | 38 | 39 | git fetch --prune --prune-tags 40 | 41 | # get current commit hash------------ 42 | if [ $# -eq 0 ] 43 | then 44 | commit_hash=`git log --pretty=format:'%H' -n 1` 45 | else 46 | commit_hash=$1 47 | fi 48 | 49 | 50 | # check if current commit already has a tag or not------------ 51 | 52 | if [[ `git tag -l --points-at $commit_hash` == "" ]] 53 | then 54 | continue=1 55 | else 56 | RED='\033[0;31m' 57 | NC='\033[0m' 58 | printf "${RED}This commit already has a tag. Please remove that and re-run this script${NC}\n" 59 | echo "git tag --delete " 60 | echo "git push --delete origin " 61 | exit 1 62 | fi 63 | 64 | # check if release version of this tag exists------------ 65 | 66 | if git rev-parse v$version >/dev/null 2>&1 67 | then 68 | RED='\033[0;31m' 69 | NC='\033[0m' 70 | printf "${RED}The released version of this tag already exists${NC}\n" 71 | exit 1 72 | fi 73 | 74 | 75 | # tag this commit and push it------------ 76 | 77 | git tag dev-v$version $commit_hash 78 | 79 | git push --tags 80 | -------------------------------------------------------------------------------- /recipe/dashboard/api/userdetails/userMetaDataGet.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userdetails 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 20 | "github.com/supertokens/supertokens-golang/recipe/usermetadata" 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | type userMetaDataGetResponse struct { 25 | Status string `json:"status"` 26 | Data interface{} `json:"data,omitempty"` 27 | } 28 | 29 | func UserMetaDataGet(apiInterface dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (userMetaDataGetResponse, error) { 30 | req := options.Req 31 | userId := req.URL.Query().Get("userId") 32 | 33 | if userId == "" { 34 | return userMetaDataGetResponse{}, supertokens.BadInputError{ 35 | Msg: "Missing required parameter 'userId'", 36 | } 37 | } 38 | 39 | _, instanceError := usermetadata.GetRecipeInstanceOrThrowError() 40 | 41 | if instanceError != nil { 42 | return userMetaDataGetResponse{ 43 | Status: "FEATURE_NOT_ENABLED_ERROR", 44 | }, nil 45 | } 46 | 47 | metadata, err := usermetadata.GetUserMetadata(userId, userContext) 48 | 49 | if err != nil { 50 | return userMetaDataGetResponse{}, err 51 | } 52 | 53 | return userMetaDataGetResponse{ 54 | Status: "OK", 55 | Data: metadata, 56 | }, nil 57 | } 58 | -------------------------------------------------------------------------------- /recipe/usermetadata/utils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package usermetadata 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/usermetadata/usermetadatamodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func validateAndNormaliseUserInput(appInfo supertokens.NormalisedAppinfo, config *usermetadatamodels.TypeInput) usermetadatamodels.TypeNormalisedInput { 24 | 25 | typeNormalisedInput := makeTypeNormalisedInput(appInfo) 26 | 27 | if config != nil && config.Override != nil { 28 | if config.Override.Functions != nil { 29 | typeNormalisedInput.Override.Functions = config.Override.Functions 30 | } 31 | if config.Override.APIs != nil { 32 | typeNormalisedInput.Override.APIs = config.Override.APIs 33 | } 34 | } 35 | 36 | return typeNormalisedInput 37 | } 38 | 39 | func makeTypeNormalisedInput(appInfo supertokens.NormalisedAppinfo) usermetadatamodels.TypeNormalisedInput { 40 | return usermetadatamodels.TypeNormalisedInput{ 41 | Override: usermetadatamodels.OverrideStruct{ 42 | Functions: func(originalImplementation usermetadatamodels.RecipeInterface) usermetadatamodels.RecipeInterface { 43 | return originalImplementation 44 | }, 45 | APIs: func(originalImplementation usermetadatamodels.APIInterface) usermetadatamodels.APIInterface { 46 | return originalImplementation 47 | }, 48 | }, 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /recipe/emailverification/evmodels/recipeInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package evmodels 17 | 18 | import "github.com/supertokens/supertokens-golang/supertokens" 19 | 20 | type RecipeInterface struct { 21 | CreateEmailVerificationToken *func(userID, email string, tenantId string, userContext supertokens.UserContext) (CreateEmailVerificationTokenResponse, error) 22 | VerifyEmailUsingToken *func(token string, tenantId string, userContext supertokens.UserContext) (VerifyEmailUsingTokenResponse, error) 23 | IsEmailVerified *func(userID, email string, userContext supertokens.UserContext) (bool, error) 24 | RevokeEmailVerificationTokens *func(userId, email string, tenantId string, userContext supertokens.UserContext) (RevokeEmailVerificationTokensResponse, error) 25 | UnverifyEmail *func(userId, email string, userContext supertokens.UserContext) (UnverifyEmailResponse, error) 26 | } 27 | 28 | type CreateEmailVerificationTokenResponse struct { 29 | OK *struct { 30 | Token string 31 | } 32 | EmailAlreadyVerifiedError *struct{} 33 | } 34 | 35 | type VerifyEmailUsingTokenResponse struct { 36 | OK *struct { 37 | User User 38 | } 39 | EmailVerificationInvalidTokenError *struct{} 40 | } 41 | 42 | type RevokeEmailVerificationTokensResponse struct { 43 | OK *struct{} 44 | } 45 | 46 | type UnverifyEmailResponse struct { 47 | OK *struct{} 48 | } 49 | -------------------------------------------------------------------------------- /recipe/thirdparty/providers/google.go: -------------------------------------------------------------------------------- 1 | package providers 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" 5 | "github.com/supertokens/supertokens-golang/supertokens" 6 | ) 7 | 8 | func Google(input tpmodels.ProviderInput) *tpmodels.TypeProvider { 9 | if input.Config.Name == "" { 10 | input.Config.Name = "Google" 11 | } 12 | 13 | if input.Config.OIDCDiscoveryEndpoint == "" { 14 | input.Config.OIDCDiscoveryEndpoint = "https://accounts.google.com/.well-known/openid-configuration" 15 | } 16 | 17 | if input.Config.AuthorizationEndpointQueryParams == nil { 18 | input.Config.AuthorizationEndpointQueryParams = map[string]interface{}{} 19 | } 20 | 21 | if _, ok := input.Config.AuthorizationEndpointQueryParams["include_granted_scopes"]; !ok { 22 | input.Config.AuthorizationEndpointQueryParams["include_granted_scopes"] = "true" 23 | } 24 | if _, ok := input.Config.AuthorizationEndpointQueryParams["access_type"]; !ok { 25 | input.Config.AuthorizationEndpointQueryParams["access_type"] = "offline" 26 | } 27 | 28 | oOverride := input.Override 29 | 30 | input.Override = func(originalImplementation *tpmodels.TypeProvider) *tpmodels.TypeProvider { 31 | oGetConfig := originalImplementation.GetConfigForClientType 32 | originalImplementation.GetConfigForClientType = func(clientType *string, userContext supertokens.UserContext) (tpmodels.ProviderConfigForClientType, error) { 33 | config, err := oGetConfig(clientType, userContext) 34 | if err != nil { 35 | return tpmodels.ProviderConfigForClientType{}, err 36 | } 37 | 38 | if len(config.Scope) == 0 { 39 | config.Scope = []string{"openid", "email"} 40 | } 41 | 42 | // The config could be coming from core where we didn't add the well-known previously 43 | config.OIDCDiscoveryEndpoint = normaliseOIDCEndpointToIncludeWellKnown(config.OIDCDiscoveryEndpoint) 44 | 45 | return config, nil 46 | } 47 | 48 | if oOverride != nil { 49 | originalImplementation = oOverride(originalImplementation) 50 | } 51 | return originalImplementation 52 | } 53 | 54 | return NewProvider(input) 55 | } 56 | -------------------------------------------------------------------------------- /ingredients/emaildelivery/models.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package emaildelivery 18 | 19 | import "github.com/supertokens/supertokens-golang/supertokens" 20 | 21 | type EmailDeliveryInterface struct { 22 | SendEmail *func(input EmailType, userContext supertokens.UserContext) error 23 | } 24 | 25 | type TypeInput struct { 26 | Service *EmailDeliveryInterface 27 | Override func(originalImplementation EmailDeliveryInterface) EmailDeliveryInterface 28 | } 29 | 30 | type TypeInputWithService struct { 31 | Service EmailDeliveryInterface 32 | Override func(originalImplementation EmailDeliveryInterface) EmailDeliveryInterface 33 | } 34 | 35 | type EmailType struct { 36 | EmailVerification *EmailVerificationType 37 | PasswordReset *PasswordResetType 38 | PasswordlessLogin *PasswordlessLoginType 39 | } 40 | 41 | type EmailVerificationType struct { 42 | User User 43 | EmailVerifyLink string 44 | TenantId string 45 | } 46 | 47 | type PasswordResetType struct { 48 | User User 49 | PasswordResetLink string 50 | TenantId string 51 | } 52 | 53 | type PasswordlessLoginType struct { 54 | Email string 55 | UserInputCode *string 56 | UrlWithLinkCode *string 57 | CodeLifetime uint64 58 | PreAuthSessionId string 59 | TenantId string 60 | } 61 | 62 | type User struct { 63 | ID string 64 | Email string 65 | } 66 | -------------------------------------------------------------------------------- /recipe/dashboard/api/tenantsListGet.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 5 | "github.com/supertokens/supertokens-golang/recipe/multitenancy" 6 | "github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | type tenantsListResponse struct { 11 | Status string `json:"status"` 12 | Tenants []tenantType `json:"tenants"` 13 | } 14 | 15 | type tenantType struct { 16 | TenantId string `json:"tenantId"` 17 | EmailPassword struct { 18 | Enabled bool `json:"enabled"` 19 | } `json:"emailPassword"` 20 | Passwordless struct { 21 | Enabled bool `json:"enabled"` 22 | } `json:"passwordless"` 23 | ThirdParty struct { 24 | Enabled bool `json:"enabled"` 25 | Providers []tpmodels.ProviderConfig `json:"providers"` 26 | } `json:"thirdParty"` 27 | } 28 | 29 | func TenantsListGet(apiInterface dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (tenantsListResponse, error) { 30 | tenantsResponse, err := multitenancy.ListAllTenants(userContext) 31 | if err != nil { 32 | return tenantsListResponse{}, err 33 | } 34 | result := tenantsListResponse{ 35 | Status: "OK", 36 | Tenants: make([]tenantType, len(tenantsResponse.OK.Tenants)), 37 | } 38 | 39 | for i, tenant := range tenantsResponse.OK.Tenants { 40 | result.Tenants[i] = tenantType{ 41 | TenantId: tenant.TenantId, 42 | EmailPassword: struct { 43 | Enabled bool `json:"enabled"` 44 | }{ 45 | Enabled: tenant.EmailPassword.Enabled, 46 | }, 47 | Passwordless: struct { 48 | Enabled bool `json:"enabled"` 49 | }{ 50 | Enabled: tenant.Passwordless.Enabled, 51 | }, 52 | ThirdParty: struct { 53 | Enabled bool `json:"enabled"` 54 | Providers []tpmodels.ProviderConfig `json:"providers"` 55 | }{ 56 | Enabled: tenant.ThirdParty.Enabled, 57 | Providers: tenant.ThirdParty.Providers, 58 | }, 59 | } 60 | } 61 | 62 | return result, nil 63 | } 64 | -------------------------------------------------------------------------------- /recipe/session/middleware.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package session 17 | 18 | import ( 19 | "context" 20 | "net/http" 21 | 22 | "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | func VerifySessionHelper(recipeInstance Recipe, options *sessmodels.VerifySessionOptions, otherHandler http.HandlerFunc) http.HandlerFunc { 27 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 28 | dw := supertokens.MakeDoneWriter(w) 29 | userContext := supertokens.MakeDefaultUserContextFromAPI(r) 30 | session, err := (*recipeInstance.APIImpl.VerifySession)(options, sessmodels.APIOptions{ 31 | Config: recipeInstance.Config, 32 | OtherHandler: otherHandler, 33 | Req: r, 34 | Res: dw, 35 | RecipeID: recipeInstance.RecipeModule.GetRecipeID(), 36 | RecipeImplementation: recipeInstance.RecipeImpl, 37 | }, userContext) 38 | if err != nil { 39 | err = supertokens.ErrorHandler(err, r, dw, userContext) 40 | if err != nil { 41 | recipeInstance.RecipeModule.OnSuperTokensAPIError(err, r, dw) 42 | } 43 | return 44 | } 45 | if session != nil { 46 | ctx := context.WithValue(r.Context(), sessmodels.SessionContext, session) 47 | otherHandler(dw, r.WithContext(ctx)) 48 | } else { 49 | otherHandler(dw, r) 50 | } 51 | }) 52 | } 53 | -------------------------------------------------------------------------------- /recipe/multitenancy/utils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package multitenancy 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/multitenancy/multitenancymodels" 20 | ) 21 | 22 | func validateAndNormaliseUserInput(config *multitenancymodels.TypeInput) multitenancymodels.TypeNormalisedInput { 23 | 24 | typeNormalisedInput := makeTypeNormalisedInput(config) 25 | 26 | if config != nil && config.Override != nil { 27 | if config.Override.Functions != nil { 28 | typeNormalisedInput.Override.Functions = config.Override.Functions 29 | } 30 | if config.Override.APIs != nil { 31 | typeNormalisedInput.Override.APIs = config.Override.APIs 32 | } 33 | } 34 | 35 | return typeNormalisedInput 36 | } 37 | 38 | func makeTypeNormalisedInput(config *multitenancymodels.TypeInput) multitenancymodels.TypeNormalisedInput { 39 | if config == nil { 40 | config = &multitenancymodels.TypeInput{} 41 | } 42 | 43 | return multitenancymodels.TypeNormalisedInput{ 44 | GetAllowedDomainsForTenantId: config.GetAllowedDomainsForTenantId, 45 | Override: multitenancymodels.OverrideStruct{ 46 | Functions: func(originalImplementation multitenancymodels.RecipeInterface) multitenancymodels.RecipeInterface { 47 | return originalImplementation 48 | }, 49 | APIs: func(originalImplementation multitenancymodels.APIInterface) multitenancymodels.APIInterface { 50 | return originalImplementation 51 | }, 52 | }, 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /recipe/jwt/createJWTFeature_test.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwt 17 | 18 | import ( 19 | "testing" 20 | 21 | "github.com/stretchr/testify/assert" 22 | "github.com/supertokens/supertokens-golang/supertokens" 23 | "github.com/supertokens/supertokens-golang/test/unittesting" 24 | ) 25 | 26 | func TestSendingZeroValidityThrowsAnError(t *testing.T) { 27 | configValue := supertokens.TypeInput{ 28 | Supertokens: &supertokens.ConnectionInfo{ 29 | ConnectionURI: "http://localhost:8080", 30 | }, 31 | AppInfo: supertokens.AppInfo{ 32 | APIDomain: "api.supertokens.io", 33 | AppName: "SuperTokens", 34 | WebsiteDomain: "supertokens.io", 35 | }, 36 | RecipeList: []supertokens.Recipe{ 37 | Init(nil), 38 | }, 39 | } 40 | 41 | BeforeEach() 42 | unittesting.StartUpST("localhost", "8080") 43 | defer AfterEach() 44 | err := supertokens.Init(configValue) 45 | if err != nil { 46 | t.Error(err.Error()) 47 | } 48 | 49 | q, err := supertokens.GetNewQuerierInstanceOrThrowError("") 50 | if err != nil { 51 | t.Error(err.Error()) 52 | } 53 | apiV, err := q.GetQuerierAPIVersion() 54 | if err != nil { 55 | t.Error(err.Error()) 56 | } 57 | 58 | if unittesting.MaxVersion(apiV, "2.8") == "2.8" { 59 | return 60 | } 61 | 62 | vaildityPointer := uint64(0) 63 | _, err = CreateJWT(map[string]interface{}{}, &vaildityPointer, nil) 64 | assert.Contains(t, err.Error(), "validity must be greater than or equal to 0") 65 | } 66 | -------------------------------------------------------------------------------- /recipe/dashboard/api/userdetails/userSessionsPost.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userdetails 17 | 18 | import ( 19 | "encoding/json" 20 | 21 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 22 | "github.com/supertokens/supertokens-golang/recipe/session" 23 | "github.com/supertokens/supertokens-golang/supertokens" 24 | ) 25 | 26 | type userSessionsPostResponse struct { 27 | Status string `json:"status"` 28 | } 29 | 30 | type userSessionsPostRequestBody struct { 31 | SessionHandles *[]string `json:"sessionHandles"` 32 | } 33 | 34 | func UserSessionsRevoke(apiInterface dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (userSessionsPostResponse, error) { 35 | body, err := supertokens.ReadFromRequest(options.Req) 36 | 37 | if err != nil { 38 | return userSessionsPostResponse{}, err 39 | } 40 | 41 | var readBody userSessionsPostRequestBody 42 | err = json.Unmarshal(body, &readBody) 43 | if err != nil { 44 | return userSessionsPostResponse{}, err 45 | } 46 | 47 | sessionHandles := readBody.SessionHandles 48 | 49 | if sessionHandles == nil { 50 | return userSessionsPostResponse{}, supertokens.BadInputError{ 51 | Msg: "Required parameter 'sessionHandles' is missing or has an invalid type", 52 | } 53 | } 54 | 55 | session.RevokeMultipleSessions(*sessionHandles, userContext) 56 | 57 | return userSessionsPostResponse{ 58 | Status: "OK", 59 | }, nil 60 | } 61 | -------------------------------------------------------------------------------- /recipe/dashboard/api/userdetails/userEmailVerifyGet.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package userdetails 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 20 | "github.com/supertokens/supertokens-golang/recipe/emailverification" 21 | "github.com/supertokens/supertokens-golang/supertokens" 22 | ) 23 | 24 | type userEmailVerifyGetResponse struct { 25 | Status string `json:"status"` 26 | IsVerified *bool `json:"isVerified,omitempty"` 27 | } 28 | 29 | func UserEmailVerifyGet(apiImplementation dashboardmodels.APIInterface, tenantId string, options dashboardmodels.APIOptions, userContext supertokens.UserContext) (userEmailVerifyGetResponse, error) { 30 | req := options.Req 31 | userId := req.URL.Query().Get("userId") 32 | 33 | if userId == "" { 34 | return userEmailVerifyGetResponse{}, supertokens.BadInputError{ 35 | Msg: "Missing required parameter 'userId'", 36 | } 37 | } 38 | 39 | emailverificationInstance := emailverification.GetRecipeInstance() 40 | 41 | if emailverificationInstance == nil { 42 | return userEmailVerifyGetResponse{ 43 | Status: "FEATURE_NOT_ENABLED_ERROR", 44 | }, nil 45 | } 46 | 47 | response, verificationError := emailverification.IsEmailVerified(userId, nil, userContext) 48 | 49 | if verificationError != nil { 50 | return userEmailVerifyGetResponse{}, verificationError 51 | } 52 | 53 | return userEmailVerifyGetResponse{ 54 | Status: "OK", 55 | IsVerified: &response, 56 | }, nil 57 | } 58 | -------------------------------------------------------------------------------- /recipe/jwt/utils.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package jwt 17 | 18 | import ( 19 | "github.com/supertokens/supertokens-golang/recipe/jwt/jwtmodels" 20 | "github.com/supertokens/supertokens-golang/supertokens" 21 | ) 22 | 23 | func validateAndNormaliseUserInput(appInfo supertokens.NormalisedAppinfo, config *jwtmodels.TypeInput) jwtmodels.TypeNormalisedInput { 24 | 25 | typeNormalisedInput := makeTypeNormalisedInput(appInfo) 26 | 27 | if config != nil && config.JwtValiditySeconds != nil { 28 | typeNormalisedInput.JwtValiditySeconds = *config.JwtValiditySeconds 29 | } 30 | 31 | if config != nil && config.Override != nil { 32 | if config.Override.Functions != nil { 33 | typeNormalisedInput.Override.Functions = config.Override.Functions 34 | } 35 | if config.Override.APIs != nil { 36 | typeNormalisedInput.Override.APIs = config.Override.APIs 37 | } 38 | } 39 | 40 | return typeNormalisedInput 41 | } 42 | 43 | func makeTypeNormalisedInput(appInfo supertokens.NormalisedAppinfo) jwtmodels.TypeNormalisedInput { 44 | return jwtmodels.TypeNormalisedInput{ 45 | JwtValiditySeconds: 3153600000, // 100 years in seconds 46 | Override: jwtmodels.OverrideStruct{ 47 | Functions: func(originalImplementation jwtmodels.RecipeInterface) jwtmodels.RecipeInterface { 48 | return originalImplementation 49 | }, 50 | APIs: func(originalImplementation jwtmodels.APIInterface) jwtmodels.APIInterface { 51 | return originalImplementation 52 | }, 53 | }, 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ingredients/emaildelivery/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved. 3 | * 4 | * This software is licensed under the Apache License, Version 2.0 (the 5 | * "License") as published by the Apache Software Foundation. 6 | * 7 | * You may not use this file except in compliance with the License. You may 8 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations 14 | * under the License. 15 | */ 16 | 17 | package emaildelivery 18 | 19 | import ( 20 | "crypto/tls" 21 | "fmt" 22 | 23 | "gopkg.in/gomail.v2" 24 | ) 25 | 26 | type Ingredient struct { 27 | IngredientInterfaceImpl EmailDeliveryInterface 28 | } 29 | 30 | func MakeIngredient(config TypeInputWithService) Ingredient { 31 | 32 | result := Ingredient{ 33 | IngredientInterfaceImpl: config.Service, 34 | } 35 | 36 | if config.Override != nil { 37 | result.IngredientInterfaceImpl = config.Override(result.IngredientInterfaceImpl) 38 | } 39 | 40 | return result 41 | } 42 | 43 | func SendSMTPEmail(settings SMTPSettings, content EmailContent) error { 44 | m := gomail.NewMessage() 45 | m.SetHeader("From", fmt.Sprintf("%s <%s>", settings.From.Name, settings.From.Email)) 46 | m.SetHeader("To", content.ToEmail) 47 | m.SetHeader("Subject", content.Subject) 48 | 49 | if content.IsHtml { 50 | m.SetBody("text/html", content.Body) 51 | } else { 52 | m.SetBody("text/plain", content.Body) 53 | } 54 | 55 | username := settings.From.Email 56 | if settings.Username != nil { 57 | username = *settings.Username 58 | } 59 | 60 | d := gomail.NewDialer(settings.Host, settings.Port, username, settings.Password) 61 | if settings.TLSConfig != nil { 62 | d.TLSConfig = settings.TLSConfig 63 | } else { 64 | d.TLSConfig = &tls.Config{ServerName: settings.Host} 65 | } 66 | 67 | if settings.Secure { 68 | d.SSL = true 69 | } 70 | return d.DialAndSend(m) 71 | } 72 | -------------------------------------------------------------------------------- /recipe/thirdparty/tpmodels/recipeInterface.go: -------------------------------------------------------------------------------- 1 | /* Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. 2 | * 3 | * This software is licensed under the Apache License, Version 2.0 (the 4 | * "License") as published by the Apache Software Foundation. 5 | * 6 | * You may not use this file except in compliance with the License. You may 7 | * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | * License for the specific language governing permissions and limitations 13 | * under the License. 14 | */ 15 | 16 | package tpmodels 17 | 18 | import "github.com/supertokens/supertokens-golang/supertokens" 19 | 20 | type RecipeInterface struct { 21 | GetUserByID *func(userID string, userContext supertokens.UserContext) (*User, error) 22 | GetUsersByEmail *func(email string, tenantId string, userContext supertokens.UserContext) ([]User, error) 23 | GetUserByThirdPartyInfo *func(thirdPartyID string, thirdPartyUserID string, tenantId string, userContext supertokens.UserContext) (*User, error) 24 | 25 | GetProvider *func(thirdPartyID string, clientType *string, tenantId string, userContext supertokens.UserContext) (*TypeProvider, error) 26 | 27 | SignInUp *func(thirdPartyID string, thirdPartyUserID string, email string, oAuthTokens TypeOAuthTokens, rawUserInfoFromProvider TypeRawUserInfoFromProvider, tenantId string, userContext supertokens.UserContext) (SignInUpResponse, error) 28 | ManuallyCreateOrUpdateUser *func(thirdPartyID string, thirdPartyUserID string, email string, tenantId string, userContext supertokens.UserContext) (ManuallyCreateOrUpdateUserResponse, error) 29 | } 30 | 31 | type SignInUpResponse struct { 32 | OK *struct { 33 | CreatedNewUser bool 34 | User User 35 | OAuthTokens TypeOAuthTokens 36 | RawUserInfoFromProvider TypeRawUserInfoFromProvider 37 | } 38 | } 39 | 40 | type ManuallyCreateOrUpdateUserResponse struct { 41 | OK *struct { 42 | CreatedNewUser bool 43 | User User 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /recipe/dashboard/api/signInPost.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | 6 | "github.com/supertokens/supertokens-golang/recipe/dashboard/dashboardmodels" 7 | "github.com/supertokens/supertokens-golang/supertokens" 8 | ) 9 | 10 | type signInPostResponse struct { 11 | Status string `json:"status"` 12 | SessionId string `json:"sessionId,omitempty"` 13 | Message string `json:"message,omitempty"` 14 | } 15 | 16 | type signInRequestBody struct { 17 | Email *string `json:"email"` 18 | Password *string `json:"password"` 19 | } 20 | 21 | func SignInPost(apiInterface dashboardmodels.APIInterface, options dashboardmodels.APIOptions, userContext supertokens.UserContext) error { 22 | body, err := supertokens.ReadFromRequest(options.Req) 23 | 24 | if err != nil { 25 | return err 26 | } 27 | 28 | var readBody signInRequestBody 29 | err = json.Unmarshal(body, &readBody) 30 | if err != nil { 31 | return err 32 | } 33 | 34 | if readBody.Email == nil { 35 | return supertokens.BadInputError{ 36 | Msg: "Required parameter 'email' is missing", 37 | } 38 | } 39 | 40 | if readBody.Password == nil { 41 | return supertokens.BadInputError{ 42 | Msg: "Required parameter 'password' is missing", 43 | } 44 | } 45 | 46 | querier, querierErr := supertokens.GetNewQuerierInstanceOrThrowError("dashboard") 47 | 48 | if querierErr != nil { 49 | return querierErr 50 | } 51 | 52 | apiResponse, apiErr := querier.SendPostRequest("/recipe/dashboard/signin", map[string]interface{}{ 53 | "email": *readBody.Email, 54 | "password": *readBody.Password, 55 | }, userContext) 56 | 57 | if apiErr != nil { 58 | return apiErr 59 | } 60 | 61 | status := apiResponse["status"] 62 | 63 | if status == "OK" { 64 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 65 | "status": "OK", 66 | "sessionId": apiResponse["sessionId"].(string), 67 | }) 68 | } 69 | 70 | if status == "USER_SUSPENDED_ERROR" { 71 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 72 | "status": "USER_SUSPENDED_ERROR", 73 | "message": apiResponse["message"].(string), 74 | }) 75 | } 76 | 77 | return supertokens.Send200Response(options.Res, map[string]interface{}{ 78 | "status": "INVAlID_CREDENTIALS_ERROR", 79 | }) 80 | } 81 | -------------------------------------------------------------------------------- /examples/with-twirp/internal/haberdasherserver/random.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Twitch Interactive, Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"). You may not 4 | // use this file except in compliance with the License. A copy of the License is 5 | // located at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // or in the "license" file accompanying this file. This file is distributed on 10 | // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 11 | // express or implied. See the License for the specific language governing 12 | // permissions and limitations under the License. 13 | 14 | package haberdasherserver 15 | 16 | import ( 17 | "context" 18 | "fmt" 19 | "math/rand" 20 | 21 | "github.com/supertokens/supertokens-golang/examples/with-twirp/haberdasher" 22 | "github.com/supertokens/supertokens-golang/recipe/session" 23 | "github.com/twitchtv/twirp" 24 | ) 25 | 26 | // New returns a new Haberdasher which returns random Hats of the requested 27 | // size. 28 | func New() *randomHaberdasher { 29 | return new(randomHaberdasher) 30 | } 31 | 32 | // randomHaberdasher is our implementation of the generated 33 | // rpc/haberdasher.Haberdasher interface. This is where the real "business 34 | // logic" lives. 35 | type randomHaberdasher struct{} 36 | 37 | func (h *randomHaberdasher) MakeHat(ctx context.Context, size *haberdasher.Size) (*haberdasher.Hat, error) { 38 | sessionContainer := session.GetSessionFromRequestContext(ctx) 39 | if sessionContainer == nil { 40 | fmt.Println("no session exists!") 41 | } else { 42 | // session exists! 43 | fmt.Println("session exists: " + sessionContainer.GetUserID()) 44 | } 45 | // When returning an error, it's best to use the error constructors defined in 46 | // the Twirp package so that the client gets a well-structured error response. 47 | if size.Inches <= 0 { 48 | return nil, twirp.InvalidArgumentError("Inches", "I can't make a hat that small!") 49 | } 50 | colors := []string{"white", "black", "brown", "red", "blue"} 51 | names := []string{"bowler", "baseball cap", "top hat", "derby"} 52 | return &haberdasher.Hat{ 53 | Size: size.Inches, 54 | Color: colors[rand.Intn(len(colors))], 55 | Name: names[rand.Intn(len(names))], 56 | }, nil 57 | } 58 | --------------------------------------------------------------------------------