Repository: supabase/gotrue
Pull request #658 (2022-09-01 07:31:03)

refactor: params.Metadata -> params.Data
Renames the OTP param from Metadata to Data to be consistent with the `/signup` route.

TODOs: 
- [ ] Check and update corresponding GoTrue-js bindings 
- [ ] Check and update corresponding GoTrue-js types


Patch:
diff --git a/Makefile b/Makefile
index 48c885f0..0e12d6ec 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: all build deps dev-deps image migrate test vet sec format
+.PHONY: all build deps dev-deps image migrate test vet sec format unused
 CHECK_FILES?=./...
 FLAGS?=-ldflags "-X github.com/netlify/gotrue/cmd.Version=`git describe --tags`"
 DEV_DOCKER_COMPOSE:=docker-compose-dev.yml
@@ -6,13 +6,13 @@ DEV_DOCKER_COMPOSE:=docker-compose-dev.yml
 help: ## Show this help.
 	@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {sub("\\\\n",sprintf("\n%22c"," "), $$2);printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
 
-all: vet sec build ## Run the tests and build the binary.
+all: vet sec unused build ## Run the tests and build the binary.
 
 build: deps ## Build the binary.
 	go build $(FLAGS)
 	GOOS=linux GOARCH=arm64 go build $(FLAGS) -o gotrue-arm64
 
-dev-deps: deps ## Install developer dependencies
+dev-deps: ## Install developer dependencies
 	@go install github.com/gobuffalo/pop/soda@latest
 	@go install github.com/securego/gosec/v2/cmd/gosec@latest
 	@go install honnef.co/go/tools/cmd/staticcheck@latest
@@ -33,11 +33,11 @@ test: build ## Run tests.
 vet: # Vet the code
 	go vet $(CHECK_FILES)
 
-sec: # Check for security vulnerabilities
+sec: dev-deps # Check for security vulnerabilities
 	gosec -quiet $(CHECK_FILES)
 	gosec -quiet -tests -exclude=G104 $(CHECK_FILES)
 
-unused: # Look for unused code
+unused: dev-deps # Look for unused code
 	@echo "Unused code:"
 	staticcheck -checks U1000 $(CHECK_FILES)
 	
diff --git a/api/external.go b/api/external.go
index ed84659d..e005fb4e 100644
--- a/api/external.go
+++ b/api/external.go
@@ -109,7 +109,8 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
 
 	providerType := getExternalProviderType(ctx)
 	var userData *provider.UserProvidedData
-	var providerToken string
+	var providerAccessToken string
+	var providerRefreshToken string = ""
 	if providerType == "twitter" {
 		// future OAuth1.0 providers will use this method
 		oAuthResponseData, err := a.oAuth1Callback(ctx, r, providerType)
@@ -117,14 +118,15 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
 			return err
 		}
 		userData = oAuthResponseData.userData
-		providerToken = oAuthResponseData.token
+		providerAccessToken = oAuthResponseData.token
 	} else {
 		oAuthResponseData, err := a.oAuthCallback(ctx, r, providerType)
 		if err != nil {
 			return err
 		}
 		userData = oAuthResponseData.userData
-		providerToken = oAuthResponseData.token
+		providerAccessToken = oAuthResponseData.token
+		providerRefreshToken = oAuthResponseData.refreshToken
 	}
 
 	var user *models.User
@@ -286,7 +288,12 @@ func (a *API) internalExternalProviderCallback(w http.ResponseWriter, r *http.Re
 	rurl := a.getExternalRedirectURL(r)
 	if token != nil {
 		q := url.Values{}
-		q.Set("provider_token", providerToken)
+		q.Set("provider_token", providerAccessToken)
+		// Because not all providers give out a refresh token
+		// See corresponding OAuth2 spec: <https://www.rfc-editor.org/rfc/rfc6749.html#section-5.1>
+		if providerRefreshToken != "" {
+			q.Set("provider_refresh_token", providerRefreshToken)
+		}
 		q.Set("access_token", token.Token)
 		q.Set("token_type", token.TokenType)
 		q.Set("expires_in", strconv.Itoa(token.ExpiresIn))
diff --git a/api/external_oauth.go b/api/external_oauth.go
index dc645fff..d00d9836 100644
--- a/api/external_oauth.go
+++ b/api/external_oauth.go
@@ -14,8 +14,9 @@ import (
 
 // OAuthProviderData contains the userData and token returned by the oauth provider
 type OAuthProviderData struct {
-	userData *provider.UserProvidedData
-	token    string
+	userData     *provider.UserProvidedData
+	token        string
+	refreshToken string
 }
 
 // loadOAuthState parses the `state` query parameter as a JWS payload,
@@ -96,8 +97,9 @@ func (a *API) oAuthCallback(ctx context.Context, r *http.Request, providerType s
 	}
 
 	return &OAuthProviderData{
-		userData: userData,
-		token:    token.AccessToken,
+		userData:     userData,
+		token:        token.AccessToken,
+		refreshToken: token.RefreshToken,
 	}, nil
 }
 
@@ -134,8 +136,9 @@ func (a *API) oAuth1Callback(ctx context.Context, r *http.Request, providerType
 	}
 
 	return &OAuthProviderData{
-		userData: userData,
-		token:    accessToken.Token,
+		userData:     userData,
+		token:        accessToken.Token,
+		refreshToken: "",
 	}, nil
 
 }
diff --git a/api/magic_link.go b/api/magic_link.go
index 01d28ac3..8e743f00 100644
--- a/api/magic_link.go
+++ b/api/magic_link.go
@@ -15,8 +15,8 @@ import (
 
 // MagicLinkParams holds the parameters for a magic link request
 type MagicLinkParams struct {
-	Email    string                 `json:"email"`
-	Metadata map[string]interface{} `json:"metadata"`
+	Email string                 `json:"email"`
+	Data  map[string]interface{} `json:"metadata"`
 }
 
 // MagicLink sends a recovery email
@@ -35,8 +35,8 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
 		return badRequestError("Could not read verification params: %v", err)
 	}
 
-	if params.Metadata == nil {
-		params.Metadata = make(map[string]interface{})
+	if params.Data == nil {
+		params.Data = make(map[string]interface{})
 	}
 
 	if params.Email == "" {
@@ -59,7 +59,7 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
 			signUpParams := &SignupParams{
 				Email:    params.Email,
 				Password: password,
-				Data:     params.Metadata,
+				Data:     params.Data,
 			}
 			newBodyContent, err := json.Marshal(signUpParams)
 			if err != nil {
@@ -76,7 +76,7 @@ func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
 				}
 				newBodyContent := &SignupParams{
 					Email: params.Email,
-					Data:  params.Metadata,
+					Data:  params.Data,
 				}
 				metadata, err := json.Marshal(newBodyContent)
 				if err != nil {
diff --git a/api/otp.go b/api/otp.go
index da626f5d..6aa4c84e 100644
--- a/api/otp.go
+++ b/api/otp.go
@@ -17,13 +17,13 @@ type OtpParams struct {
 	Email      string                 `json:"email"`
 	Phone      string                 `json:"phone"`
 	CreateUser bool                   `json:"create_user"`
-	Metadata   map[string]interface{} `json:"metadata"`
+	Data       map[string]interface{} `json:"data"`
 }
 
 // SmsParams contains the request body params for sms otp
 type SmsParams struct {
-	Phone    string                 `json:"phone"`
-	Metadata map[string]interface{} `json:"metadata"`
+	Phone string                 `json:"phone"`
+	Data  map[string]interface{} `json:"data"`
 }
 
 // Otp returns the MagicLink or SmsOtp handler based on the request body params
@@ -31,8 +31,8 @@ func (a *API) Otp(w http.ResponseWriter, r *http.Request) error {
 	params := &OtpParams{
 		CreateUser: true,
 	}
-	if params.Metadata == nil {
-		params.Metadata = make(map[string]interface{})
+	if params.Data == nil {
+		params.Data = make(map[string]interface{})
 	}
 
 	body, err := getBodyBytes(r)
@@ -82,8 +82,8 @@ func (a *API) SmsOtp(w http.ResponseWriter, r *http.Request) error {
 	if err := json.Unmarshal(body, params); err != nil {
 		return badRequestError("Could not read sms otp params: %v", err)
 	}
-	if params.Metadata == nil {
-		params.Metadata = make(map[string]interface{})
+	if params.Data == nil {
+		params.Data = make(map[string]interface{})
 	}
 
 	params.Phone, err = a.validatePhone(params.Phone)
@@ -105,7 +105,7 @@ func (a *API) SmsOtp(w http.ResponseWriter, r *http.Request) error {
 			signUpParams := &SignupParams{
 				Phone:    params.Phone,
 				Password: password,
-				Data:     params.Metadata,
+				Data:     params.Data,
 			}
 			newBodyContent, err := json.Marshal(signUpParams)
 			if err != nil {
diff --git a/api/token.go b/api/token.go
index b92aedb1..cd535670 100644
--- a/api/token.go
+++ b/api/token.go
@@ -556,7 +556,7 @@ func (a *API) issueRefreshToken(ctx context.Context, conn *storage.Connection, u
 
 	err := conn.Transaction(func(tx *storage.Connection) error {
 		var terr error
-		refreshToken, terr = models.GrantAuthenticatedUser(tx, user)
+		refreshToken, terr = models.GrantAuthenticatedUser(tx, user, models.GrantParams{})
 		if terr != nil {
 			return internalServerError("Database error granting user").WithInternalError(terr)
 		}
diff --git a/cmd/migrate_cmd.go b/cmd/migrate_cmd.go
index 3b355c9f..469be24e 100644
--- a/cmd/migrate_cmd.go
+++ b/cmd/migrate_cmd.go
@@ -32,7 +32,7 @@ func migrate(cmd *cobra.Command, args []string) {
 		globalConfig.DB.Driver = u.Scheme
 	}
 
-	log := logrus.New()
+	log := logrus.StandardLogger()
 
 	pop.Debug = false
 	if globalConfig.Logging.Level != "" {
diff --git a/conf/configuration.go b/conf/configuration.go
index d87b41b1..de25c141 100644
--- a/conf/configuration.go
+++ b/conf/configuration.go
@@ -259,11 +259,11 @@ func LoadGlobal(filename string) (*GlobalConfiguration, error) {
 		return nil, err
 	}
 
-	if err := config.Validate(); err != nil {
+	if err := ConfigureLogging(&config.Logging); err != nil {
 		return nil, err
 	}
 
-	if _, err := ConfigureLogging(&config.Logging); err != nil {
+	if err := config.Validate(); err != nil {
 		return nil, err
 	}
 
diff --git a/conf/logging.go b/conf/logging.go
index 831b3af9..e28bd0f5 100644
--- a/conf/logging.go
+++ b/conf/logging.go
@@ -2,11 +2,18 @@ package conf
 
 import (
 	"os"
-	"time"
 
+	"github.com/gobuffalo/pop/v5"
+	"github.com/gobuffalo/pop/v5/logging"
 	"github.com/sirupsen/logrus"
 )
 
+const (
+	LOG_SQL_ALL       = "all"
+	LOG_SQL_NONE      = "none"
+	LOG_SQL_STATEMENT = "statement"
+)
+
 type LoggingConfig struct {
 	Level            string                 `mapstructure:"log_level" json:"log_level"`
 	File             string                 `mapstructure:"log_file" json:"log_file"`
@@ -14,47 +21,78 @@ type LoggingConfig struct {
 	QuoteEmptyFields bool                   `mapstructure:"quote_empty_fields" split_words:"true" json:"quote_empty_fields"`
 	TSFormat         string                 `mapstructure:"ts_format" json:"ts_format"`
 	Fields           map[string]interface{} `mapstructure:"fields" json:"fields"`
+	SQL              string                 `mapstructure:"sql" json:"sql"`
 }
 
-func ConfigureLogging(config *LoggingConfig) (*logrus.Entry, error) {
-	logger := logrus.New()
-
-	tsFormat := time.RFC3339Nano
-	if config.TSFormat != "" {
-		tsFormat = config.TSFormat
-	}
-	// always use the full timestamp
-	logger.SetFormatter(&logrus.TextFormatter{
-		FullTimestamp:    true,
-		DisableTimestamp: false,
-		TimestampFormat:  tsFormat,
-		DisableColors:    config.DisableColors,
-		QuoteEmptyFields: config.QuoteEmptyFields,
-	})
+func ConfigureLogging(config *LoggingConfig) error {
+	logrus.SetFormatter(&logrus.JSONFormatter{})
 
 	// use a file if you want
 	if config.File != "" {
 		f, errOpen := os.OpenFile(config.File, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660) //#nosec G302 -- Log files should be rw-rw-r--
 		if errOpen != nil {
-			return nil, errOpen
+			return errOpen
 		}
-		logger.SetOutput(f)
-		logger.Infof("Set output file to %s", config.File)
+		logrus.SetOutput(f)
+		logrus.Infof("Set output file to %s", config.File)
 	}
 
 	if config.Level != "" {
 		level, err := logrus.ParseLevel(config.Level)
 		if err != nil {
-			return nil, err
+			return err
 		}
-		logger.SetLevel(level)
-		logger.Debug("Set log level to: " + logger.GetLevel().String())
+		logrus.SetLevel(level)
+		logrus.Debug("Set log level to: " + logrus.GetLevel().String())
 	}
 
 	f := logrus.Fields{}
 	for k, v := range config.Fields {
 		f[k] = v
 	}
+	logrus.WithFields(f)
+
+	setPopLogger(config.SQL)
+
+	return nil
+}
+
+func setPopLogger(sql string) {
+	popLog := logrus.WithField("component", "pop")
+	sqlLog := logrus.WithField("component", "sql")
 
-	return logger.WithFields(f), nil
+	shouldLogSQL := sql == LOG_SQL_STATEMENT || sql == LOG_SQL_ALL
+	shouldLogSQLArgs := sql == LOG_SQL_ALL
+
+	pop.SetLogger(func(lvl logging.Level, s string, args ...interface{}) {
+		// Special case SQL logging since we have 2 extra flags to check
+		if lvl == logging.SQL {
+			if !shouldLogSQL {
+				return
+			}
+
+			if shouldLogSQLArgs && len(args) > 0 {
+				sqlLog.WithField("args", args).Info(s)
+			} else {
+				sqlLog.Info(s)
+			}
+			return
+		}
+
+		l := popLog
+		if len(args) > 0 {
+			l = l.WithField("args", args)
+		}
+
+		switch lvl {
+		case logging.Debug:
+			l.Debug(s)
+		case logging.Info:
+			l.Info(s)
+		case logging.Warn:
+			l.Warn(s)
+		case logging.Error:
+			l.Error(s)
+		}
+	})
 }
diff --git a/logger/log.go b/logger/log.go
index 8f5c14a9..028cb541 100644
--- a/logger/log.go
+++ b/logger/log.go
@@ -6,13 +6,11 @@ import (
 	"time"
 
 	chimiddleware "github.com/go-chi/chi/middleware"
+	"github.com/netlify/gotrue/utilities"
 	"github.com/sirupsen/logrus"
 )
 
 func NewStructuredLogger(logger *logrus.Logger) func(next http.Handler) http.Handler {
-	logger.Formatter = &logrus.JSONFormatter{
-		DisableTimestamp: true,
-	}
 	return chimiddleware.RequestLogger(&structuredLogger{logger})
 }
 
@@ -26,7 +24,7 @@ func (l *structuredLogger) NewLogEntry(r *http.Request) chimiddleware.LogEntry {
 		"component":   "api",
 		"method":      r.Method,
 		"path":        r.URL.Path,
-		"remote_addr": r.RemoteAddr,
+		"remote_addr": utilities.GetIPAddress(r),
 		"referer":     r.Referer(),
 		"timestamp":   time.Now().UTC().Format(time.RFC3339),
 	}
diff --git a/mailer/mailer.go b/mailer/mailer.go
index 266944f3..b9d634b4 100644
--- a/mailer/mailer.go
+++ b/mailer/mailer.go
@@ -40,7 +40,7 @@ func NewMailer(instanceConfig *conf.GlobalConfiguration) Mailer {
 			Pass:    instanceConfig.SMTP.Pass,
 			From:    from,
 			BaseURL: instanceConfig.SiteURL,
-			Logger:  logrus.New(),
+			Logger:  logrus.StandardLogger(),
 		}
 	}
 
diff --git a/models/connection.go b/models/connection.go
index 446c58ff..8ffa95e7 100644
--- a/models/connection.go
+++ b/models/connection.go
@@ -43,7 +43,7 @@ func TruncateAll(conn *storage.Connection) error {
 		}
 
 		for _, tableName := range tables {
-			if err := tx.RawQuery("TRUNCATE " + tableName + " CASCADE").Exec(); err != nil {
+			if err := tx.RawQuery("DELETE FROM " + tableName + " CASCADE").Exec(); err != nil {
 				return err
 			}
 		}
diff --git a/models/refresh_token.go b/models/refresh_token.go
index 5f1bc463..eb2ab3d5 100644
--- a/models/refresh_token.go
+++ b/models/refresh_token.go
@@ -36,9 +36,14 @@ func (RefreshToken) TableName() string {
 	return tableName
 }
 
+// GrantParams is used to pass session-specific parameters when issuing a new
+// refresh token to authenticated users.
+type GrantParams struct {
+}
+
 // GrantAuthenticatedUser creates a refresh token for the provided user.
-func GrantAuthenticatedUser(tx *storage.Connection, user *User) (*RefreshToken, error) {
-	return createRefreshToken(tx, user, nil)
+func GrantAuthenticatedUser(tx *storage.Connection, user *User, params GrantParams) (*RefreshToken, error) {
+	return createRefreshToken(tx, user, nil, &params)
 }
 
 // GrantRefreshTokenSwap swaps a refresh token for a new one, revoking the provided token.
@@ -54,7 +59,7 @@ func GrantRefreshTokenSwap(r *http.Request, tx *storage.Connection, user *User,
 		if terr = tx.UpdateOnly(token, "revoked"); terr != nil {
 			return terr
 		}
-		newToken, terr = createRefreshToken(rtx, user, token)
+		newToken, terr = createRefreshToken(rtx, user, token, nil)
 		return terr
 	})
 	return newToken, err
@@ -94,7 +99,7 @@ func GetValidChildToken(tx *storage.Connection, token *RefreshToken) (*RefreshTo
 	return refreshToken, nil
 }
 
-func createRefreshToken(tx *storage.Connection, user *User, oldToken *RefreshToken) (*RefreshToken, error) {
+func createRefreshToken(tx *storage.Connection, user *User, oldToken *RefreshToken, params *GrantParams) (*RefreshToken, error) {
 	token := &RefreshToken{
 		UserID: user.ID,
 		Token:  crypto.SecureToken(),
diff --git a/security/hcaptcha.go b/security/hcaptcha.go
index c584f77e..a0014ab1 100644
--- a/security/hcaptcha.go
+++ b/security/hcaptcha.go
@@ -13,6 +13,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/netlify/gotrue/utilities"
 	"github.com/pkg/errors"
 	"github.com/sirupsen/logrus"
 )
@@ -77,7 +78,7 @@ func VerifyRequest(r *http.Request, secretKey string) (VerificationResult, error
 	if err != nil || strings.TrimSpace(res.Security.Token) == "" {
 		return UserRequestFailed, errors.Wrap(err, "couldn't decode captcha info")
 	}
-	clientIP := strings.Split(r.RemoteAddr, ":")[0]
+	clientIP := utilities.GetIPAddress(r)
 	return verifyCaptchaCode(res.Security.Token, secretKey, clientIP)
 }
 
diff --git a/storage/dial.go b/storage/dial.go
index 2a78d3d1..47c3af60 100644
--- a/storage/dial.go
+++ b/storage/dial.go
@@ -41,10 +41,6 @@ func Dial(config *conf.GlobalConfiguration) (*Connection, error) {
 	if err := db.Open(); err != nil {
 		return nil, errors.Wrap(err, "checking database connection")
 	}
-	if logrus.StandardLogger().Level == logrus.DebugLevel {
-		pop.Debug = true
-	}
-
 	return &Connection{db}, nil
 }
 
diff --git a/utilities/request.go b/utilities/request.go
new file mode 100644
index 00000000..3e244b7b
--- /dev/null
+++ b/utilities/request.go
@@ -0,0 +1,35 @@
+package utilities
+
+import (
+	"net"
+	"net/http"
+	"strings"
+)
+
+// GetIPAddress returns the real IP address of the HTTP request. It parses the
+// X-Forwarded-For header.
+func GetIPAddress(r *http.Request) string {
+	if r.Header != nil {
+		xForwardedFor := r.Header.Get("X-Forwarded-For")
+		if xForwardedFor != "" {
+			ips := strings.Split(xForwardedFor, ",")
+			for i := range ips {
+				ips[i] = strings.TrimSpace(ips[i])
+			}
+
+			for _, ip := range ips {
+				if ip != "" {
+					return ip
+				}
+			}
+		}
+	}
+
+	ipPort := r.RemoteAddr
+	ip, _, err := net.SplitHostPort(ipPort)
+	if err != nil {
+		return ipPort
+	}
+
+	return ip
+}


Test patch:
diff --git a/api/otp_test.go b/api/otp_test.go
index db240282..8154459c 100644
--- a/api/otp_test.go
+++ b/api/otp_test.go
@@ -51,7 +51,7 @@ func (ts *OtpTestSuite) TestOtp() {
 			OtpParams{
 				Email:      "test@example.com",
 				CreateUser: true,
-				Metadata: map[string]interface{}{
+				Data: map[string]interface{}{
 					"somedata": "metadata",
 				},
 			},
diff --git a/api/token_test.go b/api/token_test.go
index 3ff75803..c8d36377 100644
--- a/api/token_test.go
+++ b/api/token_test.go
@@ -50,7 +50,7 @@ func (ts *TokenTestSuite) SetupTest() {
 	u.BannedUntil = nil
 	require.NoError(ts.T(), ts.API.db.Create(u), "Error saving new test user")
 
-	ts.RefreshToken, err = models.GrantAuthenticatedUser(ts.API.db, u)
+	ts.RefreshToken, err = models.GrantAuthenticatedUser(ts.API.db, u, models.GrantParams{})
 	require.NoError(ts.T(), err, "Error creating refresh token")
 }
 
@@ -153,7 +153,7 @@ func (ts *TokenTestSuite) TestTokenRefreshTokenRotation() {
 	t := time.Now()
 	u.EmailConfirmedAt = &t
 	require.NoError(ts.T(), ts.API.db.Create(u), "Error saving foo user")
-	first, err := models.GrantAuthenticatedUser(ts.API.db, u)
+	first, err := models.GrantAuthenticatedUser(ts.API.db, u, models.GrantParams{})
 	require.NoError(ts.T(), err)
 	second, err := models.GrantRefreshTokenSwap(&http.Request{}, ts.API.db, u, first)
 	require.NoError(ts.T(), err)
@@ -245,7 +245,7 @@ func (ts *TokenTestSuite) createBannedUser() *models.User {
 	u.BannedUntil = &t
 	require.NoError(ts.T(), ts.API.db.Create(u), "Error saving new test banned user")
 
-	ts.RefreshToken, err = models.GrantAuthenticatedUser(ts.API.db, u)
+	ts.RefreshToken, err = models.GrantAuthenticatedUser(ts.API.db, u, models.GrantParams{})
 	require.NoError(ts.T(), err, "Error creating refresh token")
 
 	return u
diff --git a/hack/test.env b/hack/test.env
index f76624d6..f076a5a8 100644
--- a/hack/test.env
+++ b/hack/test.env
@@ -9,7 +9,8 @@ GOTRUE_DB_AUTOMIGRATE=true
 DATABASE_URL="postgres://supabase_auth_admin:root@localhost:5432/postgres"
 GOTRUE_API_HOST=localhost
 PORT=9999
-GOTRUE_LOG_LEVEL=debug
+GOTRUE_LOG_SQL=none
+GOTRUE_LOG_LEVEL=warn
 GOTRUE_SITE_URL=https://example.netlify.com
 GOTRUE_URI_ALLOW_LIST="http://localhost:3000"
 GOTRUE_OPERATOR_TOKEN=foobar
diff --git a/models/refresh_token_test.go b/models/refresh_token_test.go
index cbf32af2..6da738ba 100644
--- a/models/refresh_token_test.go
+++ b/models/refresh_token_test.go
@@ -37,7 +37,7 @@ func TestRefreshToken(t *testing.T) {
 
 func (ts *RefreshTokenTestSuite) TestGrantAuthenticatedUser() {
 	u := ts.createUser()
-	r, err := GrantAuthenticatedUser(ts.db, u)
+	r, err := GrantAuthenticatedUser(ts.db, u, GrantParams{})
 	require.NoError(ts.T(), err)
 
 	require.NotEmpty(ts.T(), r.Token)
@@ -46,7 +46,7 @@ func (ts *RefreshTokenTestSuite) TestGrantAuthenticatedUser() {
 
 func (ts *RefreshTokenTestSuite) TestGrantRefreshTokenSwap() {
 	u := ts.createUser()
-	r, err := GrantAuthenticatedUser(ts.db, u)
+	r, err := GrantAuthenticatedUser(ts.db, u, GrantParams{})
 	require.NoError(ts.T(), err)
 
 	s, err := GrantRefreshTokenSwap(&http.Request{}, ts.db, u, r)
@@ -64,7 +64,7 @@ func (ts *RefreshTokenTestSuite) TestGrantRefreshTokenSwap() {
 
 func (ts *RefreshTokenTestSuite) TestLogout() {
 	u := ts.createUser()
-	r, err := GrantAuthenticatedUser(ts.db, u)
+	r, err := GrantAuthenticatedUser(ts.db, u, GrantParams{})
 	require.NoError(ts.T(), err)
 
 	require.NoError(ts.T(), Logout(ts.db, u.ID))
diff --git a/models/user_test.go b/models/user_test.go
index 8ff308a4..eb75a599 100644
--- a/models/user_test.go
+++ b/models/user_test.go
@@ -148,7 +148,7 @@ func (ts *UserTestSuite) TestFindUserByRecoveryToken() {
 
 func (ts *UserTestSuite) TestFindUserWithRefreshToken() {
 	u := ts.createUser()
-	r, err := GrantAuthenticatedUser(ts.db, u)
+	r, err := GrantAuthenticatedUser(ts.db, u, GrantParams{})
 	require.NoError(ts.T(), err)
 
 	n, nr, err := FindUserWithRefreshToken(ts.db, r.Token)
diff --git a/utilities/request_test.go b/utilities/request_test.go
new file mode 100644
index 00000000..da76042e
--- /dev/null
+++ b/utilities/request_test.go
@@ -0,0 +1,87 @@
+package utilities
+
+import (
+	"net/http"
+	tst "testing"
+
+	"github.com/stretchr/testify/require"
+)
+
+func TestGetIPAddress(t *tst.T) {
+	examples := []func(r *http.Request) string{
+		func(r *http.Request) string {
+			r.Header = nil
+			r.RemoteAddr = "127.0.0.1:8080"
+
+			return "127.0.0.1"
+		},
+
+		func(r *http.Request) string {
+			r.Header = nil
+			r.RemoteAddr = "incorrect"
+
+			return "incorrect"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "127.0.0.1:8080"
+
+			return "127.0.0.1"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "[::1]:8080"
+
+			return "::1"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "127.0.0.1:8080"
+			r.Header.Add("X-Forwarded-For", "127.0.0.2")
+
+			return "127.0.0.2"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "127.0.0.1:8080"
+			r.Header.Add("X-Forwarded-For", "127.0.0.2")
+
+			return "127.0.0.2"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "127.0.0.1:8080"
+			r.Header.Add("X-Forwarded-For", "127.0.0.2,")
+
+			return "127.0.0.2"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "127.0.0.1:8080"
+			r.Header.Add("X-Forwarded-For", "127.0.0.2,127.0.0.3")
+
+			return "127.0.0.2"
+		},
+
+		func(r *http.Request) string {
+			r.Header = make(http.Header)
+			r.RemoteAddr = "127.0.0.1:8080"
+			r.Header.Add("X-Forwarded-For", "::1,127.0.0.2")
+
+			return "::1"
+		},
+	}
+
+	for _, example := range examples {
+		req := &http.Request{}
+		expected := example(req)
+
+		require.Equal(t, GetIPAddress(req), expected)
+	}
+}