Compare commits

...

10 Commits

Author SHA1 Message Date
ea553cfc3e add restry-ui proxy. 2024-06-17 16:27:43 +00:00
9e3bf28451 add cross cookie login. 2024-06-16 13:37:26 +00:00
702b4a3358 1.实现cookie登录。 2024-06-16 06:50:10 +00:00
cd1e47f34d add proxy for homebox. 2024-06-02 23:32:41 +08:00
bfd0425f04 add chatgpt proxy. 2024-05-31 22:47:31 +08:00
5256ab94de 1.增加unraid反向代理body最大大小。 2024-05-06 16:54:34 +08:00
3fa2c054e2 add exception handle. 2024-05-05 22:00:15 +08:00
db1e7d5cfb update usage. 2024-05-05 17:24:41 +08:00
5cf24d07f8 add ha test. 2024-05-03 22:30:46 +08:00
luocai
be7fb5bb8a update frp proxy. 2024-03-12 09:51:28 +08:00
17 changed files with 542 additions and 130 deletions

View File

@ -5,7 +5,7 @@
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}/build/_deps/kylin-src/Universal",
"/opt/Libraries/boost_1_84_0/include"
"/opt/Libraries/boost_1_85_0/include"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",

View File

@ -5,7 +5,9 @@
#include "IoContext.h"
#include "ServiceLogic.h"
#include "ServiceManager.h"
#include "SystemUsage.h"
#include "WeChatContext/CorporationContext.h"
#include <boost/stacktrace.hpp>
Application::Application(const std::string &path)
: ApplicationSettings(path), m_router{std::make_shared<boost::urls::router<RequestHandler>>()} {
@ -122,6 +124,9 @@ Application::Application(const std::string &path)
m_ioContext = Amass::Singleton<IoContext>::instance<Amass::Construct>(getThreads());
m_timer = std::make_shared<boost::asio::system_timer>(*m_ioContext->ioContext());
m_systemUsage = std::make_shared<SystemUsage>(*m_ioContext->ioContext(), getHomeAssistantAccessToken());
m_systemUsage->start();
alarmTask();
}
@ -131,7 +136,14 @@ boost::asio::io_context &Application::ioContext() {
const Application::RequestHandler *Application::find(boost::urls::segments_encoded_view path,
boost::urls::matches_base &matches) const noexcept {
return m_router->find(path, matches);
const Application::RequestHandler *ret = nullptr;
try {
ret = m_router->find(path, matches);
} catch (const std::exception &e) {
boost::stacktrace::stacktrace trace = boost::stacktrace::stacktrace::from_current_exception();
LOG(error) << e.what() << ", trace:\n" << trace;
}
return ret;
}
int Application::exec() {

View File

@ -10,6 +10,7 @@
class HttpSession;
class ChatRoom;
class SystemUsage;
class IoContext;
class Application : public ApplicationSettings<Application>, public std::enable_shared_from_this<Application> {
@ -22,6 +23,7 @@ public:
BUILD_SETTING(uint16_t, Port, 8081);
BUILD_SETTING(uint32_t, Threads, std::thread::hardware_concurrency());
BUILD_SETTING(std::string, DocumentRoot, ".");
BUILD_SETTING(std::string, HomeAssistantAccessToken, "");
INITIALIZE_FIELDS(Server, Port, Threads, DocumentRoot);
Application(const std::string &path);
@ -40,6 +42,7 @@ private:
std::shared_ptr<boost::urls::router<RequestHandler>> m_router;
std::shared_ptr<boost::asio::system_timer> m_timer;
std::shared_ptr<ChatRoom> m_charRoom;
std::shared_ptr<SystemUsage> m_systemUsage;
};
#endif // __SETTINGS_H__

View File

@ -11,6 +11,7 @@ add_executable(Server main.cpp
ResponseUtility.h ResponseUtility.cpp
ServiceLogic.h ServiceLogic.inl ServiceLogic.cpp
ServiceManager.h
SystemUsage.h SystemUsage.cpp
UdpServer.h UdpServer.cpp
WeChatContext/CorporationContext.h WeChatContext/CorporationContext.cpp
WeChatContext/WeChatContext.h WeChatContext/WeChatContext.cpp

View File

@ -1,6 +1,7 @@
#include "HttpSession.h"
#include "Application.h"
#include <boost/config.hpp>
#include <boost/stacktrace.hpp>
#include <boost/url/parse_path.hpp>
#include <boost/url/url_view.hpp>
#include <iostream>
@ -72,7 +73,12 @@ void HttpSession::onRead(boost::beast::error_code ec, std::size_t) {
boost::urls::matches matches;
auto handler = application->find(*path, matches);
if (handler) {
(*handler)(*this, request, matches);
try {
(*handler)(*this, request, matches);
} catch (const std::exception &e) {
boost::stacktrace::stacktrace trace = boost::stacktrace::stacktrace::from_current_exception();
LOG(error) << e.what() << ", trace:\n" << trace;
}
} else {
std::ostringstream oss;
oss << "The resource '" << request.target() << "' was not found.";

96
Server/SystemUsage.cpp Normal file
View File

@ -0,0 +1,96 @@
#include "SystemUsage.h"
#include "BoostLog.h"
#include "NetworkUtility.h"
#include <boost/json/object.hpp>
#include <boost/json/serialize.hpp>
#include <fstream>
#include <sstream>
#include <sys/statvfs.h>
#include <sys/sysinfo.h>
SystemUsage::SystemUsage(boost::asio::io_context &ioContext, const std::string &accessToken)
: m_ioContext(ioContext), m_accessToken(accessToken) {
m_timer = std::make_shared<boost::asio::system_timer>(m_ioContext);
// LOG(info) << "access token: " << m_accessToken;
}
void SystemUsage::start() {
m_timer->expires_after(std::chrono::seconds(10));
m_timer->async_wait([this](const boost::system::error_code &error) {
if (error) {
LOG(error) << error.message();
return;
}
auto currentCpuStats = readCpuData();
int usage = 100.0f * cpuUsage(m_lastCpuStats, currentCpuStats);
publish("yuyun_cpu_usage", usage, "%", "CPU占用率");
publish("yuyun_disk_usage", static_cast<int>(100.0f * diskUsage("/")), "%", "磁盘占用率");
m_lastCpuStats = currentCpuStats;
start();
});
}
void SystemUsage::publish(const std::string_view &deviceName, float value, const std::string_view &unit,
const std::string_view &friendlyName) {
// LOG(info) << "cpu usage: " << usage << "%";
Http::Client http(m_ioContext, Http::Transparent);
std::ostringstream oss;
oss << "Bearer " << m_accessToken;
http.addRequestField(boost::beast::http::field::authorization, oss.str());
http.addRequestField(boost::beast::http::field::content_type, "application/json");
boost::json::object request;
request["state"] = value;
boost::json::object attributes;
attributes["unit_of_measurement"] = unit;
attributes["friendly_name"] = friendlyName;
request["attributes"] = std::move(attributes);
oss.str("");
oss << "/api/states/sensor." << deviceName;
boost::system::error_code error;
auto reply = http.post("iot.amass.fun", "80", oss.str(), boost::json::serialize(request), error);
if (error) {
LOG(error) << error.message();
}
}
SystemUsage::CpuStats SystemUsage::readCpuData() {
CpuStats result;
std::ifstream proc_stat("/proc/stat");
if (proc_stat.good()) {
std::string line;
getline(proc_stat, line);
unsigned int *stats_p = (unsigned int *)&result;
std::stringstream iss(line);
std::string cpu;
iss >> cpu;
while (iss >> *stats_p) {
stats_p++;
};
}
proc_stat.close();
return result;
}
float SystemUsage::cpuUsage(const CpuStats &first, const CpuStats &second) {
const float active_time = static_cast<float>(second.totalActive() - first.totalActive());
const float idle_time = static_cast<float>(second.totalIdle() - first.totalIdle());
const float total_time = active_time + idle_time;
return active_time / total_time;
}
float SystemUsage::diskUsage(const std::string &disk) {
struct statvfs diskData;
statvfs(disk.c_str(), &diskData);
auto total = diskData.f_blocks;
auto free = diskData.f_bfree;
auto diff = total - free;
float result = static_cast<float>(diff) / total;
return result;
}

48
Server/SystemUsage.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef __SYSTEMUSAGE_H__
#define __SYSTEMUSAGE_H__
#include <boost/asio/system_timer.hpp>
/**
* @brief https://github.com/improvess/cpp-linux-system-stats
*
*/
class SystemUsage {
public:
struct CpuStats { // see http://www.linuxhowtos.org/manpages/5/proc.htm
int user;
int nice;
int system;
int idle;
int iowait;
int irq;
int softirq;
int steal;
int guest;
int guestNice;
int totalIdle() const {
return idle + iowait;
}
int totalActive() const {
return user + nice + system + irq + softirq + steal + guest + guestNice;
}
};
SystemUsage(boost::asio::io_context &ioContext, const std::string &accessToken);
void start();
protected:
void publish(const std::string_view &deviceName, float value, const std::string_view &unit,
const std::string_view &friendlyName);
CpuStats readCpuData();
float cpuUsage(const CpuStats &first, const CpuStats &second);
float diskUsage(const std::string &disk);
private:
boost::asio::io_context &m_ioContext;
std::shared_ptr<boost::asio::system_timer> m_timer;
std::string m_accessToken;
CpuStats m_lastCpuStats;
};
#endif // __SYSTEMUSAGE_H__

View File

@ -48,7 +48,7 @@ void CorporationContext::sendMessage(MessageType type, const std::string &messag
}
void CorporationContext::notify(const RequestType &request) {
boost::json::error_code error;
boost::system::error_code error;
auto json = boost::json::parse(request.body(), error);
if (error) {
LOG(error) << "parse: [" << request.body() << "] failed, reason: " << error.message();

View File

@ -2,9 +2,7 @@
user root;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
error_log logs/error.log info;
#pid logs/nginx.pid;
events {
@ -29,7 +27,7 @@ http {
gzip on;
gzip_types application/octet-stream text/markdown text/plain application/json application/x-javascript text/css application/xml text/javascript application/javascript application/x-httpd-php image/jpeg image/gif image/png;
init_by_lua_file lua/initialize.lua;
upstream local {
server 127.0.0.1:8081;
}
@ -54,37 +52,12 @@ http {
server 127.0.0.1:8087;
}
upstream typesense {
server 127.0.0.1:8108;
upstream frp_pve {
server 127.0.0.1:8088;
}
init_by_lua_file lua/settings.lua;
server {
listen 443 ssl;
server_name frp.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/frp.amass.fun.pem;
ssl_certificate_key cert/frp.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_board;
}
upstream typesense {
server 127.0.0.1:8108;
}
server {
@ -93,6 +66,7 @@ http {
client_header_timeout 120s;
client_body_timeout 120s;
client_max_body_size 512m; #上传文件最大支持512m
ssl_certificate cert/unraid.amass.fun.pem;
ssl_certificate_key cert/unraid.amass.fun.key;
@ -111,33 +85,7 @@ http {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
}
}
server {
listen 443 ssl;
server_name chatgpt.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/chatgpt.amass.fun.pem;
ssl_certificate_key cert/chatgpt.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
access_by_lua_file lua/authentication.lua;
}
}
@ -147,7 +95,7 @@ http {
client_header_timeout 120s;
client_body_timeout 120s;
client_max_body_size 512m;
client_max_body_size 512m; #上传文件最大支持512m
ssl_certificate cert/pve.amass.fun.pem;
ssl_certificate_key cert/pve.amass.fun.key;
@ -156,6 +104,33 @@ http {
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass https://frp_pve;
}
}
server {
listen 443 ssl;
server_name iot.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/iot.amass.fun.pem;
ssl_certificate_key cert/iot.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
@ -169,6 +144,165 @@ http {
}
}
server {
listen 443 ssl;
server_name docker.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/docker.amass.fun.pem;
ssl_certificate_key cert/docker.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
access_by_lua_file lua/basic_authentication_proxy.lua;
proxy_pass http://frp_http_proxy;
}
}
server {
listen 443 ssl;
server_name money.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/money.amass.fun.pem;
ssl_certificate_key cert/money.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
}
}
server {
listen 443 ssl;
server_name money-mobile.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/money-mobile.amass.fun.pem;
ssl_certificate_key cert/money-mobile.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
}
}
server {
listen 443 ssl;
server_name zainaer.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/zainaer.amass.fun.pem;
ssl_certificate_key cert/zainaer.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
}
}
server {
listen 80;
server_name zainaer.amass.fun;
rewrite ^(.*)$ https://zainaer.amass.fun$1 permanent;
}
server {
listen 80;
server_name iot.amass.fun;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
}
}
server {
listen 443 ssl;
server_name next.amass.fun;
client_header_timeout 120s;
client_body_timeout 120s;
ssl_certificate cert/next.amass.fun.pem;
ssl_certificate_key cert/next.amass.fun.key;
ssl_session_timeout 5m; #缓存有效期
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #加密算法
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #安全链接可选的加密协议
ssl_prefer_server_ciphers on; #使用服务器端的首选算法
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header x-wiz-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://frp_http_proxy;
access_by_lua_file lua/authentication.lua;
}
}
server {
listen 443 ssl;
server_name gitea.amass.fun;
@ -229,26 +363,13 @@ http {
index index.html index.htm;
}
location /lua {
default_type text/html;
content_by_lua_file lua/helloworld.lua;
}
location = /api/login {
content_by_lua_file lua/login.lua;
}
location = /blog/profile {
content_by_lua_file lua/profile.lua;
}
location /video {
access_by_lua_file lua/access.lua;
proxy_pass http://local;
}
location /phtot_gallery {
proxy_pass http://local;
location ^~ /api/v1/login {
default_type 'application/json; charset=utf-8';
content_by_lua_file lua/login.lua;
}
location ~ /api/v1/.*$ {
@ -308,10 +429,6 @@ http {
root amass_blog;
}
location ^~ /index/ {
try_files $uri /index.html;
}
location /wechat {
proxy_pass http://local;
}
@ -319,12 +436,11 @@ http {
location /twikoo {
proxy_pass http://twikoo;
}
}
server {
listen 80;
server_name pve.amass.fun;
rewrite ^(.*)$ https://pve.amass.fun$1 permanent;
location /frp/ {
proxy_pass http://frp_board/;
proxy_redirect /static/ /frp/static/;
}
}
server {

23
Server/lua/accounts.lua Normal file
View File

@ -0,0 +1,23 @@
local M = {}
local password_path = "password.txt"
function M.credentials()
local file = io.open(password_path, "r")
if not file then
ngx.log(ngx.INFO, "无法打开文件: ", password_path)
return
end
local credentials = {}
for line in file:lines() do
local account, password = line:match("([^=]+)=([^=]+)")
if account and password then
credentials[account] = password
end
end
file:close()
return credentials
end
return M

View File

@ -0,0 +1,13 @@
local session, err, exists = require "resty.session".open()
if exists and session:get("authenticated") then
ngx.log(ngx.INFO, session:get("account"), " 访问")
else
local server = ""
if ngx.var.server_port == "80" then
server = ngx.var.host
else
server = ngx.var.host .. ":" .. ngx.var.server_port
end
local target_url = ngx.var.scheme .. "://" .. server .. ngx.var.request_uri
ngx.redirect('https://amass.fun/LoginPage?next=' .. ngx.escape_uri(target_url))
end

View File

@ -0,0 +1,33 @@
local auth_header = ngx.var.http_authorization
local function authenticate()
ngx.header.content_type = 'text/plain'
ngx.header.www_authenticate = 'Basic realm="Restricted Area"'
ngx.status = ngx.HTTP_UNAUTHORIZED
ngx.say('Unauthorized')
ngx.exit(ngx.HTTP_UNAUTHORIZED)
end
if not auth_header then
return authenticate()
end
local _, _, encoded = string.find(auth_header, "Basic%s+(.+)")
if not encoded then
return authenticate()
end
local decoded = ngx.decode_base64(encoded)
local user_account, user_password = decoded:match("([^:]+):(.+)")
ngx.log(ngx.INFO, encoded, " ", user_account, " ", user_password)
local accounts = require("lua/accounts")
local credentials = accounts.credentials()
if credentials and credentials[user_account] == user_password then
return
else
return authenticate()
end

View File

@ -0,0 +1,22 @@
local session, err, exists = require "resty.session".open()
if exists and session:get("authenticated") then
local account = session:get("account")
ngx.log(ngx.INFO, session:get("account"), " 访问")
local accounts = require("lua/accounts")
local credentials = accounts.credentials()
local password = ""
if credentials then
password = credentials[account]
end
local auth_value = ngx.encode_base64(account .. ':' .. password)
ngx.req.set_header("Authorization", "Basic " .. auth_value)
else
local server = ""
if ngx.var.server_port == "80" then
server = ngx.var.host
else
server = ngx.var.host .. ":" .. ngx.var.server_port
end
local target_url = ngx.var.scheme .. "://" .. server .. ngx.var.request_uri
ngx.redirect('https://amass.fun/LoginPage?next=' .. ngx.escape_uri(target_url))
end

View File

@ -1,14 +0,0 @@
ngx.log(ngx.ERR, "cookie a:", ngx.var.cookie_a)
ngx.header['Set-Cookie'] = {'a=32; path=/ ', 'b=4; path=/'}
ngx.header['Content-Type'] = "text/html; charset=utf-8";
local session = require"resty.session".start()
ngx.log(ngx.ERR, "cookie a:", ngx.var.cookie_a)
session.data.name = "OpenResty Fan"
session.cookie.path = "/123"
session:save()
ngx.say("<p>123Hello,world 中国</p>")

9
Server/lua/settings.lua → Server/lua/initialize.lua Executable file → Normal file
View File

@ -1,3 +1,12 @@
require "resty.session".init({
cookie_http_only=true,
remember = true,
storage = "cookie",
remember_rolling_timeout = 3600,
})
app_version="0.0.1"
private_folder = {"个人笔记"};
user_infomation = {

67
Server/lua/login.lua Executable file → Normal file
View File

@ -1,21 +1,60 @@
local cjson = require "cjson"
local function add_domain(cookies, key, domain)
if type(cookies) == "string" then -- 确保 set_cookies 是一个表
cookies = { cookies }
end
local new_cookies = {} -- 查找并修改名为 'remember' 的 Cookie
for _, cookie in ipairs(cookies) do
local cookie_key, value = string.match(cookie, "^%s*(.-)%s*=%s*(.-)%s*;")
if cookie_key == key then
local new_cookie = value .. "; Domain=" .. domain .. "; Path=/; HttpOnly; SameSite=Lax"
table.insert(new_cookies, key.."=" .. new_cookie)
else
table.insert(new_cookies, cookie)
end
end
return new_cookies;
end
ngx.req.read_body()
local body = ngx.req.get_body_data()
local json = cjson.decode(body)
local password = json["password"];
local result = {}
if (password == user_password) then
result.code = 0
result.message = "succuess"
local session = require"resty.session".start()
session.data.identify = "myself"
session.cookie.idletime = 120
session:save()
else
result.code = 1
result.message = "faliure"
if not body then
ngx.status = ngx.HTTP_BAD_REQUEST
ngx.say("No body found")
return
end
ngx.say(cjson.encode(result));
local ok, json_data = pcall(cjson.decode, body)
if not ok then
ngx.status = ngx.HTTP_BAD_REQUEST
ngx.say("Invalid JSON")
return
end
local user_account = json_data.account
local user_password = json_data.password
local reply = {}
local session = require "resty.session".start()
local accounts = require("lua/accounts")
local credentials = accounts.credentials()
if credentials and credentials[user_account] == user_password then
reply.status = 0
reply.message = "登录成功"
session:set("account", user_account)
session:set("authenticated", true)
session:save()
ngx.header["Set-Cookie"] = add_domain(ngx.header["Set-Cookie"], "remember", ".amass.fun");
else
reply.status = -100
reply.message = "登录失败"
end
ngx.say(cjson.encode(reply))

View File

@ -5,16 +5,19 @@ build_path=${base_path}/build
libraries_root="/opt/Libraries"
server_location=/root/HttpServer
if command -v cmake >/dev/null 2>&1; then
cmake_exe=cmake
else
cmake_exe=/opt/Qt/Tools/CMake/bin/cmake
fi
function cmake_scan() {
if [ ! -d ${build_path} ]; then
mkdir ${build_path}
fi
/opt/Qt/Tools/CMake/bin/cmake \
-G Ninja \
-S ${base_path} \
-B ${build_path} \
${cmake_exe} -G Ninja -S ${base_path} -B ${build_path} \
-DCMAKE_BUILD_TYPE=Debug \
-DBOOST_ROOT=${libraries_root}/boost_1_84_0
-DBOOST_ROOT=${libraries_root}/boost_1_85_0
}
function build() {
@ -24,9 +27,7 @@ function build() {
if [ $? -ne 0 ]; then
exit 1
fi
/opt/Qt/Tools/CMake/bin/cmake \
--build ${build_path} \
--target all
${cmake_exe} --build ${build_path} --target all
if [ $? -ne 0 ]; then
exit 1
fi
@ -39,13 +40,17 @@ function deploy() {
echo "build backend failed ..."
exit 1
fi
rsync -azv build/Server/HttpServer Server/conf root@amass.fun:${server_location}
rsync -azv build/Server/HttpServer Server/conf Server/lua root@amass.fun:${server_location}
ssh root@amass.fun "pkill HttpServer; source /etc/profile && \
openresty -p ${server_location} -s reload && \
cd ${server_location}; \
nohup ./HttpServer >logs/HttpServer.log 2>&1 &"
}
function init() {
scp -r /opt/Libraries/boost_1_85_0 root@amass.fun:/opt/Libraries/
}
function main() {
local cmd=$1
shift 1