Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions plugins/magiclink/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,11 @@ func (p *Plugin) handleSend(ctx forge.Context, req *SendRequest) (*SendResponse,
if err != nil {
return nil, middleware.InternalError(ctx, fmt.Errorf("failed to create magic link token: %w", err))
}
// NewVerification leaves the environment empty, and the SQL stores hold
// env_id to a foreign key, so an empty one fails the insert and every
// send for a real account is a 500. The link lives in the user's own
// environment.
v.EnvID = u.EnvID

if err := p.store.CreateVerification(ctx.Context(), v); err != nil {
return nil, middleware.InternalError(ctx, fmt.Errorf("failed to create magic link: %w", err))
Expand Down
28 changes: 28 additions & 0 deletions plugins/magiclink/sendverify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xraph/forge"

"github.com/xraph/authsome/id"
)

// TestMagicLink_SendThenVerify_Succeeds is the end-to-end flow: /send must
Expand Down Expand Up @@ -65,3 +67,29 @@ func TestMagicLink_Send_UnknownEmail_UniformSuccessNoLink(t *testing.T) {
require.Equal(t, http.StatusOK, rec.Code, "send must return a uniform success even for unknown emails; body=%s", rec.Body.String())
assert.Empty(t, mailer.sent, "no magic link should be sent to an unregistered email")
}

// TestMagicLink_Send_StoresUserEnvironment pins the token to the user's
// environment. The SQL stores hold env_id to a foreign key, so a token
// saved with an empty one fails the insert and /send returns a 500 for
// every real account. The memory store doesn't enforce the key, so check
// the field itself.
func TestMagicLink_Send_StoresUserEnvironment(t *testing.T) {
p, s, mailer := newTestPlugin(t)
u := createTestUser(t, s)
u.EnvID = id.NewEnvironmentID()
require.NoError(t, s.UpdateUser(context.Background(), u))

mux := forge.NewRouter()
require.NoError(t, p.RegisterRoutes(mux))

req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/v1/magic-link/send", jsonBody(t, map[string]string{"email": u.Email}))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.Handler().ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, "send body=%s", rec.Body.String())
require.Len(t, mailer.sent, 1)

v, err := s.GetVerification(context.Background(), mailer.sent[0].Token)
require.NoError(t, err)
assert.Equal(t, u.EnvID.String(), v.EnvID.String(), "the link must be stored in the user's environment")
}
Loading