mirror of
https://github.com/wg-easy/wg-easy.git
synced 2025-10-21 06:39:34 +08:00
Support for sessionless HTTP API authentication
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const bcrypt = require('bcrypt');
|
||||
|
||||
const express = require('express');
|
||||
const expressSession = require('express-session');
|
||||
@@ -35,7 +36,7 @@ module.exports = class Server {
|
||||
return RELEASE;
|
||||
})))
|
||||
|
||||
// Authentication
|
||||
// Authentication
|
||||
.get('/api/session', Util.promisify(async (req) => {
|
||||
const requiresPassword = !!process.env.PASSWORD;
|
||||
const authenticated = requiresPassword
|
||||
@@ -66,7 +67,7 @@ module.exports = class Server {
|
||||
debug(`New Session: ${req.session.id}`);
|
||||
}))
|
||||
|
||||
// WireGuard
|
||||
// WireGuard
|
||||
.use((req, res, next) => {
|
||||
if (!PASSWORD) {
|
||||
return next();
|
||||
@@ -76,6 +77,22 @@ module.exports = class Server {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (req.path.startsWith('/api/') && req.headers['authorization']) {
|
||||
const authorizationHash = bcrypt.createHash('bcrypt')
|
||||
.update(req.headers['authorization'])
|
||||
.digest('hex');
|
||||
const passwordHash = bcrypt.createHash('bcrypt')
|
||||
.update(PASSWORD)
|
||||
.digest('hex');
|
||||
if (bcrypt.timingSafeEqual(Buffer.from(authorizationHash), Buffer.from(passwordHash))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
return res.status(401).json({
|
||||
error: 'Incorrect Password',
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(401).json({
|
||||
error: 'Not Logged In',
|
||||
});
|
||||
|
Reference in New Issue
Block a user