Spanish Total.js
Italiano
Documentazione Per agenti IA
Indice

Accedere da un'app Node.js

Un piccolo server Node.js che fa accedere gli utenti con Facebook tramite OpenAuth.

.md GitHub
In questa pagina

Questo server ha due indirizzi: /login/facebook/ avvia l'accesso, e /auth/ riceve l'utente di ritorno e legge il profilo. Usa solo Node.js (18 o più recente, per fetch).

Il codice

Salvalo come app.js e compila le tre costanti in cima:

const http = require('http');
const crypto = require('crypto');

const OPENAUTH = 'https://auth.example.com';   // your OpenAuth address
const TOKEN = 'paste-your-app-token-here';      // a token from Tokens in OpenAuth
const APP = 'https://www.example.com';          // the public address of this app

const server = http.createServer(async function(req, res) {

    const url = new URL(req.url, APP);

    // 1. The user clicks "Sign in with Facebook"
    if (url.pathname === '/login/facebook/') {

        const sessionid = crypto.randomUUID();

        const response = await fetch(OPENAUTH + '/', {
            method: 'POST',
            headers: { 'content-type': 'application/json', 'x-token': TOKEN },
            body: JSON.stringify({ serviceid: 'facebook', sessionid: sessionid, url: APP + '/auth/' })
        });

        if (!response.ok) {
            res.writeHead(502, { 'content-type': 'text/plain' });
            res.end('Sign-in is not available right now.');
            return;
        }

        const address = await response.json();
        res.writeHead(302, { location: address, 'set-cookie': 'signin=' + sessionid + '; Path=/; HttpOnly; SameSite=Lax' });
        res.end();
        return;
    }

    // 2. OpenAuth sends the user back here with ?sessionid=...
    if (url.pathname === '/auth/') {

        const sessionid = url.searchParams.get('sessionid');
        const cookie = (req.headers.cookie || '').match(/(?:^|;\s*)signin=([^;]+)/);

        if (!sessionid || !cookie || cookie[1] !== sessionid) {
            res.writeHead(400, { 'content-type': 'text/plain' });
            res.end('Invalid sign-in.');
            return;
        }

        const response = await fetch(OPENAUTH + '/sessions/?id=' + encodeURIComponent(sessionid), {
            headers: { 'x-token': TOKEN }
        });

        if (!response.ok) {
            res.writeHead(401, { 'content-type': 'text/plain' });
            res.end('The sign-in has expired. Please try again.');
            return;
        }

        const profile = await response.json();

        // 3. Find or create the user in your database by profile.serviceid + profile.id
        res.writeHead(200, { 'content-type': 'text/plain' });
        res.end('Hello ' + profile.name + ' (' + profile.email + ')');
        return;
    }

    res.writeHead(404, { 'content-type': 'text/plain' });
    res.end('Not found');
});

server.listen(3000);

Eseguirlo

node app.js

Metti un link a /login/facebook/ nella tua pagina di accesso. Dopo l'accesso, l'utente arriva su /auth/ e vede un saluto.

Come funziona

  • L'ID di sessione è casuale e viene salvato anche in un cookie. Su /auth/, il server accetta solo l'ID di sessione avviato da questo browser, così nessuno può completare un accesso con un link ricevuto da qualcun altro.
  • Il token resta sul server; il browser non lo vede mai.
  • Se l'utente ci mette più di 15 minuti, /sessions/ risponde 404 e il server gli chiede di riprovare.

In un'app vera, sostituisci il saluto con la tua sessione: cerca l'utente tramite profile.serviceid e profile.id, poi fallo accedere. Leggi Il profilo dell'utente.

Fatto in Europa