Ir al contenido

SignIn

Iniciar sesión, todo el camino: correo y contraseña, el código de un segundo factor, una llave de acceso y una contraseña olvidada. Un marco para cada paso, y una tarea por paso.

import { AuthLayout } from '@sypnia/ui/react'

En esta página
  1. En un computador
  2. En un celular
  3. Skeleton
  4. Cuando el inicio de sesión no responde
  5. Cuándo usarlo
  6. Para todos
  7. Props

En un computador

Escribe cualquier correo y contraseña: «wrong» como contraseña muestra qué pasa cuando no coinciden, y luego cualquier código menos 000000 inicia la sesión. Prueba también «¿Olvidaste tu contraseña?».

Inicia sesión en Sypnia

Usa el correo con el que te registraste.

¿Eres nuevo en Sypnia? Crea una cuenta

Código
import { useState, type ReactNode } from 'react';
import {
  Alert, AuthLayout, Button, Divider, EmailInput, Field, Form, FormActions, List, ListItem, Notice, OtpInput,
  PasswordInput, Says, SkeletonOf, Stack, useSypnia, type FormProblem,
} from '@sypnia/ui/react';

// Sign in, the whole flow: email and password, the code of a second factor, a passkey, and «Forgot your password?»
// with its email. Every step is the same frame; when the step changes, the focus moves to its title.
const en = {
  signIn: 'Sign in to Sypnia', signInLead: 'Use the email you signed up with.',
  email: 'Email', password: 'Password', forgot: 'Forgot your password?', submit: 'Sign in', busy: 'Signing in…',
  or: 'or', passkey: 'Sign in with a passkey', newHere: 'New to Sypnia?', create: 'Create an account',
  noEmail: 'Write your email.', badEmail: 'Write a whole email address, like ana@northwind.io.', noPassword: 'Write your password.',
  mismatch: 'That email and password do not match. Check both, or reset your password.',
  code: 'Enter your code', codeLead: 'Open your authenticator app and type the 6-digit code it shows for Sypnia.',
  codeLabel: 'Code from your app', wrongCode: 'That code is not right, or it already changed. Type the one your app shows now.',
  useOther: 'Use another way', back: 'Back to sign in',
  reset: 'Reset your password', resetLead: 'We will email you a link to choose a new one.', sendLink: 'Email me a link', sending: 'Sending…',
  sent: 'Check your email', sentLead: (e: string) => `If ${e} has an account, a link to choose a new password is on its way. It works for 30 minutes.`,
  resend: 'Send it again', resent: 'Sent again. Look in your spam folder too.',
  done: 'You are signed in', doneLead: 'Taking you to your projects.', open: 'Go to my projects',
  down: 'Sign-in is not answering', downBody: 'Your data is safe. This usually clears up in a minute.', retry: 'Try again',
  asideSays: 'Your tables, your API, in your region.', perks: ['Postgres with an API from the first minute', 'Backups every day, kept for 30 days', 'Free to run on your own servers'],
  terms: 'Terms', privacy: 'Privacy', help: 'Help',
};
const es: typeof en = {
  signIn: 'Inicia sesión en Sypnia', signInLead: 'Usa el correo con el que te registraste.',
  email: 'Correo', password: 'Contraseña', forgot: '¿Olvidaste tu contraseña?', submit: 'Iniciar sesión', busy: 'Iniciando sesión…',
  or: 'o', passkey: 'Iniciar sesión con una llave de acceso', newHere: '¿Eres nuevo en Sypnia?', create: 'Crea una cuenta',
  noEmail: 'Escribe tu correo.', badEmail: 'Escribe un correo completo, como ana@northwind.io.', noPassword: 'Escribe tu contraseña.',
  mismatch: 'Ese correo y esa contraseña no coinciden. Revisa los dos, o restablece tu contraseña.',
  code: 'Escribe tu código', codeLead: 'Abre tu app de autenticación y escribe el código de 6 dígitos que muestra para Sypnia.',
  codeLabel: 'Código de tu app', wrongCode: 'Ese código no es correcto, o ya cambió. Escribe el que muestra tu app ahora.',
  useOther: 'Usar otra forma', back: 'Volver a iniciar sesión',
  reset: 'Restablece tu contraseña', resetLead: 'Te enviamos un enlace para elegir una nueva.', sendLink: 'Enviarme un enlace', sending: 'Enviando…',
  sent: 'Revisa tu correo', sentLead: (e: string) => `Si ${e} tiene una cuenta, va en camino un enlace para elegir una contraseña nueva. Sirve por 30 minutos.`,
  resend: 'Enviarlo de nuevo', resent: 'Enviado de nuevo. Mira también en la carpeta de spam.',
  done: 'Ya iniciaste sesión', doneLead: 'Te llevamos a tus proyectos.', open: 'Ir a mis proyectos',
  down: 'El inicio de sesión no responde', downBody: 'Tus datos están a salvo. Esto suele resolverse en un minuto.', retry: 'Intentar de nuevo',
  asideSays: 'Tus tablas, tu API, en tu región.', perks: ['Postgres con API desde el primer minuto', 'Copias de seguridad cada día, guardadas 30 días', 'Gratis en tus propios servidores'],
  terms: 'Términos', privacy: 'Privacidad', help: 'Ayuda',
};
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
type Step = 'password' | 'code' | 'reset' | 'sent' | 'done';

export default function SignIn({ state = 'ready' }: { state?: 'ready' | 'loading' | 'error' }) {
  const { locale } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [step, setStep] = useState<Step>('password');
  const [email, setEmail] = useState('');
  const [problems, setProblems] = useState<FormProblem[]>([]);
  const [codeError, setCodeError] = useState<string>();
  const [checking, setChecking] = useState(false);
  const [resent, setResent] = useState(false);
  const [down, setDown] = useState(state === 'error');

  // Loading: while the app checks for a session, the real page with its words; the fields and buttons wait in their
  // own boxes, so that if there is no session nothing moves.
  const loading = state === 'loading';
  const wait = (n: ReactNode) => (loading ? <SkeletonOf>{n}</SkeletonOf> : n);

  const check = (v: FormData): FormProblem[] => {
    const e = String(v.get('email') ?? '').trim(), out: FormProblem[] = [];
    if (!e) out.push({ name: 'email', label: c.email, message: c.noEmail });
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) out.push({ name: 'email', label: c.email, message: c.badEmail });
    if (step === 'password' && !String(v.get('password') ?? '')) out.push({ name: 'password', label: c.password, message: c.noPassword });
    return out;
  };
  const verify = async (code: string) => {
    setChecking(true); setCodeError(undefined);
    await wait(700);
    setChecking(false);
    if (code === '000000') setCodeError(c.wrongCode); else setStep('done');
  };
  const back = <Button variant="quiet" icon="arrow-left" onClick={() => { setStep('password'); setProblems([]); }}>{c.back}</Button>;
  const view: Record<Step, { title: string; lead: string; body: ReactNode }> = {
    password: {
      title: c.signIn, lead: c.signInLead,
      body: (
        <Stack gap={5}>
          {down && <Alert tone="fail" title={c.down} actions={<Button size="sm" icon="refresh" onClick={() => setDown(false)}>{c.retry}</Button>}>{c.downBody}</Alert>}
          <Form label={c.signIn} validate={check} problems={problems} onSubmit={async (v) => {
            setEmail(String(v.get('email')));
            await wait(900);
            if (v.get('password') === 'wrong') setProblems([{ name: 'password', label: c.password, message: c.mismatch }]);
            else setStep('code');
          }}>
            {({ errorFor }) => (
              <>
                <Field label={c.email} error={errorFor('email')}>{wait(<EmailInput name="email" defaultValue={email} autoComplete="username" disabled={down} />)}</Field>
                <Field label={c.password} error={errorFor('password')}>{wait(<PasswordInput name="password" autoComplete="current-password" disabled={down} onChange={() => setProblems([])} />)}</Field>
                <div>{wait(<Button variant="quiet" size="sm" onClick={() => setStep('reset')}>{c.forgot}</Button>)}</div>
                {wait(<FormActions submitLabel={c.submit} busyLabel={c.busy} />)}
              </>
            )}
          </Form>
          <Divider label={c.or} />
          {wait(<Button icon="fingerprint" block disabled={down} onClick={() => setStep('done')}>{c.passkey}</Button>)}
        </Stack>
      ),
    },
    code: {
      title: c.code, lead: c.codeLead,
      body: (
        <Stack gap={5}>
          <Field label={c.codeLabel} error={codeError}><OtpInput autoFocus disabled={checking} onComplete={verify} /></Field>
          {checking && <Notice tone="info" icon="shield">{c.busy}</Notice>}
          {back}
        </Stack>
      ),
    },
    reset: {
      title: c.reset, lead: c.resetLead,
      body: (
        <Form label={c.reset} validate={check} onSubmit={async (v) => { setEmail(String(v.get('email'))); await wait(800); setResent(false); setStep('sent'); }}>
          {({ errorFor }) => (
            <>
              <Field label={c.email} error={errorFor('email')}><EmailInput name="email" defaultValue={email} autoComplete="username" /></Field>
              <FormActions submitLabel={c.sendLink} busyLabel={c.sending} cancel={back} />
            </>
          )}
        </Form>
      ),
    },
    sent: {
      title: c.sent, lead: c.sentLead(email),
      body: (
        <Stack gap={4}>
          {resent && <Notice tone="ok">{c.resent}</Notice>}
          <Button icon="mail" disabled={resent} onClick={() => setResent(true)}>{c.resend}</Button>
          {back}
        </Stack>
      ),
    },
    done: { title: c.done, lead: c.doneLead, body: <Button variant="primary" iconEnd="arrow-right" href="#projects">{c.open}</Button> },
  };
  const v = view[step];
  return (
    <AuthLayout title={v.title} lead={v.lead} brandHref="#"
      after={step === 'password' ? <>{c.newHere} <a href="#sign-up">{c.create}</a></> : undefined}
      aside={<><Says size="lg">{c.asideSays}</Says><List label={c.asideSays}>{c.perks.map((p) => <ListItem key={p} icon="check" title={p} />)}</List></>}
      footer={<><a href="#terms">{c.terms}</a><a href="#privacy">{c.privacy}</a><a href="#help">{c.help}</a></>}>
      {v.body}
    </AuthLayout>
  );
}

En un celular

El mismo flujo a 390 px: la tarjeta se vuelve la página y el panel lateral se va.

Skeleton

Mientras la app revisa si ya hay una sesión: la página real con sus palabras; los campos y los botones esperan en sus propias cajas.

Inicia sesión en Sypnia

Usa el correo con el que te registraste.

¿Eres nuevo en Sypnia? Crea una cuenta

Cuando el inicio de sesión no responde

El servicio está caído: el formulario se queda, deshabilitado, bajo un mensaje que dice qué pasó y deja intentar de nuevo.

Inicia sesión en Sypnia

Usa el correo con el que te registraste.

¿Eres nuevo en Sypnia? Crea una cuenta

Cuándo usarlo

Úsalo cuando

  • La entrada a cualquier consola de Sypnia, y a las apps hechas sobre Sypnia Data.
  • Errores que dicen qué campo corregir: un correo que no parece correo, una contraseña que no coincide. Nunca cuál de los dos estaba mal, así nadie sabe si una cuenta existe.

No lo uses cuando

  • Pedir cualquier otra cosa en esta página: el nombre, el plan y el equipo son del registro y de la bienvenida.
  • Decir «este correo no tiene cuenta» tras pedir restablecer: la respuesta es la misma para cualquier dirección.

Para todos

  • Cada paso es un encabezado; cuando el paso cambia el foco pasa a él, así un lector de pantalla dice dónde está la persona.
  • Los campos les dicen a los gestores de contraseñas qué guardan (autocomplete="username", current-password).
  • Las casillas del código se leen como un solo campo; pegar el código llena todas, y el código se revisa apenas se llena la última.
  • El panel lateral solo dice lo que la persona obtiene: se oculta en pantallas angostas y nada de él hace falta para iniciar sesión.

Props

AuthLayoutTipoPor defecto
after

One line under the card: «New to Sypnia? Create an account».

ReactNode
aside

Beside the card when the layout is wide enough (60rem and more): what the person gets, a quote. Hidden on narrower screens, so nothing in it may be needed to finish the task.

ReactNode
brand

The mark at the top. Defaults to the Sypnia logo.

ReactNode
brandHref

Where the mark leads. Without it the mark is not a link.

string
className string
footer

The bottom line: terms, privacy, help.

ReactNode
lead

One sentence under the title: what happens here, or what to do next.

ReactNode
plain

No card around the content: for error and not-found pages, which say one thing and offer a way out.

boolean
title

What this step is, in the voice: «Sign in to Sypnia», «Check your email». It is the page's only h1.

ReactNode
top

The end of the top bar: a LanguageSwitch, a way back to the site.

ReactNode
width

`sm` (26rem) for one or two fields, `md` (34rem) for longer forms and step-by-step tasks.

"sm" | "md" sm
  1. En un computador
  2. En un celular
  3. Skeleton
  4. Cuando el inicio de sesión no responde
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos