Prihlásenie z aplikácie Node.js
Malý server Node.js, ktorý prihlasuje používateľov cez Facebook pomocou OpenAuth.
Na tejto stránke
Tento server má dve adresy: /login/facebook/ spúšťa prihlásenie a /auth/ prijme vracajúceho sa používateľa a prečíta profil. Používa len Node.js (18 alebo novší, kvôli fetch).
Kód
Ulož ho ako app.js a vyplň tri konštanty na začiatku:
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);Spustenie
node app.jsNa svoju prihlasovaciu stránku daj odkaz na /login/facebook/. Po prihlásení používateľ skončí na /auth/ a uvidí pozdrav.
Ako to funguje
- ID relácie je náhodné a ukladá sa aj do cookie. Na
/auth/server prijme len ID relácie, ktoré spustil tento prehliadač, takže nikto nemôže dokončiť prihlásenie s odkazom, ktorý dostal od niekoho iného. - Token zostáva na serveri; prehliadač ho nikdy nevidí.
- Ak to používateľovi trvá dlhšie ako 15 minút,
/sessions/odpovie404a server ho požiada, aby to skúsil znova.
V skutočnej aplikácii nahraď pozdrav vlastnou reláciou: vyhľadaj používateľa podľa profile.serviceid a profile.id a potom ho prihlás. Pozri si Profil používateľa.