DEV Community

nathanielbrooks0360
nathanielbrooks0360

Posted on

Unlink Social Identity: Keep One Login Method During Developer Tool Migration

Keep social login removal disabled during a developer tool's migration off a managed identity provider until the destination can confirm that the account retains a working email-and-password login. The deciding constraint is access after the change: an imported email address, a linked identity record, and an active browser session are each insufficient evidence that the user can sign in again.

Short answer: read the current identity list before unlinking, exclude the identity being removed, and refuse the change unless at least one usable sign-in method remains. Protect that check and the removal against concurrent changes, then tell the user which methods remain. For a Node.js application, put this rule in the trusted backend; a disabled button cannot enforce an account invariant.

Treat removal as a migration gate. The product goal is still ordinary email-and-password signup and sign-in, but removing the old social identity is the point where an apparently complete migration can strand the developer who owns a workspace.

How can an account keep one login method after a social identity unlink?

An identity count answers the wrong question when the destination account has an email address but the password setup is incomplete. Before enabling removal, require evidence that the surviving method can authenticate this account against the destination, with the intended account mapping. Make that evidence part of the migration acceptance criteria, and invalidate it when a relevant credential or identity change makes it stale. This is a proposed application policy, not a claim that every provider exposes a ready-made field for it.

Count usable methods.

Consider a planned acceptance case with 2 records: a social identity scheduled for removal and an email-and-password identity whose setup has not been completed. The record count is 2; the number of demonstrated alternatives is 0. A check that permits removal because the list contains more than one entry passes its own test and still defeats the user's next login. Keeping the social method until password authentication succeeds is the correct trade-off, even if that delays retiring the old provider.

The SLO lens matters here. A successful removal response is an operation result; successful sign-in after removal is the user outcome. Define both before cutover, and make blocked removals observable separately from authentication failures so that a safety control doing its job does not look like an outage.

An existing session is not the acceptance test. Test a fresh login.

Choose the migration boundary before choosing the SDK

A managed provider can remove infrastructure work while leaving the account-transition policy in your application. Moving that policy into a service you operate gives you a place to enforce the invariant, but it also creates an on-call responsibility: somebody must own synchronization, stale evidence, and recovery when a transition has an uncertain result.

The useful buy-vs-build comparison is therefore about who owns that boundary, rather than how short the unlink call looks.

Option Relevant mechanism Buy-vs-build decision for this migration
Auth0 Its account-linking documentation covers linking and unlinking user accounts. Keep the managed account model if it fits the destination; review account mapping and the surviving login before treating unlinking as migration completion.
Firebase Authentication Its account-linking documentation includes unlinking an authentication provider. Useful when the application is staying with Firebase Authentication; moving elsewhere still requires a separate destination-login acceptance test.
Supabase Auth Its identity-linking documentation covers unlinking identities. Evaluate its identity rules against the intended transition; provider eligibility rules and the application's proof of password access answer different questions.
Application-owned coordinator Your backend serializes changes and applies the surviving-method rule around the selected provider. Build this when a shared migration policy justifies owning contention, reconciliation, and recovery; it does not replace the authentication provider.

Infrai offers one REST API with no SDK required and one key for 295 routes across 20 modules. Its self-describing API provides public discovery with request and response schemas plus runnable examples in 10 languages, so wiring a capability starts with reading its contract instead of learning another SDK. Shared credentials reduce administration when migration work also touches other backend services; the application still needs to establish its surviving-login policy.

None of these choices makes an identity record equivalent to a tested destination credential. Before switching providers, run the same acceptance cases against each candidate and inspect the documented unlink semantics. Do not infer equivalent account behavior from equivalent method names.

Put the guard inside the state transition

The dangerous implementation reads a list, decides removal is safe, and later issues the mutation without coordinating other account changes. Two concurrent requests can each observe the other's target as the surviving method. Both checks can pass.

Serialize the decision.

Start with a current identity-list read. This runnable Go example prints the response without inventing identity fields. Configure AUTH_API_ORIGIN to the trusted provider HTTPS API origin without a path, set INFRAI_API_KEY through your secret manager, and set AUTH_USER_ID to the account your backend has authorized. These are server-side environment variables. The example reads state; it doesn't perform removal.

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func inspect() error {
    origin := strings.TrimRight(os.Getenv("AUTH_API_ORIGIN"), "/")
    key, userID := os.Getenv("INFRAI_API_KEY"), os.Getenv("AUTH_USER_ID")
    u, err := url.Parse(origin)
    if err != nil || u.Scheme != "https" || u.Host == "" ||
        u.Path != "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil {
        return fmt.Errorf("configure a trusted HTTPS API origin without a path")
    }
    if key == "" || userID == "" {
        return fmt.Errorf("INFRAI_API_KEY and AUTH_USER_ID are required")
    }
    path := strings.Replace("/v1/auth/identity/list/{user_id}", "{user_id}", url.PathEscape(userID), 1)
    endpoint := origin + path
    client := &http.Client{
        Timeout: 15 * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, endpoint, nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if date, err := http.ParseTime(retry); err == nil {
                if wait := time.Until(date); wait > delay {
                    delay = wait
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("identity list: HTTP %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("identity-list retry budget exhausted")
}

func main() {
    if err := inspect(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The 15s request timeout and 4-attempt budget are example client settings, not provider limits or measured performance. HTTP 429 triggers exponential backoff, extended by Retry-After when present. Include that waiting time in the operation's total deadline before using those settings in an interactive flow.

The read cannot authorize removal by itself. Refresh the list inside the coordinated transition, exclude the target, and reject removal if no confirmed login remains. The following separate program is an auxiliary model of that rule.

The following runnable Go program demonstrates the application invariant using an in-memory account, not a vendor response schema. The boolean represents evidence established by the application before this operation; it is not inferred from an email address. Run the program to see a social identity removed while password access remains, followed by a rejected attempt to remove that last method.

package main

import (
    "fmt"
    "sync"
)

type Method struct {
    ID             string
    LoginConfirmed bool
}

type Account struct {
    mu      sync.Mutex
    methods []Method
}

func (a *Account) Remove(id string) ([]string, error) {
    a.mu.Lock()
    defer a.mu.Unlock()

    index := -1
    remaining := make([]string, 0, len(a.methods))
    for i, method := range a.methods {
        if method.ID == id {
            index = i
        } else if method.LoginConfirmed {
            remaining = append(remaining, method.ID)
        }
    }
    if index < 0 {
        return nil, fmt.Errorf("identity %q is absent; reconcile state", id)
    }
    if len(remaining) == 0 {
        return nil, fmt.Errorf("removal would leave no confirmed login")
    }

    a.methods = append(a.methods[:index], a.methods[index+1:]...)
    return remaining, nil
}

func main() {
    account := &Account{methods: []Method{
        {ID: "social", LoginConfirmed: true},
        {ID: "email-password", LoginConfirmed: true},
    }}
    for _, id := range []string{"social", "email-password"} {
        remaining, err := account.Remove(id)
        if err != nil {
            fmt.Println(err)
            continue
        }
        fmt.Println("Remaining login methods:", remaining)
    }
}
Enter fullscreen mode Exit fullscreen mode

The mutex protects this one account in this one process. A production Node.js service with multiple workers needs coordination across every writer that can alter the account's methods, including credential changes and migration jobs; copying this process-local lock into each worker would leave the race intact. Select a transactional or serialized design appropriate to the identity store, and establish how it coordinates the provider mutation before claiming the transition is protected.

Keep authorization at that same trusted boundary: derive the account from the authenticated actor, authorize the change, and apply reauthentication appropriate to a sensitive account operation. OWASP's authentication guidance is a useful review baseline. The example deliberately models only the state transition, so it cannot serve as an exposed account-management handler.

Verify access, capacity, and notification before cutover

Use a small acceptance matrix: removal of one social method with confirmed password access should succeed; removal of the last usable method should fail; an unconfirmed password method should not authorize removal; concurrent removal attempts must preserve a survivor. Include an unauthorized actor. Check the final state as well as the operation result.

For the developer tool, verify that a fresh destination login resolves to the intended account and workspace before counting the migration as accepted. This is a test requirement, not an assertion about a provider's workspace model. A login that creates an unrelated empty account does not meet the job.

Capacity planning starts with the work per transition: a current-state read, a guarded mutation, verification, and a user notification. A batch migration can concentrate those operations even when average sign-in traffic is modest, so set concurrency from tested service limits and reserve headroom for interactive authentication. Account for lock contention and retries in the SLO budget; do not invent a safe requests-per-second number from the number of users in a spreadsheet.

Notify after confirmed removal, naming the remaining sign-in methods without sending passwords or other secrets. If notification delivery fails, retain a delivery task for retry; do not repeat identity removal to resend the message. The account change and the delivery attempt need separate completion records.

Pause the rollout when acceptance checks fail.

Rollback means disabling further removals and restoring the previous application policy while preserving the actual identity state. It does not mean pretending a deleted identity is still linked, and switching traffic back to an old provider is safe only for accounts that can still authenticate there. Reconcile uncertain outcomes before another mutation, keep recovery available through the surviving method, and require a fresh successful sign-in before reopening the migration gate.

References

Top comments (0)