BlueGit

timfa filemanager

Files

filemanager / server / routes / auth.js

auth.js

fixes and updates
timfa Tim Falken · pushed by timfa · 6 months ago
0ae63c84 History
auth.js 4.9 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const bcrypt = require('bcrypt');
5const router = express.Router();
6
7const { getDb } = require('../db');
8const { getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient } = require('../crypto');
9const { createToken, requireAuth, revokeSession } = require('../auth');
10
11const BCRYPT_ROUNDS = 12;
12
13function extractCredentials (body)
14{
15 if (body && body.encrypted && body.encrypted.plaintext)
16 {
17 return body.encrypted.plaintext;
18 }
19
20 if (body && body.encrypted)
21 {
22 const plain = hybridDecrypt(body.encrypted);
23 return JSON.parse(plain);
24 }
25
26 if (body && typeof body.username === 'string' && typeof body.password === 'string')
27 {
28 return { username: body.username, password: body.password };
29 }
30
31 throw new Error('Invalid payload');
32}
33
34function makeAuthResponse (token, clientPublicKey)
35{
36 if (clientPublicKey)
37 {
38 return { encrypted: hybridEncryptForClient(token, clientPublicKey) };
39 }
40 return { token };
41}
42
43// ---------------------------------------------------------------------------
44// GET /api/auth/server-key
45// Returns the server's RSA public key as JWK so the browser can import it.
46// ---------------------------------------------------------------------------
47router.get('/server-key', (req, res) =>
48{
49 res.json({ publicKey: getServerPublicKeyJwk() });
50});
51
52// ---------------------------------------------------------------------------
53// GET /api/auth/setup-needed
54// Returns { needed: true } if no users exist yet.
55// ---------------------------------------------------------------------------
56router.get('/setup-needed', (req, res) =>
57{
58 const db = getDb();
59 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
60 res.json({ needed: count === 0 });
61});
62
63// ---------------------------------------------------------------------------
64// POST /api/auth/setup
65// Creates the first admin account (only when no users exist).
66// Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey }
67// The encrypted payload must be: { username, password }
68// ---------------------------------------------------------------------------
69router.post('/setup', (req, res) =>
70{
71 const db = getDb();
72 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
73 if (count > 0)
74 {
75 return res.status(403).json({ error: 'Setup already completed.' });
76 }
77
78 let credentials;
79 try
80 {
81 credentials = extractCredentials(req.body);
82 } catch
83 {
84 return res.status(400).json({ error: 'Invalid encrypted payload.' });
85 }
86
87 const { username, password } = credentials;
88 if (!username || !password || username.length < 1 || password.length < 8)
89 {
90 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
91 }
92
93 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
94 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run(
95 [username, hash, '{}']
96 );
97
98 // Issue token
99 const token = createToken(username, req, req.body.fingerprint || '');
100 res.json(makeAuthResponse(token, req.body.clientPublicKey));
101});
102
103// ---------------------------------------------------------------------------
104// POST /api/auth/login
105// Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey, fingerprint }
106// The encrypted payload must be: { username, password }
107// ---------------------------------------------------------------------------
108router.post('/login', (req, res) =>
109{
110 let credentials;
111 try
112 {
113 credentials = extractCredentials(req.body);
114 } catch
115 {
116 return res.status(400).json({ error: 'Invalid encrypted payload.' });
117 }
118
119 const { username, password } = credentials;
120 if (!username || !password)
121 {
122 return res.status(400).json({ error: 'Invalid credentials.' });
123 }
124
125 const db = getDb();
126 const user = db.prepare('SELECT * FROM users WHERE username = ?').get([username]);
127
128 if (!user || !bcrypt.compareSync(password, user.password_hash))
129 {
130 return res.status(401).json({ error: 'Invalid credentials.' });
131 }
132
133 const fingerprint = req.body.fingerprint || '';
134 const token = createToken(username, req, fingerprint);
135 res.json(makeAuthResponse(token, req.body.clientPublicKey));
136});
137
138// ---------------------------------------------------------------------------
139// GET /api/auth/me
140// Returns the current user's basic info.
141// ---------------------------------------------------------------------------
142router.get('/me', requireAuth, (req, res) =>
143{
144 res.json({
145 username: req.user.username,
146 isAdmin: req.user.isAdmin,
147 permissions: req.user.permissions,
148 });
149});
150
151// ---------------------------------------------------------------------------
152// POST /api/auth/logout
153// Revokes the active authenticated session token.
154// ---------------------------------------------------------------------------
155router.post('/logout', requireAuth, (req, res) =>
156{
157 revokeSession(req.authSessionId);
158 res.json({ ok: true });
159});
160
161module.exports = router;