# Use OhAuthCat SSO with custom auth

Use this guide when your application has its own user table and session system. The generic `linkIdentity` function applies the same linking rule as the provider helpers, through a two-method interface you implement over your store.

## Identity-linking rule

The helper keys the user by the profile's `connection_id` and `idp_id`: the link key is `oac_` followed by the first 40 hex characters of SHA-256 over `connection_id`, a newline and `idp_id`. Email is never used to match. You choose the policy on every call: `refuse` signs in only users that are already linked, `create` also creates the missing user. When the provider already holds an unlinked account with the same email, the helper fails with `email_conflict`; link that account through a signed-in, explicit flow instead of merging on email.

## Set up custom auth

1. Add a unique column for the link key (or a unique pair of `connection_id` and `idp_id`) to your user table, scoped to the tenant that owns the organization.
2. Implement `find` and `create`. When `create` hits the unique constraint because of a concurrent sign-in, throw an `email_conflict` error; `linkIdentity` then finds the winner instead of creating a duplicate.
3. Start your own session after `linkIdentity` returns, with a fresh session identifier.

## Node

```javascript
// Replace the map with your user table.
const usersByKey = new Map();
const linker = {
  provider: "custom",
  find: async (profile) => usersByKey.get(profile.key) ?? null,
  create: async (profile) => {
    if (usersByKey.has(profile.key))
      throw new ExistingAuthError("custom", "email_conflict", "already linked");
    const user = {
      id: profile.key,
      organizationId: profile.organizationId,
      email: profile.email ?? null,
    };
    usersByKey.set(profile.key, user);
    return user;
  },
};

export async function linkUser(profile) {
  const { user, created } = await linkIdentity(profile, linker, {
    onMissing: "create",
  });
  return { user, created }; // start your own session for user.id
}

export async function revokeUser(userId) {
  usersByKey.delete(userId); // and delete that user's sessions in your session store
}
```

## Python

```python
from ohauthcat.existing_auth import LinkPolicy, link_identity

users_by_key = {}  # replace with your user table


class Linker:
    provider = "custom"

    def find(self, profile):
        return users_by_key.get(profile.key)

    def create(self, profile):
        user = {"id": profile.key, "organization_id": profile.organization_id}
        users_by_key[profile.key] = user
        return user


def link_user(profile):
    result = link_identity(profile, Linker(), LinkPolicy("create"))
    return result.user, result.created


def revoke_user(user_id):
    users_by_key.pop(user_id, None)  # and delete that user's sessions
```

## Go

```go
package main

import (
	"context"
	"sync"

	ohauthcat "ohauthcat.com/sdk-go"
	"ohauthcat.com/sdk-go/existingauth"
)

type user struct{ ID, OrganizationID string }

type store struct {
	mu    sync.Mutex
	users map[string]user
}

func (s *store) Provider() existingauth.Provider { return existingauth.ProviderCustom }

func (s *store) Find(_ context.Context, p existingauth.LinkProfile) (user, bool, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	u, ok := s.users[p.Key]
	return u, ok, nil
}

func (s *store) Create(_ context.Context, p existingauth.LinkProfile) (user, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	u := user{ID: p.Key, OrganizationID: p.OrganizationID}
	s.users[p.Key] = u
	return u, nil
}

func linkUser(ctx context.Context, s *store, profile ohauthcat.Profile) (user, error) {
	res, err := existingauth.Link(ctx, existingauth.FromProfile(profile), existingauth.Linker[user](s),
		existingauth.Policy{OnMissing: existingauth.OnMissingCreate})
	return res.User, err
}
```

## Revoke sessions on `dsync.user.deleted`

Delete or disable the linked user and remove every session for that user from your session store.

Verify the webhook first ([webhook verification](/events/webhook-verification/)), then map the directory user to your linked user through your own organization-scoped record. OhAuthCat does not close sessions in your provider for you.

## Troubleshooting

| Code                   | Meaning                                                                           |
| ---------------------- | --------------------------------------------------------------------------------- |
| `invalid_input`        | A profile field or option is missing or malformed                                 |
| `not_linked`           | No linked user and the policy is `refuse`                                         |
| `email_conflict`       | An unlinked account already uses this email or identifier                         |
| `provider_error`       | The provider refused the call (HTTP status in `status`)                           |
| `provider_unavailable` | Network failure, timeout, HTTP 429 or 5xx                                         |
| `invalid_response`     | The provider answered with an unexpected body                                     |
| `session_refused`      | The provider would not start a session (disabled, banned, wrong challenge answer) |

Error messages never contain tokens, secrets or provider response bodies, so they are safe to log.

- `not_linked`: the policy is `refuse` and the user has never been linked; use `create`, or link the account explicitly first.
- Two users created for one person: your `create` did not enforce a unique link key.

See also [working with existing auth](/sso/working-with-existing-auth/) and [profiles](/sso/profiles/).
