Skip to content

Commit

Permalink
refactor: replace fmt.Sprintf with generateTokenHash
Browse files Browse the repository at this point in the history
  • Loading branch information
[email protected] committed Jul 22, 2023
1 parent 5bb5db2 commit cf91daf
Show file tree
Hide file tree
Showing 8 changed files with 41 additions and 46 deletions.
4 changes: 2 additions & 2 deletions internal/api/invite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package api

import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -16,6 +15,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/supabase/gotrue/internal/conf"
"github.com/supabase/gotrue/internal/crypto"
"github.com/supabase/gotrue/internal/models"
)

Expand Down Expand Up @@ -152,7 +152,7 @@ func (ts *InviteTestSuite) TestVerifyInvite() {
user.InvitedAt = &now
user.ConfirmationSentAt = &now
user.EncryptedPassword = ""
user.ConfirmationToken = fmt.Sprintf("%x", sha256.Sum224([]byte(c.email+c.requestBody["token"].(string))))
user.ConfirmationToken = crypto.GenerateTokenHash(c.email, c.requestBody["token"].(string))
require.NoError(ts.T(), err)
require.NoError(ts.T(), ts.API.db.Create(user))

Expand Down
20 changes: 9 additions & 11 deletions internal/api/mail.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package api

import (
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -94,7 +92,7 @@ func (a *API) GenerateLink(w http.ResponseWriter, r *http.Request) error {
if err != nil {
return err
}
hashedToken := fmt.Sprintf("%x", sha256.Sum224([]byte(params.Email+otp)))
hashedToken := crypto.GenerateTokenHash(params.Email, otp)

Check failure on line 95 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
err = db.Transaction(func(tx *storage.Connection) error {
var terr error
switch params.Type {
Expand Down Expand Up @@ -198,7 +196,7 @@ func (a *API) GenerateLink(w http.ResponseWriter, r *http.Request) error {
if params.Type == "email_change_current" {
user.EmailChangeTokenCurrent = hashedToken
} else if params.Type == "email_change_new" {
user.EmailChangeTokenNew = fmt.Sprintf("%x", sha256.Sum224([]byte(params.NewEmail+otp)))
user.EmailChangeTokenNew = crypto.GenerateTokenHash(params.NewEmail, otp)

Check failure on line 199 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
}
terr = errors.Wrap(tx.UpdateOnly(user, "email_change_token_current", "email_change_token_new", "email_change", "email_change_sent_at", "email_change_confirm_status"), "Database error updating user for email change")
default:
Expand Down Expand Up @@ -243,7 +241,7 @@ func sendConfirmation(tx *storage.Connection, u *models.User, mailer mailer.Mail
if err != nil {
return err
}
token := fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+otp)))
token := crypto.GenerateTokenHash(u.GetEmail(), otp)

Check failure on line 244 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
u.ConfirmationToken = addFlowPrefixToToken(token, flowType)
now := time.Now()
if err := mailer.ConfirmationMail(u, otp, referrerURL, externalURL); err != nil {
Expand All @@ -261,7 +259,7 @@ func sendInvite(tx *storage.Connection, u *models.User, mailer mailer.Mailer, re
if err != nil {
return err
}
u.ConfirmationToken = fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+otp)))
u.ConfirmationToken = crypto.GenerateTokenHash(u.GetEmail(), otp)

Check failure on line 262 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
now := time.Now()
if err := mailer.InviteMail(u, otp, referrerURL, externalURL); err != nil {
u.ConfirmationToken = oldToken
Expand All @@ -283,7 +281,7 @@ func (a *API) sendPasswordRecovery(tx *storage.Connection, u *models.User, maile
if err != nil {
return err
}
token := fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+otp)))
token := crypto.GenerateTokenHash(u.GetEmail(), otp)

Check failure on line 284 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
u.RecoveryToken = addFlowPrefixToToken(token, flowType)
now := time.Now()
if err := mailer.RecoveryMail(u, otp, referrerURL, externalURL); err != nil {
Expand All @@ -305,7 +303,7 @@ func (a *API) sendReauthenticationOtp(tx *storage.Connection, u *models.User, ma
if err != nil {
return err
}
u.ReauthenticationToken = fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+otp)))
u.ReauthenticationToken = crypto.GenerateTokenHash(u.GetEmail(), otp)

Check failure on line 306 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
if err != nil {
return err
}
Expand All @@ -330,7 +328,7 @@ func (a *API) sendMagicLink(tx *storage.Connection, u *models.User, mailer maile
if err != nil {
return err
}
token := fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+otp)))
token := crypto.GenerateTokenHash(u.GetEmail(), otp)

Check failure on line 331 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
u.RecoveryToken = addFlowPrefixToToken(token, flowType)

now := time.Now()
Expand All @@ -353,7 +351,7 @@ func (a *API) sendEmailChange(tx *storage.Connection, config *conf.GlobalConfigu
return err
}
u.EmailChange = email
token := fmt.Sprintf("%x", sha256.Sum224([]byte(u.EmailChange+otpNew)))
token := crypto.GenerateTokenHash(u.EmailChange, otpNew)

Check failure on line 354 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
u.EmailChangeTokenNew = addFlowPrefixToToken(token, flowType)

otpCurrent := ""
Expand All @@ -362,7 +360,7 @@ func (a *API) sendEmailChange(tx *storage.Connection, config *conf.GlobalConfigu
if err != nil {
return err
}
currentToken := fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+otpCurrent)))
currentToken := crypto.GenerateTokenHash(u.GetEmail(), otpCurrent)

Check failure on line 363 in internal/api/mail.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash
u.EmailChangeTokenCurrent = addFlowPrefixToToken(currentToken, flowType)
if err != nil {
return err
Expand Down
4 changes: 2 additions & 2 deletions internal/api/mail_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package api

import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -15,6 +14,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/supabase/gotrue/internal/conf"
"github.com/supabase/gotrue/internal/crypto"
"github.com/supabase/gotrue/internal/models"
)

Expand Down Expand Up @@ -176,7 +176,7 @@ func (ts *MailTestSuite) TestGenerateLink() {
require.Equal(ts.T(), c.ExpectedResponse["redirect_to"], data["redirect_to"])

// check if hashed_token matches hash function of email and the raw otp
require.Equal(ts.T(), fmt.Sprintf("%x", sha256.Sum224([]byte(c.Body.Email+data["email_otp"].(string)))), data["hashed_token"])
require.Equal(ts.T(), crypto.GenerateTokenHash(c.Body.Email, data["email_otp"].(string)), data["hashed_token"])

// check if the host used in the email link matches the initial request host
u, err := url.ParseRequestURI(data["action_link"].(string))
Expand Down
3 changes: 1 addition & 2 deletions internal/api/phone.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package api

import (
"context"
"crypto/sha256"
"fmt"
"regexp"
"strings"
Expand Down Expand Up @@ -76,7 +75,7 @@ func (a *API) sendPhoneConfirmation(ctx context.Context, tx *storage.Connection,
if err != nil {
return "", internalServerError("error generating otp").WithInternalError(err)
}
*token = fmt.Sprintf("%x", sha256.Sum224([]byte(phone+otp)))
*token = crypto.GenerateTokenHash(phone, otp)

Check failure on line 78 in internal/api/phone.go

View workflow job for this annotation

GitHub Actions / test (1.20.x)

undefined: crypto.GenerateTokenHash

var message string
if config.Sms.Template == "" {
Expand Down
7 changes: 3 additions & 4 deletions internal/api/reauthenticate.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package api

import (
"crypto/sha256"
"errors"
"fmt"
"net/http"

"github.com/supabase/gotrue/internal/api/sms_provider"
"github.com/supabase/gotrue/internal/conf"
"github.com/supabase/gotrue/internal/crypto"
"github.com/supabase/gotrue/internal/models"
"github.com/supabase/gotrue/internal/storage"
)
Expand Down Expand Up @@ -82,7 +81,7 @@ func (a *API) verifyReauthentication(nonce string, tx *storage.Connection, confi
}
var isValid bool
if user.GetEmail() != "" {
tokenHash := fmt.Sprintf("%x", sha256.Sum224([]byte(user.GetEmail()+nonce)))
tokenHash := crypto.GenerateTokenHash(user.GetEmail(), nonce)
isValid = isOtpValid(tokenHash, user.ReauthenticationToken, user.ReauthenticationSentAt, config.Mailer.OtpExp)
} else if user.GetPhone() != "" {
if config.Sms.IsTwilioVerifyProvider() {
Expand All @@ -92,7 +91,7 @@ func (a *API) verifyReauthentication(nonce string, tx *storage.Connection, confi
}
return nil
} else {
tokenHash := fmt.Sprintf("%x", sha256.Sum224([]byte(user.GetPhone()+nonce)))
tokenHash := crypto.GenerateTokenHash(user.GetPhone(), nonce)
isValid = isOtpValid(tokenHash, user.ReauthenticationToken, user.ReauthenticationSentAt, config.Sms.OtpExp)
}
} else {
Expand Down
4 changes: 2 additions & 2 deletions internal/api/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package api

import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
Expand All @@ -14,6 +13,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/supabase/gotrue/internal/conf"
"github.com/supabase/gotrue/internal/crypto"
"github.com/supabase/gotrue/internal/models"
)

Expand Down Expand Up @@ -340,7 +340,7 @@ func (ts *UserTestSuite) TestUserUpdatePasswordReauthentication() {
require.NotEmpty(ts.T(), u.ReauthenticationSentAt)

// update reauthentication token to a known token
u.ReauthenticationToken = fmt.Sprintf("%x", sha256.Sum224([]byte(u.GetEmail()+"123456")))
u.ReauthenticationToken = crypto.GenerateTokenHash(u.GetEmail(), "123456")
require.NoError(ts.T(), ts.API.db.Update(u))

// update password with reauthentication token
Expand Down
7 changes: 3 additions & 4 deletions internal/api/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package api

import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
Expand All @@ -14,6 +12,7 @@ import (

"github.com/sethvargo/go-password/password"
"github.com/supabase/gotrue/internal/api/sms_provider"
"github.com/supabase/gotrue/internal/crypto"
"github.com/supabase/gotrue/internal/models"
"github.com/supabase/gotrue/internal/observability"
"github.com/supabase/gotrue/internal/storage"
Expand Down Expand Up @@ -77,13 +76,13 @@ func (p *VerifyParams) Validate(r *http.Request) error {
if err != nil {
return err
}
p.TokenHash = fmt.Sprintf("%x", sha256.Sum224([]byte(p.Phone+p.Token)))
p.TokenHash = crypto.GenerateTokenHash(p.Phone, p.Token)
} else if isEmailOtpVerification(p) {
p.Email, err = validateEmail(p.Email)
if err != nil {
return unprocessableEntityError("Invalid email format").WithInternalError(err)
}
p.TokenHash = fmt.Sprintf("%x", sha256.Sum224([]byte(p.Email+p.Token)))
p.TokenHash = crypto.GenerateTokenHash(p.Email, p.Token)
} else {
return badRequestError("Only an email address or phone number should be provided on verify")
}
Expand Down
Loading

0 comments on commit cf91daf

Please sign in to comment.