mirror of
https://github.com/yhl452493373/frps-panel.git
synced 2026-04-04 14:27:00 +08:00
Compare commits
33 Commits
1.5.0
...
b18d06d83d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b18d06d83d | ||
|
|
eef4390878 | ||
|
|
621893872d | ||
| 8d61054332 | |||
| 7cf43c869a | |||
| 70bddc6c1b | |||
| db0a36fc00 | |||
|
|
32ced78da4 | ||
|
|
8b574adfe6 | ||
|
|
6d787693dc | ||
|
|
e8de396f6c | ||
|
|
59af75a785 | ||
|
|
7c30c6d150 | ||
| 2f79a5d093 | |||
| 856bb3e27b | |||
|
|
7e09934024 | ||
| e2d276c4fc | |||
| c182e17abb | |||
| f41672a613 | |||
| 8eb72831c1 | |||
|
|
79bbf4a39c | ||
|
|
09401aae46 | ||
|
|
c0bce28529 | ||
|
|
1780913228 | ||
|
|
3c0f1e53aa | ||
|
|
65123ada6a | ||
|
|
21cf6b9c8b | ||
|
|
655fced1ce | ||
|
|
bf56c9ead9 | ||
|
|
d8c991883c | ||
|
|
0df98345d5 | ||
|
|
60f4c75d4b | ||
|
|
c7ee259531 |
3
Makefile
3
Makefile
@@ -4,7 +4,8 @@ export GOOS=linux
|
||||
export GOARCH=amd64
|
||||
|
||||
build: frps-panel
|
||||
cp ./config/frps-panel.ini ./bin/frps-panel.ini
|
||||
cp ./config/frps-panel.toml ./bin/frps-panel.toml
|
||||
cp ./config/frps-tokens.toml ./bin/frps-tokens.toml
|
||||
cp -r ./assets/ ./bin/assets/
|
||||
|
||||
frps-panel:
|
||||
|
||||
@@ -5,7 +5,8 @@ package: copy
|
||||
sh ./package.sh
|
||||
|
||||
copy: build
|
||||
cp ./config/frps-panel.ini ./release/frps-panel.ini
|
||||
cp ./config/frps-panel.toml ./release/frps-panel.toml
|
||||
cp ./config/frps-tokens.toml ./release/frps-tokens.toml
|
||||
cp -r ./assets/ ./release/assets/
|
||||
|
||||
build:
|
||||
|
||||
96
README.md
96
README.md
@@ -7,6 +7,7 @@ frp server plugin to show server info and support multiple users for [frp](https
|
||||
frps-panel will run as one single process and accept HTTP requests from frps.
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
@@ -35,62 +36,60 @@ frp version >= v0.31.0
|
||||
|
||||
### Usage
|
||||
|
||||
1. Create file `frps-panel.ini` including all support usernames and tokens.
|
||||
1. Create file `frps-panel.toml` including common config.
|
||||
|
||||
```ini
|
||||
```toml
|
||||
#frps-panel.toml
|
||||
[common]
|
||||
;plugin listen ip
|
||||
plugin_addr = 127.0.0.1
|
||||
;plugin listen port
|
||||
# frps panel config info
|
||||
plugin_addr = "127.0.0.1"
|
||||
plugin_port = 7200
|
||||
;the username of manage ui,optional
|
||||
admin_user = admin
|
||||
;the password of manage ui,optional
|
||||
admin_pwd = admin
|
||||
#admin_user = "admin"
|
||||
#admin_pwd = "admin"
|
||||
# specified login state keep time
|
||||
admin_keep_time = 0
|
||||
|
||||
; enable tls
|
||||
# enable tls
|
||||
tls_mode = false
|
||||
; tls_cert_file = cert.crt
|
||||
; tls_key_file = cert.key
|
||||
# tls_cert_file = "cert.crt"
|
||||
# tls_key_file = "cert.key"
|
||||
|
||||
; frp dashboard info
|
||||
dashboard_addr = 127.0.0.1
|
||||
# frp dashboard info
|
||||
dashboard_addr = "127.0.0.1"
|
||||
dashboard_port = 7500
|
||||
dashboard_user = admin
|
||||
dashboard_pwd = admin
|
||||
; if your frps dashboard enable tls, change this to true
|
||||
dashboard_tls = false
|
||||
|
||||
[users]
|
||||
;user user1 with meta_token 123
|
||||
user1 = 123
|
||||
;user user2 with meta_token abc
|
||||
user2 = abc
|
||||
|
||||
[ports]
|
||||
;user1 can only use ports 8080,9090 to 9010 ,other ports will fail to create proxy (frpc can normally startup)
|
||||
user1=8080,9090-9010
|
||||
|
||||
[domains]
|
||||
;user1 can only use domain web01.user1.com ,other domain will fail to create proxy (frpc can normally startup)
|
||||
user1=web01.user1.com
|
||||
|
||||
[subdomains]
|
||||
;user1 can only use subdomain web01 ,other subdomain will fail to create proxy (frpc can normally startup)
|
||||
user1=web01
|
||||
|
||||
[disabled]
|
||||
;user2 is disabled,when frpc use this user to connect with frps,if frpc is not startup,it cannot startup,if it's already startup,it will always show error logs on console
|
||||
user2 = disable
|
||||
dashboard_user = "admin"
|
||||
dashboard_pwd = "admin"
|
||||
```
|
||||
|
||||
One user each line. Username and token are split by `=`.
|
||||
2. Create file `frps-tokens.toml` to save users,it should be the same place with `frps-panel.toml`.this file will auto create by system.
|
||||
|
||||
2. Run frps-panel:
|
||||
```toml
|
||||
#frps-tokens.toml
|
||||
[tokens]
|
||||
[tokens.user1]
|
||||
user = "user1"
|
||||
token = "token1"
|
||||
comment = "user1 with token1"
|
||||
ports = [8080, "10000-10200"]
|
||||
domains = ["web01.domain.com", "web02.domain.com"]
|
||||
subdomains = ["web01", "web02"]
|
||||
enable = true
|
||||
[tokens.user2]
|
||||
user = "user2"
|
||||
token = "token2"
|
||||
comment = "user2 with token2"
|
||||
ports = [9080]
|
||||
domains = ["web11.domain.com", "web12.domain.com"]
|
||||
subdomains = ["web11", "web12"]
|
||||
enable = false
|
||||
```
|
||||
|
||||
`./frps-panel -c ./frps-panel.ini`
|
||||
|
||||
3. Register plugin in frps.
|
||||
3. Run frps-panel:
|
||||
|
||||
`./frps-panel -c ./frps-panel.toml`
|
||||
|
||||
4. Register plugin in frps.
|
||||
|
||||
```ini
|
||||
# frps.ini
|
||||
@@ -98,12 +97,13 @@ user2 = disable
|
||||
bind_port = 7000
|
||||
|
||||
[plugin.multiuser]
|
||||
; if you set tls_mode = true, you should change addr value to https://127.0.0.1:7200
|
||||
addr = 127.0.0.1:7200
|
||||
path = /handler
|
||||
ops = Login,NewWorkConn,NewUserConn,NewProxy,Ping
|
||||
```
|
||||
|
||||
4. Specify username and meta_token in frpc configure file.
|
||||
5. Specify username and meta_token in frpc configure file.
|
||||
|
||||
For user1:
|
||||
|
||||
@@ -137,6 +137,8 @@ local_port = 22
|
||||
remote_port = 6000
|
||||
```
|
||||
|
||||
6. Manage your users in browser via: http://127.0.0.1:7200 or https://127.0.0.1:7200
|
||||
|
||||
## Run as service
|
||||
|
||||
this example is for `ubuntu` and with `root` user
|
||||
@@ -151,8 +153,8 @@ Wants = network.target
|
||||
|
||||
[Service]
|
||||
Type = simple
|
||||
# config of frps-panel.ini,you should change the file path
|
||||
Environment=FRPS_PANEL_OPTS="-c /root/frps-panel/frps-panel.ini"
|
||||
# config of frps-panel.toml,you should change the file path
|
||||
Environment=FRPS_PANEL_OPTS="-c /root/frps-panel/frps-panel.toml"
|
||||
# command of run frps-panel,you should change the file path
|
||||
ExecStart = /root/frps-panel/frps-panel $FRPS_PANEL_OPTS
|
||||
|
||||
|
||||
94
README_zh.md
94
README_zh.md
@@ -7,6 +7,7 @@ frps-panel 是 [frp](https://github.com/fatedier/frp) 的一个服务端插件
|
||||
frps-panel 会以一个单独的进程运行,并接收 frps 发送过来的 HTTP 请求。
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
@@ -36,62 +37,59 @@ frps-panel 会以一个单独的进程运行,并接收 frps 发送过来的 HT
|
||||
|
||||
### 使用示例
|
||||
|
||||
1. 创建 `frps-panel.ini` 文件,内容为所有支持的用户名和 token。
|
||||
1. 创建 `frps-panel.toml` 文件,内容为基础配置。
|
||||
|
||||
```ini
|
||||
```toml
|
||||
# frps-panel.toml
|
||||
[common]
|
||||
;插件监听地址
|
||||
plugin_addr = 127.0.0.1
|
||||
;插件端口
|
||||
# frps panel config info
|
||||
plugin_addr = "127.0.0.1"
|
||||
plugin_port = 7200
|
||||
;插件管理页面账号,可选
|
||||
admin_user = admin
|
||||
;插件管理页面密码,与账号一起进行鉴权,可选
|
||||
admin_pwd = admin
|
||||
#admin_user = "admin"
|
||||
#admin_pwd = "admin"
|
||||
# specified login state keep time
|
||||
admin_keep_time = 0
|
||||
|
||||
; frps 面板页面是否启用https访问,如果为true,则只能通过https访问
|
||||
# enable tls
|
||||
tls_mode = false
|
||||
; tls_cert_file = cert.crt
|
||||
; tls_key_file = cert.key
|
||||
# tls_cert_file = "cert.crt"
|
||||
# tls_key_file = "cert.key"
|
||||
|
||||
; frp服务器的看板页面信息,必须配置,且与frp服务器一致,否则无法获取服务器信息
|
||||
dashboard_addr = 127.0.0.1
|
||||
# frp dashboard info
|
||||
dashboard_addr = "127.0.0.1"
|
||||
dashboard_port = 7500
|
||||
dashboard_user = admin
|
||||
dashboard_pwd = admin
|
||||
; 如果frps的dashboard启用了tls,则把这个选项置为true,否则无法获取服务器信息
|
||||
dashboard_tls = false
|
||||
|
||||
[users]
|
||||
;user1的meta_token为123
|
||||
user1 = 123
|
||||
;user2的meta_token为abc
|
||||
user2 = abc
|
||||
|
||||
[ports]
|
||||
;user1只能使用8080,9090到9010端口,其他端口则建立连接时返回失败(不影响客户端启动)
|
||||
user1=8080,9090-9010
|
||||
|
||||
[domains]
|
||||
;user1只能使用web01.yyy.zzz域名,配置了其他域名则建立连接时返回失败(不影响客户端启动)
|
||||
user1=web01.user1.com
|
||||
|
||||
[subdomains]
|
||||
;user1只能使用web01.xxx.yyy.zzz域名,配置了其他三级域名则建立连接时返回失败(不影响客户端启动)
|
||||
user1=web01
|
||||
|
||||
[disabled]
|
||||
;user2被禁用,frpc使用此账户与frps通信时,如果未启动则无法启动,如果已启动,则会一直打印错误日志
|
||||
user2 = disable
|
||||
dashboard_user = "admin"
|
||||
dashboard_pwd = "admin"
|
||||
```
|
||||
|
||||
每一个用户占一行,用户名和 token 之间以 `=` 号分隔。
|
||||
2. 创建`frps-tokens.toml`文件,其内容为系统中的用户,该文件位置和`frps-panel.toml`相同。如不创建此文件,在增加用户时会自动创建。
|
||||
|
||||
2. 运行 frps-panel,指定监听地址以及 token 存储文件路径。
|
||||
```toml
|
||||
#frps-tokens.toml
|
||||
[tokens]
|
||||
[tokens.user1]
|
||||
user = "user1"
|
||||
token = "token1"
|
||||
comment = "user1 with token1"
|
||||
ports = [8080, "10000-10200"]
|
||||
domains = ["web01.domain.com", "web02.domain.com"]
|
||||
subdomains = ["web01", "web02"]
|
||||
enable = true
|
||||
[tokens.user2]
|
||||
user = "user2"
|
||||
token = "token2"
|
||||
comment = "user2 with token2"
|
||||
ports = [9080]
|
||||
domains = ["web11.domain.com", "web12.domain.com"]
|
||||
subdomains = ["web11", "web12"]
|
||||
enable = false
|
||||
```
|
||||
|
||||
`./frps-panel -c ./frps-panel.ini`
|
||||
3. 运行 frps-panel,指定监听地址以及 token 存储文件路径。
|
||||
|
||||
3. 在 frps 的配置文件中注册插件,并启动。
|
||||
`./frps-panel -c ./frps-panel.toml`
|
||||
|
||||
4. 在 frps 的配置文件中注册插件,并启动。
|
||||
|
||||
```ini
|
||||
# frps.ini
|
||||
@@ -104,7 +102,7 @@ path = /handler
|
||||
ops = Login,NewWorkConn,NewUserConn,NewProxy,Ping
|
||||
```
|
||||
|
||||
4. 在 frpc 中指定用户名,在 meta 中指定 token,用户名以及 `meta_token` 的内容需要和之前创建的 token 文件匹配。
|
||||
5. 在 frpc 中指定用户名,在 meta 中指定 token,用户名以及 `meta_token` 的内容需要和之前创建的 token 文件匹配。
|
||||
|
||||
user1 的配置:
|
||||
|
||||
@@ -138,6 +136,8 @@ local_port = 22
|
||||
remote_port = 6000
|
||||
```
|
||||
|
||||
6.浏览器中输入地址: http://127.0.0.1:7200 或 https://127.0.0.1:7200 进入管理页面进行用户管理
|
||||
|
||||
## 以服务的形式运行
|
||||
|
||||
本实例是在 `ubuntu` 下, 以 `root` 用户执操作
|
||||
@@ -152,8 +152,8 @@ Wants = network.target
|
||||
|
||||
[Service]
|
||||
Type = simple
|
||||
# 启动frps-panel的配置文件路径,需修改为您的frps-panel.ini的路径
|
||||
Environment=FRPS_PANEL_OPTS="-c /root/frps-panel/frps-panel.ini"
|
||||
# 启动frps-panel的配置文件路径,需修改为您的frps-panel.toml的路径
|
||||
Environment=FRPS_PANEL_OPTS="-c /root/frps-panel/frps-panel.toml"
|
||||
# 启动frps-panel的命令,需修改为您的frps-panel的安装路径
|
||||
ExecStart = /root/frps-panel/frps-panel $FRPS_PANEL_OPTS
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"Other error": "Other error",
|
||||
"Param error": "Param error",
|
||||
"User exist": "User exist",
|
||||
"User not exist": "User not exist",
|
||||
"User format error": "User cannot be empty or include space char. It only allowed alphanumeric and underline.",
|
||||
"Token format error": "Token cannot be empty or include space char. It allow include those special char: _!@#$%^&*()",
|
||||
"Please check at least one user": "Please Check at least one user",
|
||||
@@ -90,5 +91,13 @@
|
||||
"Client Counts": "Client Counts",
|
||||
"Proxy Counts": "Proxy Counts",
|
||||
"Not Set": "Not Set",
|
||||
"Proxy": "Proxies"
|
||||
"Proxy": "Proxies",
|
||||
"Username": "Username",
|
||||
"Password": "Password",
|
||||
"Login": "Login",
|
||||
"Please input username": "Please input username",
|
||||
"Please input password": "Please input password",
|
||||
"Login success": "Login success",
|
||||
"Username or password incorrect": "Username or password incorrect",
|
||||
"Token invalid": "Token invalid"
|
||||
}
|
||||
@@ -29,6 +29,7 @@
|
||||
"Other error": "其他异常",
|
||||
"Param error": "参数异常",
|
||||
"User exist": "用户已经存在",
|
||||
"User not exist": "用户不存在",
|
||||
"User format error": "用户不能为空或包含空格。只允许英文数字、字母、下划线",
|
||||
"Token format error": "Token不能为空或包含空格。允许的特殊符号:_!@#$%^&*()",
|
||||
"Please check at least one user": "请选中需要操作的用户",
|
||||
@@ -90,5 +91,13 @@
|
||||
"Client Counts": "客户端总数",
|
||||
"Proxy Counts": "代理总数",
|
||||
"Not Set": "未配置",
|
||||
"Proxy": "代理数量"
|
||||
"Proxy": "代理数量",
|
||||
"Username": "用户名",
|
||||
"Password": "密码",
|
||||
"Login": "登录",
|
||||
"Please input username": "请填写用户名",
|
||||
"Please input password": "请填写密码",
|
||||
"Login success": "登录成功",
|
||||
"Username or password incorrect": "用户名或密码错误",
|
||||
"Token invalid": "登录信息无效"
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(199, 199, 199, 0.8);
|
||||
}
|
||||
|
||||
.layui-bg-blue {
|
||||
background-color: #58b7ff !important;
|
||||
}
|
||||
@@ -29,6 +33,10 @@
|
||||
border-color: #ff5722 !important;
|
||||
}
|
||||
|
||||
.layui-laypage a:hover {
|
||||
color: #409eff;
|
||||
}
|
||||
|
||||
.layui-laypage .layui-laypage-curr .layui-laypage-em {
|
||||
background-color: #409eff;
|
||||
}
|
||||
@@ -46,6 +54,14 @@
|
||||
border-color: #79bbff;
|
||||
}
|
||||
|
||||
.layui-form-checkbox[lay-skin=primary] > .layui-icon-indeterminate:before {
|
||||
background-color: #79bbff;
|
||||
}
|
||||
|
||||
.layui-form-checkbox[lay-skin=primary] > .layui-icon-indeterminate {
|
||||
border-color: #79bbff;
|
||||
}
|
||||
|
||||
.layui-form-checked[lay-skin=primary] > i {
|
||||
background-color: #409eff;
|
||||
border-color: #409eff !important;
|
||||
@@ -63,6 +79,11 @@
|
||||
border-color: #79bbff;
|
||||
}
|
||||
|
||||
.layui-table-checked.layui-table-click,
|
||||
.layui-table-checked.layui-table-hover {
|
||||
background-color: #d9ecff;
|
||||
}
|
||||
|
||||
.layui-nav-tree .layui-nav-child dd.layui-this,
|
||||
.layui-nav-tree .layui-nav-child dd.layui-this a,
|
||||
.layui-nav-tree .layui-this,
|
||||
@@ -113,7 +134,21 @@ section.proxy-list .proxy-info .layui-row .layui-row > div:first-child {
|
||||
color: #99a9bf;
|
||||
}
|
||||
|
||||
.login-title,
|
||||
.login-title a {
|
||||
color: #333 !important;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(107, 107, 107, 0.8);
|
||||
}
|
||||
|
||||
.login-title,
|
||||
.login-title a {
|
||||
color: #99a9bf !important;
|
||||
}
|
||||
|
||||
.layui-bg-blue {
|
||||
background-color: #395c74 !important;
|
||||
}
|
||||
@@ -141,6 +176,10 @@ section.proxy-list .proxy-info .layui-row .layui-row > div:first-child {
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.layui-laypage a:hover {
|
||||
color: #4f80a1;
|
||||
}
|
||||
|
||||
.layui-laypage .layui-laypage-curr .layui-laypage-em {
|
||||
background-color: #4f80a1;
|
||||
}
|
||||
@@ -154,10 +193,23 @@ section.proxy-list .proxy-info .layui-row .layui-row > div:first-child {
|
||||
border-color: #5f5f60;
|
||||
}
|
||||
|
||||
.layui-form-danger + .layui-form-select .layui-input,
|
||||
.layui-form-danger:focus {
|
||||
border-color: #ff5722 !important;
|
||||
}
|
||||
|
||||
.layui-form-checkbox[lay-skin=primary]:hover > i {
|
||||
border-color: #5f5f60;
|
||||
}
|
||||
|
||||
.layui-form-checkbox[lay-skin=primary] > .layui-icon-indeterminate:before {
|
||||
background-color: #5f5f60;
|
||||
}
|
||||
|
||||
.layui-form-checkbox[lay-skin=primary] > .layui-icon-indeterminate {
|
||||
border-color: #5f5f60;
|
||||
}
|
||||
|
||||
.layui-form-checked[lay-skin=primary] > i {
|
||||
background-color: #484849;
|
||||
border-color: #484849 !important;
|
||||
@@ -175,6 +227,11 @@ section.proxy-list .proxy-info .layui-row .layui-row > div:first-child {
|
||||
border-color: #5f5f60;
|
||||
}
|
||||
|
||||
.layui-table-checked.layui-table-click,
|
||||
.layui-table-checked.layui-table-hover {
|
||||
background-color: #5f5f60;
|
||||
}
|
||||
|
||||
.layui-nav-tree .layui-nav-child dd.layui-this,
|
||||
.layui-nav-tree .layui-nav-child dd.layui-this a,
|
||||
.layui-nav-tree .layui-this,
|
||||
@@ -1,3 +1,13 @@
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
border-radius: 4px;
|
||||
transition: 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
html, body {
|
||||
padding: 0;
|
||||
word-break: break-all;
|
||||
@@ -14,6 +24,10 @@ section {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.layui-layout-admin .layui-body {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.layui-header {
|
||||
line-height: 60px;
|
||||
font-size: 16px;
|
||||
@@ -43,6 +57,19 @@ section {
|
||||
height: 100%;
|
||||
padding: 0 15px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.layui-title #title {
|
||||
flex: 1;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.layui-title #logout{
|
||||
display: inline-block;
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.layui-nav.layui-nav-tree {
|
||||
|
||||
30
assets/static/css/login.css
Normal file
30
assets/static/css/login.css
Normal file
@@ -0,0 +1,30 @@
|
||||
html, body {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
text-align: center;
|
||||
margin-bottom: 50px;
|
||||
}
|
||||
|
||||
.login-title .title-text {
|
||||
font-size: 24px;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.login-title .title-version {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.login-container {
|
||||
width: 320px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
@@ -106,6 +106,10 @@ var loadProxyInfo = (function ($) {
|
||||
cols: [cols],
|
||||
page: navigator.language.indexOf("zh") !== -1,
|
||||
data: data,
|
||||
initSort: {
|
||||
field: 'name',
|
||||
type: 'asc'
|
||||
},
|
||||
done: function (res, curr, count, origin) {
|
||||
//向每一行tr后面追加显示子table的tr
|
||||
var $tr = $('.layui-table-view[lay-id=' + this.id + '] tbody tr');
|
||||
@@ -116,7 +120,6 @@ var loadProxyInfo = (function ($) {
|
||||
var useCompression = datum.conf.use_compression;
|
||||
datum.conf.use_encryption = i18n[useEncryption];
|
||||
datum.conf.use_compression = i18n[useCompression];
|
||||
console.log(datum)
|
||||
var html = layui.laytpl(expandTrTemplateHtml).render({
|
||||
index: i,
|
||||
colspan: cols.length - 1,
|
||||
|
||||
@@ -97,7 +97,7 @@ var loadUserList = (function ($) {
|
||||
}
|
||||
return {
|
||||
valid: valid,
|
||||
trim: username
|
||||
trim: username.trim()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ var loadUserList = (function ($) {
|
||||
}
|
||||
return {
|
||||
valid: valid,
|
||||
trim: comment.replace(/[\n\t\r]/g, '')
|
||||
trim: comment.trim().replace(/[\n\t\r]/g, '')
|
||||
};
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ var loadUserList = (function ($) {
|
||||
if (domains.trim() !== '') {
|
||||
try {
|
||||
domains.split(',').forEach(function (domain) {
|
||||
if (!/^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62}){1,3}$/.test(domain.trim())) {
|
||||
if (!/^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\.)+[a-zA-Z]{2,}$/.test(domain.trim())) {
|
||||
valid = false;
|
||||
throw 'break';
|
||||
}
|
||||
@@ -209,7 +209,7 @@ var loadUserList = (function ($) {
|
||||
if (subdomains.trim() !== '') {
|
||||
try {
|
||||
subdomains.split(',').forEach(function (subdomain) {
|
||||
if (!/^[a-zA-z0-9][a-zA-Z0-9-]{0,19}$/.test(subdomain.trim())) {
|
||||
if (!/^[a-zA-z0-9][a-zA-z0-9-]{0,19}$/.test(subdomain.trim())) {
|
||||
valid = false;
|
||||
throw 'break';
|
||||
}
|
||||
@@ -251,7 +251,9 @@ var loadUserList = (function ($) {
|
||||
where: {},
|
||||
dataType: 'json',
|
||||
editTrigger: 'dblclick',
|
||||
page: navigator.language.indexOf("zh") !== -1,
|
||||
page: {
|
||||
layout: navigator.language.indexOf("zh") === -1 ? ['first', 'prev', 'next', 'last'] : ['prev', 'page', 'next', 'skip', 'count', 'limit']
|
||||
},
|
||||
toolbar: '#userListToolbarTemplate',
|
||||
defaultToolbar: false,
|
||||
cols: [[
|
||||
@@ -263,27 +265,35 @@ var loadUserList = (function ($) {
|
||||
{field: 'domains', title: i18n['AllowedDomains'], sort: true, edit: 'textarea'},
|
||||
{field: 'subdomains', title: i18n['AllowedSubdomains'], sort: true, edit: 'textarea'},
|
||||
{
|
||||
field: 'status',
|
||||
field: 'enable',
|
||||
title: i18n['Status'],
|
||||
width: 100,
|
||||
templet: '<span>{{d.status? "' + i18n['Enable'] + '":"' + i18n['Disable'] + '"}}</span>',
|
||||
templet: '<span>{{d.enable? "' + i18n['Enable'] + '":"' + i18n['Disable'] + '"}}</span>',
|
||||
sort: true
|
||||
},
|
||||
{title: i18n['Operation'], width: 150, toolbar: '#userListOperationTemplate'}
|
||||
]]
|
||||
]],
|
||||
parseData: function (res) {
|
||||
res.data.forEach(function (data) {
|
||||
data.ports = data.ports.join(',');
|
||||
data.domains = data.domains.join(',');
|
||||
data.subdomains = data.subdomains.join(',');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
bindFormEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* bind event of layui.form
|
||||
* bind event of {{@link layui.form}}
|
||||
*/
|
||||
function bindFormEvent() {
|
||||
layui.table.on('edit(tokenTable)', function (obj) {
|
||||
var field = obj.field;
|
||||
var value = obj.value;
|
||||
var oldValue = obj.oldValue;
|
||||
|
||||
var before = $.extend(true, {}, obj.data);
|
||||
var after = $.extend(true, {}, obj.data);
|
||||
var verifyMsg = false;
|
||||
@@ -344,30 +354,60 @@ var loadUserList = (function ($) {
|
||||
after.subdomains = value;
|
||||
}
|
||||
|
||||
before.ports = before.ports.split(',')
|
||||
before.domains = before.domains.split(',')
|
||||
before.subdomains = before.subdomains.split(',')
|
||||
after.ports = after.ports.split(',')
|
||||
after.domains = after.domains.split(',')
|
||||
after.subdomains = after.subdomains.split(',')
|
||||
|
||||
update(before, after);
|
||||
});
|
||||
|
||||
layui.table.on('toolbar(tokenTable)', function (obj) {
|
||||
var id = obj.config.id;
|
||||
var checkStatus = layui.table.checkStatus(id);
|
||||
var data = checkStatus.data;
|
||||
|
||||
data.forEach(function (temp) {
|
||||
temp.ports = temp.ports.split(',')
|
||||
temp.ports.forEach(function (port, index) {
|
||||
if (/^\d+$/.test(String(port))) {
|
||||
temp.ports[index] = parseInt(String(port));
|
||||
}
|
||||
});
|
||||
|
||||
temp.domains = temp.domains.split(',')
|
||||
temp.subdomains = temp.subdomains.split(',')
|
||||
});
|
||||
|
||||
switch (obj.event) {
|
||||
case 'add':
|
||||
addPopup();
|
||||
break
|
||||
case 'remove':
|
||||
batchRemovePopup(checkStatus.data);
|
||||
batchRemovePopup(data);
|
||||
break
|
||||
case 'disable':
|
||||
batchDisablePopup(checkStatus.data);
|
||||
batchDisablePopup(data);
|
||||
break
|
||||
case 'enable':
|
||||
batchEnablePopup(checkStatus.data);
|
||||
batchEnablePopup(data);
|
||||
break
|
||||
}
|
||||
});
|
||||
|
||||
layui.table.on('tool(tokenTable)', function (obj) {
|
||||
var data = obj.data;
|
||||
|
||||
data.ports = data.ports.split(',')
|
||||
data.ports.forEach(function (port, index) {
|
||||
if (/^\d+$/.test(String(port))) {
|
||||
data.ports[index] = parseInt(String(port));
|
||||
}
|
||||
});
|
||||
data.domains = data.domains.split(',')
|
||||
data.subdomains = data.subdomains.split(',')
|
||||
switch (obj.event) {
|
||||
case 'remove':
|
||||
removePopup(data);
|
||||
@@ -406,7 +446,22 @@ var loadUserList = (function ($) {
|
||||
btn: [i18n['Confirm'], i18n['Cancel']],
|
||||
btn1: function (index) {
|
||||
if (layui.form.validate('#addUserForm')) {
|
||||
add(layui.form.val('addUserForm'), index);
|
||||
var formData = layui.form.val('addUserForm');
|
||||
if (formData.ports != null) {
|
||||
formData.ports = formData.ports.split(',')
|
||||
formData.ports.forEach(function (port, index) {
|
||||
if (/^\d+$/.test(String(port))) {
|
||||
formData.ports[index] = parseInt(String(port));
|
||||
}
|
||||
})
|
||||
}
|
||||
if (formData.domains != null) {
|
||||
formData.domains = formData.domains.split(',')
|
||||
}
|
||||
if (formData.subdomains != null) {
|
||||
formData.subdomains = formData.subdomains.split(',')
|
||||
}
|
||||
add(formData, index);
|
||||
}
|
||||
},
|
||||
btn2: function (index) {
|
||||
@@ -417,7 +472,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* add user action
|
||||
* @param data {{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}} user data
|
||||
* @param data {{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}} user data
|
||||
* @param index popup index
|
||||
*/
|
||||
function add(data, index) {
|
||||
@@ -446,10 +501,20 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* update user action
|
||||
* @param before {{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}} data before update
|
||||
* @param after {{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}} data after update
|
||||
* @param before {{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}} data before update
|
||||
* @param after {{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}} data after update
|
||||
*/
|
||||
function update(before, after) {
|
||||
before.ports.forEach(function (port, index) {
|
||||
if (/^\d+$/.test(String(port))) {
|
||||
before.ports[index] = parseInt(String(port));
|
||||
}
|
||||
});
|
||||
after.ports.forEach(function (port, index) {
|
||||
if (/^\d+$/.test(String(port)) && typeof port === "string") {
|
||||
after.ports[index] = parseInt(String(port));
|
||||
}
|
||||
});
|
||||
var loading = layui.layer.load();
|
||||
$.ajax({
|
||||
url: '/update',
|
||||
@@ -474,7 +539,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* batch remove user popup
|
||||
* @param data {[{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}]} user data list
|
||||
* @param data {[{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}]} user data list
|
||||
*/
|
||||
function batchRemovePopup(data) {
|
||||
if (data.length === 0) {
|
||||
@@ -491,7 +556,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* batch disable user popup
|
||||
* @param data {[{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}]} user data list
|
||||
* @param data {[{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}]} user data list
|
||||
*/
|
||||
function batchDisablePopup(data) {
|
||||
if (data.length === 0) {
|
||||
@@ -508,7 +573,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* batch enable user popup
|
||||
* @param data {[{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}]} user data list
|
||||
* @param data {[{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}]} user data list
|
||||
*/
|
||||
function batchEnablePopup(data) {
|
||||
if (data.length === 0) {
|
||||
@@ -525,7 +590,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* remove one user popup
|
||||
* @param data {{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}} user data
|
||||
* @param data {{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}} user data
|
||||
*/
|
||||
function removePopup(data) {
|
||||
layui.layer.confirm(i18n['ConfirmRemoveUser'], {
|
||||
@@ -538,7 +603,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* disable one user popup
|
||||
* @param data {{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}} user data
|
||||
* @param data {{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}} user data
|
||||
*/
|
||||
function disablePopup(data) {
|
||||
layui.layer.confirm(i18n['ConfirmDisableUser'], {
|
||||
@@ -551,7 +616,7 @@ var loadUserList = (function ($) {
|
||||
|
||||
/**
|
||||
* enable one user popup
|
||||
* @param data {{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}} user data
|
||||
* @param data {{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}} user data
|
||||
*/
|
||||
function enablePopup(data) {
|
||||
layui.layer.confirm(i18n['ConfirmEnableUser'], {
|
||||
@@ -565,7 +630,7 @@ var loadUserList = (function ($) {
|
||||
/**
|
||||
* operate actions
|
||||
* @param type {apiType} action type
|
||||
* @param data {[{user:string, token:string, comment:string, status:boolean, ports:string, domains:string, subdomains:string}]} user data list
|
||||
* @param data {[{user:string, token:string, comment:string, enable:boolean, ports:[string|number], domains:[string], subdomains:[string]}]} user data list
|
||||
* @param index popup index
|
||||
*/
|
||||
function operate(type, data, index) {
|
||||
@@ -623,17 +688,27 @@ var loadUserList = (function ($) {
|
||||
* @param result
|
||||
*/
|
||||
function errorMsg(result) {
|
||||
var reason = i18n['Other Error'];
|
||||
var reason = i18n['OtherError'];
|
||||
if (result.code === 1)
|
||||
reason = i18n['ParamError'];
|
||||
else if (result.code === 2)
|
||||
reason = i18n['UserExist'];
|
||||
else if (result.code === 3)
|
||||
reason = i18n['ParamError'];
|
||||
reason = i18n['UserNotExist'];
|
||||
else if (result.code === 4)
|
||||
reason = i18n['UserFormatError'];
|
||||
reason = i18n['ParamError'];
|
||||
else if (result.code === 5)
|
||||
reason = i18n['UserFormatError'];
|
||||
else if (result.code === 6)
|
||||
reason = i18n['TokenFormatError'];
|
||||
else if (result.code === 7)
|
||||
reason = i18n['CommentInvalid'];
|
||||
else if (result.code === 8)
|
||||
reason = i18n['PortsInvalid'];
|
||||
else if (result.code === 9)
|
||||
reason = i18n['DomainsInvalid'];
|
||||
else if (result.code === 10)
|
||||
reason = i18n['SubdomainsInvalid'];
|
||||
layui.layer.msg(i18n['OperateFailed'] + ',' + reason)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,50 @@
|
||||
var http_port, https_port;
|
||||
(function ($) {
|
||||
$(function () {
|
||||
var langLoading = layui.layer.load()
|
||||
$.getJSON('/lang.json').done(function (lang) {
|
||||
layui.element.on('nav(leftNav)', function (elem) {
|
||||
var id = elem.attr('id');
|
||||
var title = elem.text();
|
||||
if (id === 'serverInfo') {
|
||||
loadServerInfo(lang, title.trim());
|
||||
} else if (id === 'userList') {
|
||||
loadUserList(lang, title.trim());
|
||||
} else if (elem.closest('.layui-nav-item').attr('id') === 'proxyList') {
|
||||
if (id != null && id.trim() !== '') {
|
||||
var suffix = elem.closest('.layui-nav-item').children('a').text().trim();
|
||||
loadProxyInfo(lang, title + " " + suffix, id);
|
||||
}
|
||||
}
|
||||
});
|
||||
function init() {
|
||||
var langLoading = layui.layer.load()
|
||||
$.getJSON('/lang.json').done(function (lang) {
|
||||
$.ajaxSetup({
|
||||
error: function (xhr,) {
|
||||
if (xhr.status === 401) {
|
||||
layui.layer.msg(lang['TokenInvalid'], function () {
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
$('#leftNav .layui-this > a').click();
|
||||
}).always(function () {
|
||||
layui.layer.close(langLoading);
|
||||
layui.element.on('nav(leftNav)', function (elem) {
|
||||
var id = elem.attr('id');
|
||||
var title = elem.text();
|
||||
if (id === 'serverInfo') {
|
||||
loadServerInfo(lang, title.trim());
|
||||
} else if (id === 'userList') {
|
||||
loadUserList(lang, title.trim());
|
||||
} else if (elem.closest('.layui-nav-item').attr('id') === 'proxyList') {
|
||||
if (id != null && id.trim() !== '') {
|
||||
var suffix = elem.closest('.layui-nav-item').children('a').text().trim();
|
||||
loadProxyInfo(lang, title + " " + suffix, id);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$('#leftNav .layui-this > a').click();
|
||||
}).always(function () {
|
||||
layui.layer.close(langLoading);
|
||||
});
|
||||
}
|
||||
|
||||
function logout() {
|
||||
$.get("/logout", function (result) {
|
||||
window.location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('click.logout', '#logout', function () {
|
||||
logout();
|
||||
});
|
||||
|
||||
init();
|
||||
});
|
||||
})(layui.$);
|
||||
33
assets/static/js/login.js
Normal file
33
assets/static/js/login.js
Normal file
@@ -0,0 +1,33 @@
|
||||
(function ($) {
|
||||
$(function () {
|
||||
function login() {
|
||||
if (!layui.form.validate('#loginForm')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: "/login",
|
||||
type: 'post',
|
||||
data: {
|
||||
username: $('#username').val(),
|
||||
password: $('#password').val()
|
||||
},
|
||||
success: function (result) {
|
||||
if (result.success) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
layui.layer.msg(result.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$(document).on('click.login', '#login', function () {
|
||||
login();
|
||||
}).on('keydown', function (e) {
|
||||
if (e.keyCode === 13) {
|
||||
login();
|
||||
}
|
||||
});
|
||||
})
|
||||
})(layui.$)
|
||||
@@ -1,18 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>${ .FrpsPanel }</title>
|
||||
<link rel="stylesheet" href="./static/lib/layui/css/layui.css">
|
||||
<link rel="stylesheet" href="./static/css/layui-theme-dark.css">
|
||||
<link rel="stylesheet" href="./static/css/index.css">
|
||||
<link rel="stylesheet" href="./static/css/index-color.css">
|
||||
<script src="./static/lib/layui/layui.js"></script>
|
||||
<script src="./static/lib/echarts.min.js"></script>
|
||||
<script src="./static/lib/filesize.min.js"></script>
|
||||
<script src="./static/js/index-server-info.js"></script>
|
||||
<script src="./static/js/index-user-list.js"></script>
|
||||
<script src="./static/js/index-proxy-list.js"></script>
|
||||
<script src="./static/js/index.js"></script>
|
||||
<link rel="stylesheet" href="./static/lib/layui/css/layui.css?v=${ .version }">
|
||||
<link rel="stylesheet" href="./static/css/layui-theme-dark.css?v=${ .version }">
|
||||
<link rel="stylesheet" href="./static/css/index.css?v=${ .version }">
|
||||
<link rel="stylesheet" href="./static/css/color.css?v=${ .version }">
|
||||
<script src="./static/lib/layui/layui.js?v=${ .version }"></script>
|
||||
<script src="./static/lib/echarts.min.js?v=${ .version }"></script>
|
||||
<script src="./static/lib/filesize.min.js?v=${ .version }"></script>
|
||||
<script src="./static/js/index-server-info.js?v=${ .version }"></script>
|
||||
<script src="./static/js/index-user-list.js?v=${ .version }"></script>
|
||||
<script src="./static/js/index-proxy-list.js?v=${ .version }"></script>
|
||||
<script src="./static/js/index.js?v=${ .version }"></script>
|
||||
<style>
|
||||
section.user-list .layui-table-cell:empty::after {
|
||||
content: '${ .NotLimit }';
|
||||
@@ -22,17 +22,17 @@
|
||||
content: '${ .None }';
|
||||
}
|
||||
</style>
|
||||
<style>
|
||||
.layui-layout-admin .layui-body {
|
||||
padding: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="layui-layout layui-layout-admin">
|
||||
<div class="layui-header layui-bg-blue">
|
||||
<div class="layui-logo layui-hide-xs layui-bg-black">${ .FrpsPanel }</div>
|
||||
<div class="layui-title" id="title"></div>
|
||||
<div class="layui-logo layui-bg-black">${ .FrpsPanel }</div>
|
||||
<div class="layui-title">
|
||||
<span id="title"></span>
|
||||
${ if .showExit }
|
||||
<span class="layui-icon layui-icon-logout" id="logout"></span>
|
||||
${ end }
|
||||
</div>
|
||||
</div>
|
||||
<div class="layui-side layui-bg-black">
|
||||
<div class="layui-side-scroll">
|
||||
@@ -214,7 +214,7 @@
|
||||
<script type="text/html" id="userListOperationTemplate">
|
||||
<div class="layui-clear-space">
|
||||
<a class="layui-btn layui-btn-xs" lay-event="remove">${ .Remove }</a>
|
||||
{{# if (d.status) { }}
|
||||
{{# if (d.enable) { }}
|
||||
<a class="layui-btn layui-btn-xs" lay-event="disable">${ .Disable }</a>
|
||||
{{# } else { }}
|
||||
<a class="layui-btn layui-btn-xs" lay-event="enable">${ .Enable }</a>
|
||||
|
||||
43
assets/templates/login.html
Normal file
43
assets/templates/login.html
Normal file
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="">
|
||||
<head>
|
||||
<title>Login</title>
|
||||
<link rel="stylesheet" href="./static/lib/layui/css/layui.css?v=${ .version }">
|
||||
<link rel="stylesheet" href="./static/css/layui-theme-dark.css?v=${ .version }">
|
||||
<link rel="stylesheet" href="./static/css/color.css?v=${ .version }">
|
||||
<link rel="stylesheet" href="./static/css/login.css?v=${ .version }">
|
||||
<script src="./static/lib/layui/layui.js?v=${ .version }"></script>
|
||||
<script src="./static/js/login.js?v=${ .version }"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="login-title">
|
||||
<a href="https://github.com/yhl452493373/frps-panel" target="_blank">
|
||||
<span class="title-text">${ .FrpsPanel }</span>
|
||||
<span class="title-version">${ .version }</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="layui-form login-container" id="loginForm">
|
||||
<div class="layui-form-item">
|
||||
<div class="layui-input-wrap">
|
||||
<div class="layui-input-prefix">
|
||||
<i class="layui-icon layui-icon-username"></i>
|
||||
</div>
|
||||
<input type="text" id="username" value="" lay-verify="required" placeholder="${ .Username }"
|
||||
lay-reqtext="${ .PleaseInputUsername }" autocomplete="off" class="layui-input" lay-affix="clear">
|
||||
</div>
|
||||
</div>
|
||||
<div class="layui-form-item">
|
||||
<div class="layui-input-wrap">
|
||||
<div class="layui-input-prefix">
|
||||
<i class="layui-icon layui-icon-password"></i>
|
||||
</div>
|
||||
<input type="password" id="password" value="" lay-verify="required" placeholder="${ .Password }"
|
||||
lay-reqtext="${ .PleaseInputPassword }" autocomplete="off" class="layui-input" lay-affix="eye">
|
||||
</div>
|
||||
</div>
|
||||
<div class="layui-form-item">
|
||||
<button class="layui-btn layui-btn-fluid" id="login">${ .Login }</button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -4,16 +4,15 @@ import (
|
||||
"errors"
|
||||
"frps-panel/pkg/server"
|
||||
"frps-panel/pkg/server/controller"
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/spf13/cobra"
|
||||
"gopkg.in/ini.v1"
|
||||
"io/fs"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const version = "1.5.0"
|
||||
const version = "1.7.0"
|
||||
|
||||
var (
|
||||
showVersion bool
|
||||
@@ -22,7 +21,7 @@ var (
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frps-panel")
|
||||
rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "./frps-panel.ini", "config file of frps-panel")
|
||||
rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "./frps-panel.toml", "config file of frps-panel")
|
||||
}
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
@@ -40,7 +39,10 @@ var rootCmd = &cobra.Command{
|
||||
}
|
||||
rootDir := filepath.Dir(executable)
|
||||
|
||||
config, tls, err := ParseConfigFile(configFile)
|
||||
configDir := filepath.Dir(configFile)
|
||||
tokensFile := filepath.Join(configDir, "frps-tokens.toml")
|
||||
|
||||
config, tls, err := parseConfigFile(configFile, tokensFile)
|
||||
if err != nil {
|
||||
log.Printf("fail to start frps-panel : %v", err)
|
||||
return err
|
||||
@@ -68,183 +70,47 @@ func Execute() {
|
||||
}
|
||||
}
|
||||
|
||||
func ParseConfigFile(file string) (controller.HandleController, server.TLS, error) {
|
||||
common := controller.CommonInfo{}
|
||||
users := make(map[string]controller.TokenInfo)
|
||||
ports := make(map[string][]string)
|
||||
domains := make(map[string][]string)
|
||||
subdomains := make(map[string][]string)
|
||||
tls := server.TLS{
|
||||
Enable: false,
|
||||
Protocol: "HTTP",
|
||||
func parseConfigFile(configFile, tokensFile string) (controller.HandleController, server.TLS, error) {
|
||||
var common controller.Common
|
||||
var tokens controller.Tokens
|
||||
_, err := toml.DecodeFile(configFile, &common)
|
||||
if err != nil {
|
||||
log.Fatalf("decode config file %v error: %v", configFile, err)
|
||||
}
|
||||
|
||||
iniFile, err := ini.LoadSources(ini.LoadOptions{
|
||||
Insensitive: false,
|
||||
InsensitiveSections: false,
|
||||
InsensitiveKeys: false,
|
||||
IgnoreInlineComment: true,
|
||||
AllowBooleanKeys: true,
|
||||
}, file)
|
||||
_, err = toml.DecodeFile(tokensFile, &tokens)
|
||||
if err != nil {
|
||||
var pathError *fs.PathError
|
||||
if errors.As(err, &pathError) {
|
||||
log.Printf("token file %s not found", file)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
tokens = controller.Tokens{Tokens: make(map[string]controller.TokenInfo)}
|
||||
} else {
|
||||
log.Printf("fail to parse token file %s : %v", file, err)
|
||||
log.Fatalf("decode token file %v error: %v", tokensFile, err)
|
||||
}
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
|
||||
commonSection, err := iniFile.GetSection("common")
|
||||
if err != nil {
|
||||
log.Printf("fail to get [common] section from file %s : %v", file, err)
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
common.PluginAddr = commonSection.Key("plugin_addr").MustString("0.0.0.0")
|
||||
common.PluginPort = commonSection.Key("plugin_port").MustInt(7200)
|
||||
common.User = commonSection.Key("admin_user").Value()
|
||||
common.Pwd = commonSection.Key("admin_pwd").Value()
|
||||
common.DashboardTLS = commonSection.Key("dashboard_tls").MustBool(false)
|
||||
common.DashboardAddr = commonSection.Key("dashboard_addr").MustString("127.0.0.1")
|
||||
common.DashboardPort = commonSection.Key("dashboard_port").MustInt(7500)
|
||||
common.DashboardUser = commonSection.Key("dashboard_user").Value()
|
||||
common.DashboardPwd = commonSection.Key("dashboard_pwd").Value()
|
||||
common.Common.DashboardTls = strings.HasPrefix("https://", strings.ToLower(common.Common.DashboardAddr))
|
||||
|
||||
tls := server.TLS{
|
||||
Enable: common.Common.TlsMode,
|
||||
Protocol: "HTTP",
|
||||
Cert: common.Common.TlsCertFile,
|
||||
Key: common.Common.TlsKeyFile,
|
||||
}
|
||||
|
||||
tls.Enable = commonSection.Key("tls_mode").MustBool(false)
|
||||
tls.Cert = commonSection.Key("tls_cert_file").MustString("")
|
||||
tls.Key = commonSection.Key("tls_key_file").MustString("")
|
||||
if tls.Enable {
|
||||
tls.Protocol = "HTTPS"
|
||||
}
|
||||
if tls.Enable && (strings.TrimSpace(tls.Cert) == "" || strings.TrimSpace(tls.Key) == "") {
|
||||
tls.Enable = false
|
||||
tls.Protocol = "HTTP"
|
||||
log.Printf("fail to enable tls: tls cert or key not exist, use http as default.")
|
||||
}
|
||||
|
||||
portsSection, err := iniFile.GetSection("ports")
|
||||
if err != nil {
|
||||
log.Printf("fail to get [ports] section from file %s : %v", file, err)
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
for _, key := range portsSection.Keys() {
|
||||
user := key.Name()
|
||||
value := key.Value()
|
||||
port := strings.Split(controller.TrimAllSpaceReg.ReplaceAllString(value, ""), ",")
|
||||
ports[user] = port
|
||||
}
|
||||
|
||||
domainsSection, err := iniFile.GetSection("domains")
|
||||
if err != nil {
|
||||
log.Printf("fail to get [domains] section from file %s : %v", file, err)
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
for _, key := range domainsSection.Keys() {
|
||||
user := key.Name()
|
||||
value := key.Value()
|
||||
domain := strings.Split(controller.TrimAllSpaceReg.ReplaceAllString(value, ""), ",")
|
||||
domains[user] = domain
|
||||
}
|
||||
|
||||
subdomainsSection, err := iniFile.GetSection("subdomains")
|
||||
if err != nil {
|
||||
log.Printf("fail to get [subdomains] section from file %s : %v", file, err)
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
for _, key := range subdomainsSection.Keys() {
|
||||
user := key.Name()
|
||||
value := key.Value()
|
||||
subdomain := strings.Split(controller.TrimAllSpaceReg.ReplaceAllString(value, ""), ",")
|
||||
subdomains[user] = subdomain
|
||||
}
|
||||
|
||||
usersSection, err := iniFile.GetSection("users")
|
||||
if err != nil {
|
||||
log.Printf("fail to get [users] section from file %s : %v", file, err)
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
|
||||
disabledSection, err := iniFile.GetSection("disabled")
|
||||
if err != nil {
|
||||
log.Printf("fail to get [disabled] section from file %s : %v", file, err)
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: nil,
|
||||
Ports: nil,
|
||||
Domains: nil,
|
||||
Subdomains: nil,
|
||||
IniFile: iniFile,
|
||||
}, tls, err
|
||||
}
|
||||
|
||||
keys := usersSection.Keys()
|
||||
for _, key := range keys {
|
||||
comment, found := strings.CutPrefix(key.Comment, ";")
|
||||
if !found {
|
||||
comment, found = strings.CutPrefix(comment, "#")
|
||||
if strings.TrimSpace(tls.Cert) == "" || strings.TrimSpace(tls.Key) == "" {
|
||||
tls.Enable = false
|
||||
tls.Protocol = "HTTP"
|
||||
log.Printf("fail to enable tls: tls cert or key not exist, use http as default.")
|
||||
}
|
||||
token := controller.TokenInfo{
|
||||
User: key.Name(),
|
||||
Token: key.Value(),
|
||||
Comment: comment,
|
||||
Ports: strings.Join(ports[key.Name()], ","),
|
||||
Domains: strings.Join(domains[key.Name()], ","),
|
||||
Subdomains: strings.Join(subdomains[key.Name()], ","),
|
||||
Status: !(disabledSection.HasKey(key.Name()) && disabledSection.Key(key.Name()).Value() == "disable"),
|
||||
}
|
||||
users[token.User] = token
|
||||
}
|
||||
|
||||
return controller.HandleController{
|
||||
CommonInfo: common,
|
||||
Tokens: users,
|
||||
Ports: ports,
|
||||
Domains: domains,
|
||||
Subdomains: subdomains,
|
||||
ConfigFile: configFile,
|
||||
IniFile: iniFile,
|
||||
CommonInfo: common.Common,
|
||||
Tokens: tokens.Tokens,
|
||||
Version: version,
|
||||
ConfigFile: configFile,
|
||||
TokensFile: tokensFile,
|
||||
}, tls, nil
|
||||
}
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDwDCCAqigAwIBAgIIYb+7dG3vm+swDQYJKoZIhvcNAQELBQAwejELMAkGA1UE
|
||||
BhMCQ04xFzAVBgNVBAoTDktleU1hbmFnZXIub3JnMTEwLwYDVQQLEyhLZXlNYW5h
|
||||
Z2VyIFRlc3QgUm9vdCAtIEZvciBUZXN0IFVzZSBPbmx5MR8wHQYDVQQDExZLZXlN
|
||||
YW5hZ2VyIFRlc3QgUlNBIENBMB4XDTIzMDkxMTA5NTY0NloXDTI0MDkxMTA5NTY0
|
||||
NlowJjELMAkGA1UEBhMCQ04xFzAVBgNVBAMTDmxvY2FsaG9zdDo3MjAwMIIBIjAN
|
||||
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqp/BNnNx4OGqJHNLN0GX8MDUO4PI
|
||||
WJ9rq6by65i2RXd4t51yyOH68l/TNmfCXcUQ91SvBBD+P2dK2gkZOlprDOS3tO+G
|
||||
sCTAAEf/tv1+N2ZqDUPKwaIH60seDJd2a3A97KtfySFVrCUrlTeB/tPL5XMBFwTT
|
||||
xPvfV6RULAaK6lJGdrM9/k/vYfneE+ZY5Bo1b7kaqZLOz9LW3icarPGcFDIes/Lu
|
||||
d3sCbpjza0bAKFy594vIdwqjRY4OHdubwXV3wV/AxgA0tQNyYADFwa3YeSvBsfFq
|
||||
PortWOAYKrg86RJJ8ilQumNiEs6FSYnSatbjMkKh7q9EerJf/exlW1IzDQIDAQAB
|
||||
o4GdMIGaMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB
|
||||
BQUHAwIwHQYDVR0OBBYEFJFGsaMxKCw1E2r2NC+PxdiI4p/VMB8GA1UdIwQYMBaA
|
||||
FIBNaqqKRqtaWv5Us+XACf5jiY2rMCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo3MjAw
|
||||
gg4xMjcuMC4wLjE6NzIwMDANBgkqhkiG9w0BAQsFAAOCAQEAhuNAScvlzJKL4aAm
|
||||
bPl6Yru85GZZk+QmL8tICT9rxfq5L/5RhZXuTIqBDLB+ETHq5yQdiUJTphMpq2i3
|
||||
UZUzSMkUFokLROKWaENJz82RWYPUGNLqUO7vTIy2HGd4qOYjWDlHba7d9UIRTcKx
|
||||
1pd4rqXRTka1rprmoBcSNgcFDcKmctgliOPFqa9V89xrWSznahNqRqdkvbzuuHFz
|
||||
oZHKsTBzZ65Mk/E5+EdOYgEPg4kBfBMP7LXabUYCON1ArekRUHS1QJ0yCrzDpUxu
|
||||
0XnFTHaoBtP2o7tqmRQk78/8UkqOkz8241p2Tl8n3YZDiJbrv6okTPe+c/m9xD37
|
||||
2kwdDg==
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIID2jCCAsKgAwIBAgIIcAbJXpLHgDkwDQYJKoZIhvcNAQELBQAwezELMAkGA1UE
|
||||
BhMCQ04xFzAVBgNVBAoTDktleU1hbmFnZXIub3JnMTEwLwYDVQQLEyhLZXlNYW5h
|
||||
Z2VyIFRlc3QgUm9vdCAtIEZvciBUZXN0IFVzZSBPbmx5MSAwHgYDVQQDExdLZXlN
|
||||
YW5hZ2VyIFRlc3QgUm9vdCBDQTAeFw0yMzA5MTEwOTEzNTFaFw0zMzA5MTEwOTEz
|
||||
NTFaMHoxCzAJBgNVBAYTAkNOMRcwFQYDVQQKEw5LZXlNYW5hZ2VyLm9yZzExMC8G
|
||||
A1UECxMoS2V5TWFuYWdlciBUZXN0IFJvb3QgLSBGb3IgVGVzdCBVc2UgT25seTEf
|
||||
MB0GA1UEAxMWS2V5TWFuYWdlciBUZXN0IFJTQSBDQTCCASIwDQYJKoZIhvcNAQEB
|
||||
BQADggEPADCCAQoCggEBANfE1y7r94k5LeDncCnOfjItWXWWuNAzJFXsd0620cON
|
||||
5jXCYfVGdRqPkpHtLml1OiMtnSyxxqIASCsxn+puvXPy12FJkTq8D5GtuuLk/8oI
|
||||
iiGvFTbVR1C63ZwYQ/MOjMbmlICNVNFYDZfPbALLaZbvtd2q9xc/bq0zd9P6cfW4
|
||||
GKZyGNwmrNukUtXkIdPIaUiNRiseHwwyR//bJh9GFhCw5jpVK5bnDT1PZYFKww0J
|
||||
qv5kA9fCY/Xm635MfRsvNI+2RMOBhKgblWGmDCaJMOglgyao3AVK8ajrNrlAoTHC
|
||||
9Lcm4dQc2p0KUVfRitLio2ANKM3oh8q2qHPFrAnvjzcCAwEAAaNjMGEwDgYDVR0P
|
||||
AQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIBNaqqKRqtaWv5U
|
||||
s+XACf5jiY2rMB8GA1UdIwQYMBaAFEOl8mT1ZXKyUe00w/jyQQKMYUQAMA0GCSqG
|
||||
SIb3DQEBCwUAA4IBAQCouCabkdzZKiGMKlrCE0y/eDNqBUwdERWD+Xrxhm/K13bg
|
||||
gJJXZsWWr2/iumbWkc3N9W5J2gyFc+iO79VrVMzlq2Kfbhy5XY5gioC8n1BL4FPs
|
||||
lmOGtO/8NubZhjTVrE/wH2iDcC9vfE5EAM/axnQXA1DjuEhyRnZe40lTXnA37vc1
|
||||
f0hizePrPiMNpzJLZ9kj9pvOYRc7h+Oe04fz+iG5iSlJ/s4y81o0oOJkDLatfveC
|
||||
+L2ZqbiagZTsBYiL68Y612n7UDH2tUpyE6hCxYlNb+hCMFLakRHfp/IHcz6oHxvV
|
||||
kyJ5FwVvwn9fy4QOi/NsfASdb4AnyqRkJKNSlqWw
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,27 +0,0 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEAqp/BNnNx4OGqJHNLN0GX8MDUO4PIWJ9rq6by65i2RXd4t51y
|
||||
yOH68l/TNmfCXcUQ91SvBBD+P2dK2gkZOlprDOS3tO+GsCTAAEf/tv1+N2ZqDUPK
|
||||
waIH60seDJd2a3A97KtfySFVrCUrlTeB/tPL5XMBFwTTxPvfV6RULAaK6lJGdrM9
|
||||
/k/vYfneE+ZY5Bo1b7kaqZLOz9LW3icarPGcFDIes/Lud3sCbpjza0bAKFy594vI
|
||||
dwqjRY4OHdubwXV3wV/AxgA0tQNyYADFwa3YeSvBsfFqPortWOAYKrg86RJJ8ilQ
|
||||
umNiEs6FSYnSatbjMkKh7q9EerJf/exlW1IzDQIDAQABAoIBAFcIGBEDQAI6eYQQ
|
||||
PzyXO751TYxyAv6Zit1K0jw0cDzs3Omj6UnoYw3ArUbiFDWqcKYITyGe3WFP+dFP
|
||||
tMucFWDFRaOITkaI6Fr8XsZjdT8jAVN00faFBM8TSOeZVrEk1qFjJP+9/ipJ53o8
|
||||
jxWByU5npBWuw6qF432b98dhKvisW5Uu1hw8z935ld7uk3nF2mWAxzrTq8GE+Mn5
|
||||
Ic0yDmxnd/6rgUuAVtfGMDsKCks7P0J4bvxIG8fDnWh40SwNffrlHZ1Fz/yqJCCl
|
||||
tzkbQnX7lp4JGq1NkubgIchQ5pJzoqzWSShr72tyipjpTBIKDWT6TMapp0Y+veJX
|
||||
jl4fXs0CgYEA2kBFyO+/BSjOLmlftvos1YqrJD9eSy9ydSY9jRF/6qX1AWbbmH2c
|
||||
rIN+kLeQtoFP87BMpMU1qDhmqbXx+WLaMYU0RTB8oNhriUbXE2hs7ndGm/FS8yzu
|
||||
wG0xHBT8Bm8WA/5/bmFbjUCA7eSKYczYrHFd/aaf5HKGtGFJx8jz4t8CgYEAyCKm
|
||||
vqJ1WGK2Ql/hN1Gw3/rmyzgPqMgfq0gi7cQ3bRY/txK5vWHcDQdIywpxmmMWpkzy
|
||||
UX3m9hMb2ao01riFngIhBJslong0ExLSv50bi9evCAL0dZCQFPaBCgjNoMRjofGq
|
||||
SE0fJMDEOqcEt2fEAH8Fa4FUw9MKAypV++H7s5MCgYEA1gZpaN8Sp/CYIJNdNYao
|
||||
KNDPe8BYq8pfp9pUSd57XpRYa4N+nU+xMMvSdgBNfWvaB9M/leV+9PQ6WPr/y9vQ
|
||||
tPc3hxJBZUpWSkyZ5YJmMIPvTkWdXrMVfsaVfkBl1bliEZClTo1SxnYW+TNBMR88
|
||||
6/5QecnIyrI0vvcY7z51TGkCgYB8CpYEc5Z9WHkUPG7PJY+V0uE2tSFnf9m5BDW5
|
||||
3jJoJzEIW8/JJB0J6ijgxzFP+fgwzGInxfvfKkrJpqenKaiPHUyvmSVDRHMqGzGJ
|
||||
12saSmzOb15qe1YB2CJ0QK6J5Q7HcYwT0dDqq5szqw7OSb7+e7u1POx3jpaXDadL
|
||||
PW4OhwKBgHcZWsXJUaKesNJbeGeRKmQHooSdrE69gika1HU7GYmTV3JwvAFrHSNF
|
||||
EGMMTmWc6nTh63ADO/f+dpAoJVOQM/OhEVVyfvlByLEFeieGegwyREWVYajW+6Dt
|
||||
Ztrafmyvn+r3yhWN9g+p1yQTeVLw23ir9cYhP8OqnL4d89c3o+r3
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -1,36 +0,0 @@
|
||||
; basic options
|
||||
[common]
|
||||
; frps panel config info
|
||||
plugin_addr = 127.0.0.1
|
||||
plugin_port = 7200
|
||||
admin_user = admin
|
||||
admin_pwd = admin
|
||||
|
||||
; enable tls
|
||||
tls_mode = false
|
||||
; tls_cert_file = cert.crt
|
||||
; tls_key_file = cert.key
|
||||
|
||||
; frp dashboard info
|
||||
dashboard_addr = 127.0.0.1
|
||||
dashboard_port = 7500
|
||||
dashboard_user = admin
|
||||
dashboard_pwd = admin
|
||||
; if your frps dashboard enable tls, change this to true
|
||||
dashboard_tls = false
|
||||
|
||||
; user tokens
|
||||
[users]
|
||||
user1 = token1
|
||||
|
||||
; user been disabled
|
||||
[disabled]
|
||||
|
||||
; user allowed ports. it will be used when a new proxy connect on
|
||||
[ports]
|
||||
|
||||
; user allowed domains. it will be used when a new proxy connect on
|
||||
[domains]
|
||||
|
||||
; user allowed subdomains. it will be used when a new proxy connect on
|
||||
[subdomains]
|
||||
21
config/frps-panel.toml
Normal file
21
config/frps-panel.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
# basic options
|
||||
[common]
|
||||
# frps panel config info
|
||||
plugin_addr = "127.0.0.1"
|
||||
plugin_port = 7200
|
||||
#admin_user = "admin"
|
||||
#admin_pwd = "admin"
|
||||
# specified login state keep time
|
||||
admin_keep_time = 0
|
||||
|
||||
# enable tls
|
||||
tls_mode = false
|
||||
#tls_cert_file = "cert.crt"
|
||||
#tls_key_file = "cert.key"
|
||||
|
||||
# frp dashboard info
|
||||
dashboard_addr = "127.0.0.1"
|
||||
dashboard_port = 7500
|
||||
dashboard_user = "admin"
|
||||
dashboard_pwd = "admin"
|
||||
|
||||
17
config/frps-tokens.toml
Normal file
17
config/frps-tokens.toml
Normal file
@@ -0,0 +1,17 @@
|
||||
[tokens]
|
||||
[tokens.user1]
|
||||
user = "user1"
|
||||
token = "token1"
|
||||
comment = "user1 with token1"
|
||||
ports = [8080, "10000-10200"]
|
||||
domains = ["web01.domain.com", "web02.domain.com"]
|
||||
subdomains = ["web01", "web02"]
|
||||
enable = false
|
||||
[tokens.user2]
|
||||
user = "user2"
|
||||
token = "token2"
|
||||
comment = "user2 with token2"
|
||||
ports = [9080]
|
||||
domains = ["web11.domain.com", "web12.domain.com"]
|
||||
subdomains = ["web11", "web12"]
|
||||
enable = false
|
||||
10
go.mod
10
go.mod
@@ -3,11 +3,14 @@ module frps-panel
|
||||
go 1.21
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.0.0
|
||||
github.com/fatedier/frp v0.34.1
|
||||
github.com/gin-contrib/i18n v1.0.0
|
||||
github.com/gin-contrib/sessions v0.0.5
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/pelletier/go-toml/v2 v2.0.9
|
||||
github.com/spf13/cobra v0.0.3
|
||||
gopkg.in/ini.v1 v1.67.0
|
||||
golang.org/x/text v0.11.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -22,6 +25,9 @@ require (
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.1 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/gorilla/context v1.1.1 // indirect
|
||||
github.com/gorilla/securecookie v1.1.1 // indirect
|
||||
github.com/gorilla/sessions v1.2.1 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
|
||||
@@ -30,7 +36,6 @@ require (
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/nicksnyder/go-i18n/v2 v2.2.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.9 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
@@ -38,7 +43,6 @@ require (
|
||||
golang.org/x/crypto v0.11.0 // indirect
|
||||
golang.org/x/net v0.12.0 // indirect
|
||||
golang.org/x/sys v0.10.0 // indirect
|
||||
golang.org/x/text v0.11.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
10
go.sum
10
go.sum
@@ -46,6 +46,8 @@ github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9
|
||||
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/gin-contrib/i18n v1.0.0 h1:e5uEOmaAr09Iyr4vuWuvvpByjmvxGDO7iSkmiFpSsk0=
|
||||
github.com/gin-contrib/i18n v1.0.0/go.mod h1:yyyTArpVZeXCFT/kbLbD5CS192+OZ8Y+angnJjvnB98=
|
||||
github.com/gin-contrib/sessions v0.0.5 h1:CATtfHmLMQrMNpJRgzjWXD7worTh7g7ritsQfmF+0jE=
|
||||
github.com/gin-contrib/sessions v0.0.5/go.mod h1:vYAuaUPqie3WUSsft6HUlCjlwwoJQs97miaG2+7neKY=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
@@ -95,7 +97,13 @@ github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
|
||||
github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY=
|
||||
github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
|
||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
|
||||
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
|
||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM=
|
||||
@@ -293,8 +301,6 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogR
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/square/go-jose.v2 v2.4.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/bin/bash
|
||||
version=$(cat cmd/frps-panel/cmd.go | grep 'const version' | egrep -o '[0-9.]+')
|
||||
cd ./release || exit
|
||||
rm -rf *.zip
|
||||
list=$(ls frps-panel-*)
|
||||
@@ -6,11 +7,13 @@ echo "$list"
|
||||
for binFile in $list
|
||||
do
|
||||
tmpFile=frps-panel
|
||||
newBinFile=$binFile
|
||||
if echo "$binFile" | grep -q -E "\.exe";then
|
||||
tmpFile=frps-panel.exe
|
||||
newBinFile=${newBinFile%%.exe*}
|
||||
fi
|
||||
cp "$binFile" "$tmpFile"
|
||||
zip -r "$binFile".zip "$tmpFile" frps-panel.ini assets -x "*.git*" "*.idea*" "*.DS_Store" "*.contentFlavour"
|
||||
zip -r "$newBinFile-$version".zip "$tmpFile" frps-panel.toml frps-tokens.toml assets -x "*.git*" "*.idea*" "*.DS_Store" "*.contentFlavour"
|
||||
rm -rf "$binFile" "$tmpFile"
|
||||
done
|
||||
rm -rf frps-panel.ini assets
|
||||
rm -rf frps-panel.toml frps-tokens.toml assets
|
||||
|
||||
104
pkg/server/controller/authorizer.go
Normal file
104
pkg/server/controller/authorizer.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (c *HandleController) BasicAuth() gin.HandlerFunc {
|
||||
return func(context *gin.Context) {
|
||||
if trimString(c.CommonInfo.AdminUser) == "" || trimString(c.CommonInfo.AdminPwd) == "" {
|
||||
if context.Request.RequestURI == LoginUrl {
|
||||
context.Redirect(http.StatusTemporaryRedirect, LoginSuccessUrl)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
session := sessions.Default(context)
|
||||
auth := session.Get(AuthName)
|
||||
|
||||
if auth != nil {
|
||||
if c.CommonInfo.AdminKeepTime > 0 {
|
||||
cookie, _ := context.Request.Cookie(SessionName)
|
||||
if cookie != nil {
|
||||
//important thx https://blog.csdn.net/zhanghongxia8285/article/details/107321838/
|
||||
cookie.Expires = time.Now().Add(time.Second * time.Duration(c.CommonInfo.AdminKeepTime))
|
||||
http.SetCookie(context.Writer, cookie)
|
||||
}
|
||||
}
|
||||
|
||||
username, password, _ := parseBasicAuth(fmt.Sprintf("%v", auth))
|
||||
|
||||
usernameMatch := username == c.CommonInfo.AdminUser
|
||||
passwordMatch := password == c.CommonInfo.AdminPwd
|
||||
|
||||
if usernameMatch && passwordMatch {
|
||||
context.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
isAjax := context.GetHeader("X-Requested-With") == "XMLHttpRequest"
|
||||
|
||||
if !isAjax && context.Request.RequestURI != LoginUrl {
|
||||
context.Redirect(http.StatusTemporaryRedirect, LoginUrl)
|
||||
} else {
|
||||
context.AbortWithStatus(http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HandleController) LoginAuth(username, password string, context *gin.Context) bool {
|
||||
if trimString(c.CommonInfo.AdminUser) == "" || trimString(c.CommonInfo.AdminPwd) == "" {
|
||||
return true
|
||||
}
|
||||
|
||||
session := sessions.Default(context)
|
||||
|
||||
sessionAuth := session.Get(AuthName)
|
||||
internalAuth := encodeBasicAuth(c.CommonInfo.AdminUser, c.CommonInfo.AdminPwd)
|
||||
|
||||
if sessionAuth == internalAuth {
|
||||
return true
|
||||
} else {
|
||||
basicAuth := encodeBasicAuth(username, password)
|
||||
if basicAuth == internalAuth {
|
||||
session.Set(AuthName, basicAuth)
|
||||
_ = session.Save()
|
||||
return true
|
||||
} else {
|
||||
session.Delete(AuthName)
|
||||
_ = session.Save()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ClearAuth(context *gin.Context) {
|
||||
session := sessions.Default(context)
|
||||
session.Delete(AuthName)
|
||||
_ = session.Save()
|
||||
}
|
||||
|
||||
func parseBasicAuth(auth string) (username, password string, ok bool) {
|
||||
c, err := base64.StdEncoding.DecodeString(auth)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
cs := string(c)
|
||||
username, password, ok = strings.Cut(cs, ":")
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
|
||||
func encodeBasicAuth(username, password string) string {
|
||||
authString := fmt.Sprintf("%s:%s", username, password)
|
||||
return base64.StdEncoding.EncodeToString([]byte(authString))
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package controller
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -12,105 +11,11 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
Success = 0
|
||||
ParamError = 1
|
||||
UserExist = 2
|
||||
SaveError = 3
|
||||
UserFormatError = 4
|
||||
TokenFormatError = 5
|
||||
FrpServerError = 6
|
||||
)
|
||||
|
||||
var UserFormatReg = regexp.MustCompile("^\\w+$")
|
||||
var TokenFormatReg = regexp.MustCompile("^[\\w!@#$%^&*()]+$")
|
||||
var TrimAllSpaceReg = regexp.MustCompile("[\\n\\t\\r\\s]")
|
||||
var TrimBreakLineReg = regexp.MustCompile("[\\n\\t\\r]")
|
||||
|
||||
type Response struct {
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
type HTTPError struct {
|
||||
Code int
|
||||
Err error
|
||||
}
|
||||
|
||||
type CommonInfo struct {
|
||||
PluginAddr string
|
||||
PluginPort int
|
||||
User string
|
||||
Pwd string
|
||||
DashboardTLS bool
|
||||
DashboardAddr string
|
||||
DashboardPort int
|
||||
DashboardUser string
|
||||
DashboardPwd string
|
||||
}
|
||||
|
||||
type TokenInfo struct {
|
||||
User string `json:"user" form:"user"`
|
||||
Token string `json:"token" form:"token"`
|
||||
Comment string `json:"comment" form:"comment"`
|
||||
Ports string `json:"ports" from:"ports"`
|
||||
Domains string `json:"domains" from:"domains"`
|
||||
Subdomains string `json:"subdomains" from:"subdomains"`
|
||||
Status bool `json:"status" form:"status"`
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Count int `json:"count"`
|
||||
Data []TokenInfo `json:"data"`
|
||||
}
|
||||
|
||||
type OperationResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type ProxyResponse struct {
|
||||
OperationResponse
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
type TokenSearch struct {
|
||||
TokenInfo
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
type TokenUpdate struct {
|
||||
Before TokenInfo `json:"before"`
|
||||
After TokenInfo `json:"after"`
|
||||
}
|
||||
|
||||
type TokenRemove struct {
|
||||
Users []TokenInfo `json:"users"`
|
||||
}
|
||||
|
||||
type TokenDisable struct {
|
||||
TokenRemove
|
||||
}
|
||||
|
||||
type TokenEnable struct {
|
||||
TokenDisable
|
||||
}
|
||||
|
||||
func (e *HTTPError) Error() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
type HandlerFunc func(ctx *gin.Context) (interface{}, error)
|
||||
|
||||
func (c *HandleController) MakeHandlerFunc() gin.HandlerFunc {
|
||||
return func(context *gin.Context) {
|
||||
var response plugin.Response
|
||||
@@ -118,19 +23,13 @@ func (c *HandleController) MakeHandlerFunc() gin.HandlerFunc {
|
||||
|
||||
request := plugin.Request{}
|
||||
if err := context.BindJSON(&request); err != nil {
|
||||
_ = context.Error(&HTTPError{
|
||||
Code: http.StatusBadRequest,
|
||||
Err: err,
|
||||
})
|
||||
_ = context.AbortWithError(http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
jsonStr, err := json.Marshal(request.Content)
|
||||
if err != nil {
|
||||
_ = context.Error(&HTTPError{
|
||||
Code: http.StatusBadRequest,
|
||||
Err: err,
|
||||
})
|
||||
_ = context.AbortWithError(http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -175,10 +74,54 @@ func (c *HandleController) MakeHandlerFunc() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HandleController) MakeManagerFunc() func(context *gin.Context) {
|
||||
func (c *HandleController) MakeLoginFunc() func(context *gin.Context) {
|
||||
return func(context *gin.Context) {
|
||||
if context.Request.Method == "GET" {
|
||||
if c.LoginAuth("", "", context) {
|
||||
if context.Request.RequestURI == LoginUrl {
|
||||
context.Redirect(http.StatusTemporaryRedirect, LoginSuccessUrl)
|
||||
}
|
||||
return
|
||||
}
|
||||
context.HTML(http.StatusOK, "login.html", gin.H{
|
||||
"version": c.Version,
|
||||
"FrpsPanel": ginI18n.MustGetMessage(context, "Frps Panel"),
|
||||
"Username": ginI18n.MustGetMessage(context, "Username"),
|
||||
"Password": ginI18n.MustGetMessage(context, "Password"),
|
||||
"Login": ginI18n.MustGetMessage(context, "Login"),
|
||||
"PleaseInputUsername": ginI18n.MustGetMessage(context, "Please input username"),
|
||||
"PleaseInputPassword": ginI18n.MustGetMessage(context, "Please input password"),
|
||||
})
|
||||
} else if context.Request.Method == "POST" {
|
||||
username := context.PostForm("username")
|
||||
password := context.PostForm("password")
|
||||
if c.LoginAuth(username, password, context) {
|
||||
context.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": ginI18n.MustGetMessage(context, "Login success"),
|
||||
})
|
||||
} else {
|
||||
context.JSON(http.StatusOK, gin.H{
|
||||
"success": false,
|
||||
"message": ginI18n.MustGetMessage(context, "Username or password incorrect"),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HandleController) MakeLogoutFunc() func(context *gin.Context) {
|
||||
return func(context *gin.Context) {
|
||||
ClearAuth(context)
|
||||
context.Redirect(http.StatusTemporaryRedirect, LogoutSuccessUrl)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HandleController) MakeIndexFunc() func(context *gin.Context) {
|
||||
return func(context *gin.Context) {
|
||||
context.HTML(http.StatusOK, "index.html", gin.H{
|
||||
"version": c.Version,
|
||||
"showExit": trimString(c.CommonInfo.AdminUser) != "" && trimString(c.CommonInfo.AdminPwd) != "",
|
||||
"FrpsPanel": ginI18n.MustGetMessage(context, "Frps Panel"),
|
||||
"User": ginI18n.MustGetMessage(context, "User"),
|
||||
"Token": ginI18n.MustGetMessage(context, "Token"),
|
||||
@@ -261,6 +204,7 @@ func (c *HandleController) MakeLangFunc() func(context *gin.Context) {
|
||||
"OperateError": ginI18n.MustGetMessage(context, "Operate error"),
|
||||
"OperateFailed": ginI18n.MustGetMessage(context, "Operate failed"),
|
||||
"UserExist": ginI18n.MustGetMessage(context, "User exist"),
|
||||
"UserNotExist": ginI18n.MustGetMessage(context, "User not exist"),
|
||||
"UserFormatError": ginI18n.MustGetMessage(context, "User format error"),
|
||||
"TokenFormatError": ginI18n.MustGetMessage(context, "Token format error"),
|
||||
"ShouldCheckUser": ginI18n.MustGetMessage(context, "Please check at least one user"),
|
||||
@@ -275,6 +219,7 @@ func (c *HandleController) MakeLangFunc() func(context *gin.Context) {
|
||||
"SubdomainsInvalid": ginI18n.MustGetMessage(context, "Subdomains is invalid"),
|
||||
"CommentInvalid": ginI18n.MustGetMessage(context, "Comment is invalid"),
|
||||
"ParamError": ginI18n.MustGetMessage(context, "Param error"),
|
||||
"OtherError": ginI18n.MustGetMessage(context, "Other error"),
|
||||
"Name": ginI18n.MustGetMessage(context, "Name"),
|
||||
"Port": ginI18n.MustGetMessage(context, "Port"),
|
||||
"Connections": ginI18n.MustGetMessage(context, "Connections"),
|
||||
@@ -292,6 +237,7 @@ func (c *HandleController) MakeLangFunc() func(context *gin.Context) {
|
||||
"Proxies": ginI18n.MustGetMessage(context, "Proxies"),
|
||||
"NotSet": ginI18n.MustGetMessage(context, "Not Set"),
|
||||
"Proxy": ginI18n.MustGetMessage(context, "Proxy"),
|
||||
"TokenInvalid": ginI18n.MustGetMessage(context, "Token invalid"),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -341,34 +287,10 @@ func (c *HandleController) MakeQueryTokensFunc() func(context *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func filter(main TokenInfo, sub TokenInfo) bool {
|
||||
replaceSpaceUser := TrimAllSpaceReg.ReplaceAllString(sub.User, "")
|
||||
if len(replaceSpaceUser) != 0 {
|
||||
if !strings.Contains(main.User, replaceSpaceUser) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
replaceSpaceToken := TrimAllSpaceReg.ReplaceAllString(sub.Token, "")
|
||||
if len(replaceSpaceToken) != 0 {
|
||||
if !strings.Contains(main.Token, replaceSpaceToken) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
replaceSpaceComment := TrimAllSpaceReg.ReplaceAllString(sub.Comment, "")
|
||||
if len(replaceSpaceComment) != 0 {
|
||||
if !strings.Contains(main.Comment, replaceSpaceComment) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *HandleController) MakeAddTokenFunc() func(context *gin.Context) {
|
||||
return func(context *gin.Context) {
|
||||
info := TokenInfo{
|
||||
Status: true,
|
||||
Enable: true,
|
||||
}
|
||||
response := OperationResponse{
|
||||
Success: true,
|
||||
@@ -377,72 +299,34 @@ func (c *HandleController) MakeAddTokenFunc() func(context *gin.Context) {
|
||||
}
|
||||
err := context.BindJSON(&info)
|
||||
if err != nil {
|
||||
log.Printf("user add failed, param error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = ParamError
|
||||
response.Message = "user add failed, param error "
|
||||
response.Message = fmt.Sprintf("user add failed, param error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
if !UserFormatReg.MatchString(info.User) {
|
||||
log.Printf("user add failed, user format error")
|
||||
response.Success = false
|
||||
response.Code = UserFormatError
|
||||
response.Message = fmt.Sprintf("user add failed, user format error")
|
||||
context.JSON(http.StatusOK, &response)
|
||||
|
||||
result := c.verifyToken(info, TOKEN_ADD)
|
||||
|
||||
if !result.Success {
|
||||
context.JSON(http.StatusOK, &result)
|
||||
return
|
||||
}
|
||||
if _, exist := c.Tokens[info.User]; exist {
|
||||
log.Printf("user add failed, user [%v] exist", info.User)
|
||||
response.Success = false
|
||||
response.Code = UserExist
|
||||
response.Message = fmt.Sprintf("user add failed, user [%s] exist ", info.User)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
if !TokenFormatReg.MatchString(info.Token) {
|
||||
log.Printf("user add failed, token format error")
|
||||
response.Success = false
|
||||
response.Code = TokenFormatError
|
||||
response.Message = fmt.Sprintf("user add failed, token format error")
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
replaceSpaceToken := TrimAllSpaceReg.ReplaceAllString(info.Token, "")
|
||||
info.Token = replaceSpaceToken
|
||||
|
||||
info.Comment = cleanString(info.Comment)
|
||||
info.Ports = cleanPorts(info.Ports)
|
||||
info.Domains = cleanStrings(info.Domains)
|
||||
info.Subdomains = cleanStrings(info.Subdomains)
|
||||
|
||||
c.Tokens[info.User] = info
|
||||
|
||||
usersSection, _ := c.IniFile.GetSection("users")
|
||||
key, err := usersSection.NewKey(info.User, info.Token)
|
||||
key.Comment = info.Comment
|
||||
|
||||
replaceSpacePorts := TrimAllSpaceReg.ReplaceAllString(info.Ports, "")
|
||||
if len(replaceSpacePorts) != 0 {
|
||||
portsSection, _ := c.IniFile.GetSection("ports")
|
||||
key, err = portsSection.NewKey(info.User, replaceSpacePorts)
|
||||
key.Comment = fmt.Sprintf("user %s allowed ports", info.User)
|
||||
}
|
||||
|
||||
replaceSpaceDomains := TrimAllSpaceReg.ReplaceAllString(info.Domains, "")
|
||||
if len(replaceSpaceDomains) != 0 {
|
||||
domainsSection, _ := c.IniFile.GetSection("domains")
|
||||
key, err = domainsSection.NewKey(info.User, replaceSpaceDomains)
|
||||
key.Comment = fmt.Sprintf("user %s allowed domains", info.User)
|
||||
}
|
||||
|
||||
replaceSpaceSubdomains := TrimAllSpaceReg.ReplaceAllString(info.Subdomains, "")
|
||||
if len(replaceSpaceSubdomains) != 0 {
|
||||
subdomainsSection, _ := c.IniFile.GetSection("subdomains")
|
||||
key, err = subdomainsSection.NewKey(info.User, replaceSpaceSubdomains)
|
||||
key.Comment = fmt.Sprintf("user %s allowed subdomains", info.User)
|
||||
}
|
||||
|
||||
err = c.IniFile.SaveTo(c.ConfigFile)
|
||||
err = c.saveToken()
|
||||
if err != nil {
|
||||
log.Printf("add failed, error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = SaveError
|
||||
response.Message = "user add failed"
|
||||
response.Message = fmt.Sprintf("user add failed, error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
@@ -461,88 +345,46 @@ func (c *HandleController) MakeUpdateTokensFunc() func(context *gin.Context) {
|
||||
update := TokenUpdate{}
|
||||
err := context.BindJSON(&update)
|
||||
if err != nil {
|
||||
log.Printf("update failed, param error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = ParamError
|
||||
response.Message = "user update failed, param error "
|
||||
response.Message = fmt.Sprintf("update failed, param error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
|
||||
after := update.After
|
||||
before := update.Before
|
||||
after := update.After
|
||||
|
||||
usersSection, _ := c.IniFile.GetSection("users")
|
||||
key, err := usersSection.GetKey(before.User)
|
||||
comment := TrimBreakLineReg.ReplaceAllString(after.Comment, "")
|
||||
after.Comment = comment
|
||||
key.Comment = comment
|
||||
|
||||
if !TokenFormatReg.MatchString(after.Token) {
|
||||
log.Printf("update failed, token format error")
|
||||
if before.User != after.User {
|
||||
response.Success = false
|
||||
response.Code = TokenFormatError
|
||||
response.Message = "user update failed, token format error "
|
||||
response.Code = ParamError
|
||||
response.Message = fmt.Sprintf("update failed, user should be same : before -> %v, after -> %v", before.User, after.User)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
replaceSpaceToken := TrimAllSpaceReg.ReplaceAllString(after.Token, "")
|
||||
after.Token = replaceSpaceToken
|
||||
key.SetValue(replaceSpaceToken)
|
||||
|
||||
if before.Ports != after.Ports {
|
||||
portsSection, _ := c.IniFile.GetSection("ports")
|
||||
replaceSpacePorts := TrimAllSpaceReg.ReplaceAllString(after.Ports, "")
|
||||
after.Ports = replaceSpacePorts
|
||||
ports := strings.Split(replaceSpacePorts, ",")
|
||||
if len(replaceSpacePorts) != 0 {
|
||||
key, err = portsSection.NewKey(after.User, replaceSpacePorts)
|
||||
key.Comment = fmt.Sprintf("user %s allowed ports", after.User)
|
||||
c.Ports[after.User] = ports
|
||||
} else {
|
||||
portsSection.DeleteKey(after.User)
|
||||
delete(c.Ports, after.User)
|
||||
}
|
||||
result := c.verifyToken(after, TOKEN_UPDATE)
|
||||
|
||||
if !result.Success {
|
||||
context.JSON(http.StatusOK, &result)
|
||||
return
|
||||
}
|
||||
|
||||
if before.Domains != after.Domains {
|
||||
domainsSection, _ := c.IniFile.GetSection("domains")
|
||||
replaceSpaceDomains := TrimAllSpaceReg.ReplaceAllString(after.Domains, "")
|
||||
after.Domains = replaceSpaceDomains
|
||||
domains := strings.Split(replaceSpaceDomains, ",")
|
||||
if len(replaceSpaceDomains) != 0 {
|
||||
key, err = domainsSection.NewKey(after.User, replaceSpaceDomains)
|
||||
key.Comment = fmt.Sprintf("user %s allowed domains", after.User)
|
||||
c.Domains[after.User] = domains
|
||||
} else {
|
||||
domainsSection.DeleteKey(after.User)
|
||||
delete(c.Domains, after.User)
|
||||
}
|
||||
}
|
||||
|
||||
if before.Subdomains != after.Subdomains {
|
||||
subdomainsSection, _ := c.IniFile.GetSection("subdomains")
|
||||
replaceSpaceSubdomains := TrimAllSpaceReg.ReplaceAllString(after.Subdomains, "")
|
||||
after.Subdomains = replaceSpaceSubdomains
|
||||
subdomains := strings.Split(replaceSpaceSubdomains, ",")
|
||||
if len(replaceSpaceSubdomains) != 0 {
|
||||
key, err = subdomainsSection.NewKey(after.User, replaceSpaceSubdomains)
|
||||
key.Comment = fmt.Sprintf("user %s allowed subdomains", after.User)
|
||||
c.Subdomains[after.User] = subdomains
|
||||
} else {
|
||||
subdomainsSection.DeleteKey(after.User)
|
||||
delete(c.Subdomains, after.User)
|
||||
}
|
||||
}
|
||||
after.Comment = cleanString(after.Comment)
|
||||
after.Ports = cleanPorts(after.Ports)
|
||||
after.Domains = cleanStrings(after.Domains)
|
||||
after.Subdomains = cleanStrings(after.Subdomains)
|
||||
|
||||
c.Tokens[after.User] = after
|
||||
|
||||
err = c.IniFile.SaveTo(c.ConfigFile)
|
||||
err = c.saveToken()
|
||||
if err != nil {
|
||||
log.Printf("user update failed, error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = SaveError
|
||||
response.Message = "user update failed"
|
||||
response.Message = fmt.Sprintf("user update failed, error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
@@ -561,44 +403,33 @@ func (c *HandleController) MakeRemoveTokensFunc() func(context *gin.Context) {
|
||||
remove := TokenRemove{}
|
||||
err := context.BindJSON(&remove)
|
||||
if err != nil {
|
||||
log.Printf("user remove failed, param error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = ParamError
|
||||
response.Message = "user remove failed, param error "
|
||||
response.Message = fmt.Sprintf("user remove failed, param error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
|
||||
usersSection, _ := c.IniFile.GetSection("users")
|
||||
for _, user := range remove.Users {
|
||||
result := c.verifyToken(user, TOKEN_REMOVE)
|
||||
|
||||
if !result.Success {
|
||||
context.JSON(http.StatusOK, &result)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for _, user := range remove.Users {
|
||||
delete(c.Tokens, user.User)
|
||||
usersSection.DeleteKey(user.User)
|
||||
}
|
||||
|
||||
portsSection, _ := c.IniFile.GetSection("ports")
|
||||
for _, user := range remove.Users {
|
||||
delete(c.Ports, user.User)
|
||||
portsSection.DeleteKey(user.User)
|
||||
}
|
||||
|
||||
domainsSection, _ := c.IniFile.GetSection("domains")
|
||||
for _, user := range remove.Users {
|
||||
delete(c.Domains, user.User)
|
||||
domainsSection.DeleteKey(user.User)
|
||||
}
|
||||
|
||||
subdomainsSection, _ := c.IniFile.GetSection("subdomains")
|
||||
for _, user := range remove.Users {
|
||||
delete(c.Subdomains, user.User)
|
||||
subdomainsSection.DeleteKey(user.User)
|
||||
}
|
||||
|
||||
err = c.IniFile.SaveTo(c.ConfigFile)
|
||||
err = c.saveToken()
|
||||
if err != nil {
|
||||
log.Printf("user remove failed, error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = SaveError
|
||||
response.Message = "user remove failed"
|
||||
response.Message = fmt.Sprintf("user update failed, error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
@@ -617,38 +448,36 @@ func (c *HandleController) MakeDisableTokensFunc() func(context *gin.Context) {
|
||||
disable := TokenDisable{}
|
||||
err := context.BindJSON(&disable)
|
||||
if err != nil {
|
||||
log.Printf("disable failed, param error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = ParamError
|
||||
response.Message = "disable failed, param error "
|
||||
response.Message = fmt.Sprintf("disable failed, param error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
|
||||
section, _ := c.IniFile.GetSection("disabled")
|
||||
for _, user := range disable.Users {
|
||||
section.DeleteKey(user.User)
|
||||
token := c.Tokens[user.User]
|
||||
token.Status = false
|
||||
c.Tokens[user.User] = token
|
||||
key, err := section.NewKey(user.User, "disable")
|
||||
if err != nil {
|
||||
log.Printf("disable failed, error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = SaveError
|
||||
response.Message = "disable failed"
|
||||
context.JSON(http.StatusOK, &response)
|
||||
result := c.verifyToken(user, TOKEN_DISABLE)
|
||||
|
||||
if !result.Success {
|
||||
context.JSON(http.StatusOK, &result)
|
||||
return
|
||||
}
|
||||
key.Comment = fmt.Sprintf("disable user '%s'", user.User)
|
||||
}
|
||||
|
||||
err = c.IniFile.SaveTo(c.ConfigFile)
|
||||
for _, user := range disable.Users {
|
||||
token := c.Tokens[user.User]
|
||||
token.Enable = false
|
||||
c.Tokens[user.User] = token
|
||||
}
|
||||
|
||||
err = c.saveToken()
|
||||
|
||||
if err != nil {
|
||||
log.Printf("disable failed, error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = SaveError
|
||||
response.Message = "disable failed"
|
||||
response.Message = fmt.Sprintf("disable failed, error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
@@ -667,23 +496,31 @@ func (c *HandleController) MakeEnableTokensFunc() func(context *gin.Context) {
|
||||
enable := TokenEnable{}
|
||||
err := context.BindJSON(&enable)
|
||||
if err != nil {
|
||||
log.Printf("enable failed, param error : %v", err)
|
||||
response.Success = false
|
||||
response.Code = ParamError
|
||||
response.Message = "enable failed, param error "
|
||||
response.Message = fmt.Sprintf("enable failed, param error : %v", err)
|
||||
log.Printf(response.Message)
|
||||
context.JSON(http.StatusOK, &response)
|
||||
return
|
||||
}
|
||||
|
||||
section, _ := c.IniFile.GetSection("disabled")
|
||||
for _, user := range enable.Users {
|
||||
section.DeleteKey(user.User)
|
||||
result := c.verifyToken(user, TOKEN_ENABLE)
|
||||
|
||||
if !result.Success {
|
||||
context.JSON(http.StatusOK, &result)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
for _, user := range enable.Users {
|
||||
token := c.Tokens[user.User]
|
||||
token.Status = true
|
||||
token.Enable = true
|
||||
c.Tokens[user.User] = token
|
||||
}
|
||||
|
||||
err = c.IniFile.SaveTo(c.ConfigFile)
|
||||
err = c.saveToken()
|
||||
|
||||
if err != nil {
|
||||
log.Printf("enable failed, error : %v", err)
|
||||
response.Success = false
|
||||
@@ -702,7 +539,7 @@ func (c *HandleController) MakeProxyFunc() func(context *gin.Context) {
|
||||
var client *http.Client
|
||||
var protocol string
|
||||
|
||||
if c.CommonInfo.DashboardTLS {
|
||||
if c.CommonInfo.DashboardTls {
|
||||
client = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
@@ -722,12 +559,10 @@ func (c *HandleController) MakeProxyFunc() func(context *gin.Context) {
|
||||
requestUrl := protocol + host + ":" + strconv.Itoa(port) + context.Param("serverApi")
|
||||
request, _ := http.NewRequest("GET", requestUrl, nil)
|
||||
username := c.CommonInfo.DashboardUser
|
||||
if len(strings.TrimSpace(username)) != 0 {
|
||||
password := c.CommonInfo.DashboardPwd
|
||||
userAndPwd := []byte(username + ":" + password)
|
||||
authorization := "Basic " + base64.StdEncoding.EncodeToString(userAndPwd)
|
||||
request.Header.Add("Authorization", authorization)
|
||||
log.Printf("Proxy to %s with Authorization %s", requestUrl, authorization)
|
||||
password := c.CommonInfo.DashboardPwd
|
||||
if trimString(username) != "" && trimString(password) != "" {
|
||||
request.SetBasicAuth(username, password)
|
||||
log.Printf("Proxy to %s", requestUrl)
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
@@ -751,10 +586,14 @@ func (c *HandleController) MakeProxyFunc() func(context *gin.Context) {
|
||||
if res.Code == http.StatusOK {
|
||||
res.Success = true
|
||||
res.Data = string(body)
|
||||
res.Message = "Proxy to " + requestUrl + " success"
|
||||
res.Message = fmt.Sprintf("Proxy to %s success", requestUrl)
|
||||
} else {
|
||||
res.Success = false
|
||||
res.Message = "Proxy to " + requestUrl + " error: " + string(body)
|
||||
if res.Code == http.StatusNotFound {
|
||||
res.Message = fmt.Sprintf("Proxy to %s error: url not found", requestUrl)
|
||||
} else {
|
||||
res.Message = fmt.Sprintf("Proxy to %s error: %s", requestUrl, string(body))
|
||||
}
|
||||
}
|
||||
}
|
||||
log.Printf(res.Message)
|
||||
|
||||
@@ -3,61 +3,11 @@ package controller
|
||||
import (
|
||||
"fmt"
|
||||
plugin "github.com/fatedier/frp/pkg/plugin/server"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gopkg.in/ini.v1"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type HandleController struct {
|
||||
CommonInfo CommonInfo
|
||||
Tokens map[string]TokenInfo
|
||||
Ports map[string][]string
|
||||
Domains map[string][]string
|
||||
Subdomains map[string][]string
|
||||
ConfigFile string
|
||||
IniFile *ini.File
|
||||
Version string
|
||||
}
|
||||
|
||||
func NewHandleController(config *HandleController) *HandleController {
|
||||
return config
|
||||
}
|
||||
|
||||
func (c *HandleController) Register(rootDir string, engine *gin.Engine) {
|
||||
assets := filepath.Join(rootDir, "assets")
|
||||
_, err := os.Stat(assets)
|
||||
if err != nil && !os.IsExist(err) {
|
||||
assets = "./assets"
|
||||
}
|
||||
|
||||
engine.Delims("${", "}")
|
||||
engine.LoadHTMLGlob(filepath.Join(assets, "templates/*"))
|
||||
engine.POST("/handler", c.MakeHandlerFunc())
|
||||
|
||||
var group *gin.RouterGroup
|
||||
if len(c.CommonInfo.User) != 0 {
|
||||
group = engine.Group("/", gin.BasicAuthForRealm(gin.Accounts{
|
||||
c.CommonInfo.User: c.CommonInfo.Pwd,
|
||||
}, "Restricted"))
|
||||
} else {
|
||||
group = engine.Group("/")
|
||||
}
|
||||
group.Static("/static", filepath.Join(assets, "static"))
|
||||
group.GET("/", c.MakeManagerFunc())
|
||||
group.GET("/lang.json", c.MakeLangFunc())
|
||||
group.GET("/tokens", c.MakeQueryTokensFunc())
|
||||
group.POST("/add", c.MakeAddTokenFunc())
|
||||
group.POST("/update", c.MakeUpdateTokensFunc())
|
||||
group.POST("/remove", c.MakeRemoveTokensFunc())
|
||||
group.POST("/disable", c.MakeDisableTokensFunc())
|
||||
group.POST("/enable", c.MakeEnableTokensFunc())
|
||||
group.GET("/proxy/*serverApi", c.MakeProxyFunc())
|
||||
}
|
||||
|
||||
func (c *HandleController) HandleLogin(content *plugin.LoginContent) plugin.Response {
|
||||
token := content.Metas["token"]
|
||||
user := content.User
|
||||
@@ -100,7 +50,7 @@ func (c *HandleController) JudgeToken(user string, token string) plugin.Response
|
||||
res.Reject = true
|
||||
res.RejectReason = "user or meta token can not be empty"
|
||||
} else if info, exist := c.Tokens[user]; exist {
|
||||
if !info.Status {
|
||||
if !info.Enable {
|
||||
res.Reject = true
|
||||
res.RejectReason = fmt.Sprintf("user [%s] is disabled", user)
|
||||
} else {
|
||||
@@ -127,8 +77,7 @@ func (c *HandleController) JudgePort(content *plugin.NewProxyContent) plugin.Res
|
||||
"tcp", "tcpmux", "udp", "http", "https",
|
||||
}
|
||||
proxyType := content.ProxyType
|
||||
|
||||
if StringIndexOf(proxyType, supportProxyTypes) == -1 {
|
||||
if stringContains(proxyType, supportProxyTypes) {
|
||||
log.Printf("proxy type [%v] not support, plugin do nothing", proxyType)
|
||||
res.Unchange = true
|
||||
return res
|
||||
@@ -142,38 +91,47 @@ func (c *HandleController) JudgePort(content *plugin.NewProxyContent) plugin.Res
|
||||
portAllowed := true
|
||||
if proxyType == "tcp" || proxyType == "udp" {
|
||||
portAllowed = false
|
||||
if _, exist := c.Ports[user]; exist {
|
||||
for _, port := range c.Ports[user] {
|
||||
if strings.Contains(port, "-") {
|
||||
allowedRanges := strings.Split(port, "-")
|
||||
if len(allowedRanges) != 2 {
|
||||
portErr = fmt.Errorf("user [%v] port range [%v] format error", user, port)
|
||||
break
|
||||
}
|
||||
start, err := strconv.Atoi(strings.TrimSpace(allowedRanges[0]))
|
||||
if err != nil {
|
||||
portErr = fmt.Errorf("user [%v] port rang [%v] start port [%v] is not a number", user, port, allowedRanges[0])
|
||||
break
|
||||
}
|
||||
end, err := strconv.Atoi(strings.TrimSpace(allowedRanges[1]))
|
||||
if err != nil {
|
||||
portErr = fmt.Errorf("user [%v] port rang [%v] end port [%v] is not a number", user, port, allowedRanges[0])
|
||||
break
|
||||
}
|
||||
if max(userPort, start) == userPort && min(userPort, end) == userPort {
|
||||
portAllowed = true
|
||||
break
|
||||
if token, exist := c.Tokens[user]; exist {
|
||||
for _, port := range token.Ports {
|
||||
if str, ok := port.(string); ok {
|
||||
if strings.Contains(str, "-") {
|
||||
allowedRanges := strings.Split(str, "-")
|
||||
if len(allowedRanges) != 2 {
|
||||
portErr = fmt.Errorf("user [%v] port range [%v] format error", user, port)
|
||||
break
|
||||
}
|
||||
start, err := strconv.Atoi(trimString(allowedRanges[0]))
|
||||
if err != nil {
|
||||
portErr = fmt.Errorf("user [%v] port rang [%v] start port [%v] is not a number", user, port, allowedRanges[0])
|
||||
break
|
||||
}
|
||||
end, err := strconv.Atoi(trimString(allowedRanges[1]))
|
||||
if err != nil {
|
||||
portErr = fmt.Errorf("user [%v] port rang [%v] end port [%v] is not a number", user, port, allowedRanges[0])
|
||||
break
|
||||
}
|
||||
if max(userPort, start) == userPort && min(userPort, end) == userPort {
|
||||
portAllowed = true
|
||||
break
|
||||
}
|
||||
} else {
|
||||
allowed, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
portErr = fmt.Errorf("user [%v] allowed port [%v] is not a number", user, port)
|
||||
}
|
||||
if allowed == userPort {
|
||||
portAllowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
allowed, err := strconv.Atoi(port)
|
||||
if err != nil {
|
||||
portErr = fmt.Errorf("user [%v] allowed port [%v] is not a number", user, port)
|
||||
}
|
||||
allowed := port
|
||||
if allowed == userPort {
|
||||
portAllowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
portAllowed = true
|
||||
@@ -189,9 +147,9 @@ func (c *HandleController) JudgePort(content *plugin.NewProxyContent) plugin.Res
|
||||
domainAllowed := true
|
||||
if proxyType == "http" || proxyType == "https" || proxyType == "tcpmux" {
|
||||
if portAllowed {
|
||||
if _, exist := c.Domains[user]; exist {
|
||||
if token, exist := c.Tokens[user]; exist {
|
||||
for _, userDomain := range userDomains {
|
||||
if StringIndexOf(userDomain, c.Domains[user]) == -1 {
|
||||
if stringContains(userDomain, token.Domains) {
|
||||
domainAllowed = false
|
||||
break
|
||||
}
|
||||
@@ -208,8 +166,8 @@ func (c *HandleController) JudgePort(content *plugin.NewProxyContent) plugin.Res
|
||||
if proxyType == "http" || proxyType == "https" {
|
||||
subdomainAllowed = false
|
||||
if portAllowed && domainAllowed {
|
||||
if _, exist := c.Subdomains[user]; exist {
|
||||
for _, subdomain := range c.Subdomains[user] {
|
||||
if token, exist := c.Tokens[user]; exist {
|
||||
for _, subdomain := range token.Subdomains {
|
||||
if subdomain == userSubdomain {
|
||||
subdomainAllowed = true
|
||||
break
|
||||
@@ -233,12 +191,3 @@ func (c *HandleController) JudgePort(content *plugin.NewProxyContent) plugin.Res
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func StringIndexOf(element string, data []string) int {
|
||||
for k, v := range data {
|
||||
if element == v {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
54
pkg/server/controller/register.go
Normal file
54
pkg/server/controller/register.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type HandleController struct {
|
||||
CommonInfo CommonInfo
|
||||
Tokens map[string]TokenInfo
|
||||
Version string
|
||||
ConfigFile string
|
||||
TokensFile string
|
||||
}
|
||||
|
||||
func NewHandleController(config *HandleController) *HandleController {
|
||||
return config
|
||||
}
|
||||
|
||||
func (c *HandleController) Register(rootDir string, engine *gin.Engine) {
|
||||
assets := filepath.Join(rootDir, "assets")
|
||||
_, err := os.Stat(assets)
|
||||
if err != nil && !os.IsExist(err) {
|
||||
assets = "./assets"
|
||||
}
|
||||
|
||||
engine.Delims("${", "}")
|
||||
engine.LoadHTMLGlob(filepath.Join(assets, "templates/*"))
|
||||
engine.POST("/handler", c.MakeHandlerFunc())
|
||||
engine.Static("/static", filepath.Join(assets, "static"))
|
||||
engine.GET("/lang.json", c.MakeLangFunc())
|
||||
engine.GET(LoginUrl, c.MakeLoginFunc())
|
||||
engine.POST(LoginUrl, c.MakeLoginFunc())
|
||||
engine.GET(LogoutUrl, c.MakeLogoutFunc())
|
||||
|
||||
var group *gin.RouterGroup
|
||||
if len(c.CommonInfo.AdminUser) != 0 {
|
||||
//group = engine.Group("/", gin.BasicAuthForRealm(gin.Accounts{
|
||||
// c.CommonInfo.User: c.CommonInfo.Pwd,
|
||||
//}, "Restricted"))
|
||||
group = engine.Group("/", c.BasicAuth())
|
||||
} else {
|
||||
group = engine.Group("/")
|
||||
}
|
||||
group.GET("/", c.MakeIndexFunc())
|
||||
group.GET("/tokens", c.MakeQueryTokensFunc())
|
||||
group.POST("/add", c.MakeAddTokenFunc())
|
||||
group.POST("/update", c.MakeUpdateTokensFunc())
|
||||
group.POST("/remove", c.MakeRemoveTokensFunc())
|
||||
group.POST("/disable", c.MakeDisableTokensFunc())
|
||||
group.POST("/enable", c.MakeEnableTokensFunc())
|
||||
group.GET("/proxy/*serverApi", c.MakeProxyFunc())
|
||||
}
|
||||
222
pkg/server/controller/utils.go
Normal file
222
pkg/server/controller/utils.go
Normal file
@@ -0,0 +1,222 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/BurntSushi/toml"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func filter(main TokenInfo, sub TokenInfo) bool {
|
||||
replaceSpaceUser := trimAllSpace.ReplaceAllString(sub.User, "")
|
||||
if len(replaceSpaceUser) != 0 {
|
||||
if !strings.Contains(main.User, replaceSpaceUser) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
replaceSpaceToken := trimAllSpace.ReplaceAllString(sub.Token, "")
|
||||
if len(replaceSpaceToken) != 0 {
|
||||
if !strings.Contains(main.Token, replaceSpaceToken) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
replaceSpaceComment := trimAllSpace.ReplaceAllString(sub.Comment, "")
|
||||
if len(replaceSpaceComment) != 0 {
|
||||
if !strings.Contains(main.Comment, replaceSpaceComment) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func trimString(str string) string {
|
||||
return strings.TrimSpace(str)
|
||||
}
|
||||
|
||||
func (c *HandleController) verifyToken(token TokenInfo, operate int) OperationResponse {
|
||||
response := OperationResponse{
|
||||
Success: true,
|
||||
Code: Success,
|
||||
Message: "operate success",
|
||||
}
|
||||
|
||||
var (
|
||||
validateExist = false
|
||||
validateNotExist = false
|
||||
validateUser = false
|
||||
validateToken = false
|
||||
validateComment = false
|
||||
validatePorts = false
|
||||
validateDomains = false
|
||||
validateSubdomains = false
|
||||
)
|
||||
|
||||
if operate == TOKEN_ADD {
|
||||
validateExist = true
|
||||
validateUser = true
|
||||
validateToken = true
|
||||
validateComment = true
|
||||
validatePorts = true
|
||||
validateDomains = true
|
||||
validateSubdomains = true
|
||||
} else if operate == TOKEN_UPDATE {
|
||||
validateNotExist = true
|
||||
validateUser = true
|
||||
validateToken = true
|
||||
validateComment = true
|
||||
validatePorts = true
|
||||
validateDomains = true
|
||||
validateSubdomains = true
|
||||
} else if operate == TOKEN_ENABLE || operate == TOKEN_DISABLE || operate == TOKEN_REMOVE {
|
||||
validateNotExist = true
|
||||
}
|
||||
|
||||
if validateUser && !userFormat.MatchString(token.User) {
|
||||
response.Success = false
|
||||
response.Code = UserFormatError
|
||||
response.Message = fmt.Sprintf("operate failed, user [%s] format error", token.User)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
|
||||
if validateExist {
|
||||
if _, exist := c.Tokens[token.User]; exist {
|
||||
response.Success = false
|
||||
response.Code = UserExist
|
||||
response.Message = fmt.Sprintf("operate failed, user [%s] exist ", token.User)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
if validateNotExist {
|
||||
if _, exist := c.Tokens[token.User]; !exist {
|
||||
response.Success = false
|
||||
response.Code = UserNotExist
|
||||
response.Message = fmt.Sprintf("operate failed, user [%s] not exist ", token.User)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
if validateToken && !tokenFormat.MatchString(token.Token) {
|
||||
response.Success = false
|
||||
response.Code = TokenFormatError
|
||||
response.Message = fmt.Sprintf("operate failed, token [%s] format error", token.Token)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
|
||||
trimmedComment := trimString(token.Comment)
|
||||
if validateComment && trimmedComment != "" && commentFormat.MatchString(trimmedComment) {
|
||||
response.Success = false
|
||||
response.Code = CommentFormatError
|
||||
response.Message = fmt.Sprintf("operate failed, comment [%s] format error", token.Comment)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
|
||||
if validatePorts {
|
||||
for _, port := range token.Ports {
|
||||
if str, ok := port.(string); ok {
|
||||
trimmedPort := trimString(str)
|
||||
if trimmedPort != "" && !portsFormatSingle.MatchString(trimmedPort) && !portsFormatRange.MatchString(trimmedPort) {
|
||||
response.Success = false
|
||||
response.Code = PortsFormatError
|
||||
response.Message = fmt.Sprintf("operate failed, ports [%v] format error", token.Ports)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if validateDomains {
|
||||
for _, domain := range token.Domains {
|
||||
trimmedDomain := trimString(domain)
|
||||
if trimmedDomain != "" && !domainFormat.MatchString(trimmedDomain) {
|
||||
response.Success = false
|
||||
response.Code = DomainsFormatError
|
||||
response.Message = fmt.Sprintf("operate failed, domains [%v] format error", token.Domains)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if validateSubdomains {
|
||||
for _, subdomain := range token.Subdomains {
|
||||
trimmedSubdomain := trimString(subdomain)
|
||||
if trimmedSubdomain != "" && !subdomainFormat.MatchString(trimmedSubdomain) {
|
||||
response.Success = false
|
||||
response.Code = SubdomainsFormatError
|
||||
response.Message = fmt.Sprintf("operate failed, subdomains [%v] format error", token.Subdomains)
|
||||
log.Printf(response.Message)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func cleanPorts(ports []any) []any {
|
||||
cleanedPorts := make([]any, len(ports))
|
||||
for i, port := range ports {
|
||||
if str, ok := port.(string); ok {
|
||||
cleanedPorts[i] = cleanString(str)
|
||||
} else {
|
||||
//float64, for JSON numbers
|
||||
cleanedPorts[i] = int(port.(float64))
|
||||
}
|
||||
}
|
||||
return cleanedPorts
|
||||
}
|
||||
|
||||
func cleanStrings(originalStrings []string) []string {
|
||||
cleanedStrings := make([]string, len(originalStrings))
|
||||
for i, str := range originalStrings {
|
||||
cleanedStrings[i] = cleanString(str)
|
||||
}
|
||||
return cleanedStrings
|
||||
}
|
||||
|
||||
func cleanString(originalString string) string {
|
||||
return trimString(originalString)
|
||||
}
|
||||
|
||||
func stringContains(element string, data []string) bool {
|
||||
for _, v := range data {
|
||||
if element == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func tokensList(tokens map[string]TokenInfo) Tokens {
|
||||
return Tokens{
|
||||
tokens,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HandleController) saveToken() error {
|
||||
tokenFile, err := os.Create(c.TokensFile)
|
||||
if err != nil {
|
||||
log.Printf("error to crate file %v: %v", c.TokensFile, err)
|
||||
}
|
||||
|
||||
encoder := toml.NewEncoder(tokenFile)
|
||||
encoder.Indent = " "
|
||||
if err = encoder.Encode(tokensList(c.Tokens)); err != nil {
|
||||
log.Printf("error to encode tokens: %v", err)
|
||||
}
|
||||
if err = tokenFile.Close(); err != nil {
|
||||
log.Printf("error to close file %v: %v", c.TokensFile, err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
136
pkg/server/controller/variables.go
Normal file
136
pkg/server/controller/variables.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const (
|
||||
Success int = iota
|
||||
ParamError
|
||||
UserExist
|
||||
UserNotExist
|
||||
SaveError
|
||||
UserFormatError
|
||||
TokenFormatError
|
||||
CommentFormatError
|
||||
PortsFormatError
|
||||
DomainsFormatError
|
||||
SubdomainsFormatError
|
||||
FrpServerError
|
||||
)
|
||||
|
||||
const (
|
||||
TOKEN_ADD int = iota
|
||||
TOKEN_UPDATE
|
||||
TOKEN_REMOVE
|
||||
TOKEN_ENABLE
|
||||
TOKEN_DISABLE
|
||||
)
|
||||
|
||||
const (
|
||||
SessionName = "GOSESSION"
|
||||
AuthName = "_PANEL_AUTH"
|
||||
LoginUrl = "/login"
|
||||
LoginSuccessUrl = "/"
|
||||
LogoutUrl = "/logout"
|
||||
LogoutSuccessUrl = "/login"
|
||||
)
|
||||
|
||||
var (
|
||||
userFormat = regexp.MustCompile("^\\w+$")
|
||||
tokenFormat = regexp.MustCompile("^[\\w!@#$%^&*()]+$")
|
||||
commentFormat = regexp.MustCompile("[\\n\\t\\r]")
|
||||
portsFormatSingle = regexp.MustCompile("^\\s*\\d{1,5}\\s*$")
|
||||
portsFormatRange = regexp.MustCompile("^\\s*\\d{1,5}\\s*-\\s*\\d{1,5}\\s*$")
|
||||
domainFormat = regexp.MustCompile("^([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*\\.)+[a-zA-Z]{2,}$")
|
||||
subdomainFormat = regexp.MustCompile("^[a-zA-z0-9-]{1,20}$")
|
||||
trimAllSpace = regexp.MustCompile("[\\n\\t\\r\\s]")
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
type HTTPError struct {
|
||||
Code int
|
||||
Err error
|
||||
}
|
||||
|
||||
type Common struct {
|
||||
Common CommonInfo
|
||||
}
|
||||
|
||||
type CommonInfo struct {
|
||||
PluginAddr string `toml:"plugin_addr"`
|
||||
PluginPort int `toml:"plugin_port"`
|
||||
AdminUser string `toml:"admin_user"`
|
||||
AdminPwd string `toml:"admin_pwd"`
|
||||
AdminKeepTime int `toml:"admin_keep_time"`
|
||||
TlsMode bool `toml:"tls_mode"`
|
||||
TlsCertFile string `toml:"tls_cert_file"`
|
||||
TlsKeyFile string `toml:"tls_key_file"`
|
||||
DashboardAddr string `toml:"dashboard_addr"`
|
||||
DashboardPort int `toml:"dashboard_port"`
|
||||
DashboardUser string `toml:"dashboard_user"`
|
||||
DashboardPwd string `toml:"dashboard_pwd"`
|
||||
DashboardTls bool
|
||||
}
|
||||
|
||||
type Tokens struct {
|
||||
Tokens map[string]TokenInfo `toml:"tokens"`
|
||||
}
|
||||
|
||||
type TokenInfo struct {
|
||||
User string `toml:"user" json:"user" form:"user"`
|
||||
Token string `toml:"token" json:"token" form:"token"`
|
||||
Comment string `toml:"comment" json:"comment" form:"comment"`
|
||||
Ports []any `toml:"ports" json:"ports" from:"ports"`
|
||||
Domains []string `toml:"domains" json:"domains" from:"domains"`
|
||||
Subdomains []string `toml:"subdomains" json:"subdomains" from:"subdomains"`
|
||||
Enable bool `toml:"enable" json:"enable" form:"enable"`
|
||||
}
|
||||
|
||||
type TokenResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Count int `json:"count"`
|
||||
Data []TokenInfo `json:"data"`
|
||||
}
|
||||
|
||||
type OperationResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type ProxyResponse struct {
|
||||
OperationResponse
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
type TokenSearch struct {
|
||||
TokenInfo
|
||||
Page int `form:"page"`
|
||||
Limit int `form:"limit"`
|
||||
}
|
||||
|
||||
type TokenUpdate struct {
|
||||
Before TokenInfo `json:"before"`
|
||||
After TokenInfo `json:"after"`
|
||||
}
|
||||
|
||||
type TokenRemove struct {
|
||||
Users []TokenInfo `json:"users"`
|
||||
}
|
||||
|
||||
type TokenDisable struct {
|
||||
TokenRemove
|
||||
}
|
||||
|
||||
type TokenEnable struct {
|
||||
TokenDisable
|
||||
}
|
||||
|
||||
func (e *HTTPError) Error() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"fmt"
|
||||
"frps-panel/pkg/server/controller"
|
||||
ginI18n "github.com/gin-contrib/i18n"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/cookie"
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/text/language"
|
||||
"log"
|
||||
@@ -171,6 +173,15 @@ func GinI18nLocalize(rootDir string) gin.HandlerFunc {
|
||||
func (s *Server) initHTTPServer() error {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
engine := gin.New()
|
||||
authStore := cookie.NewStore([]byte("frps-panel"))
|
||||
authStore.Options(sessions.Options{
|
||||
Secure: true,
|
||||
HttpOnly: false,
|
||||
SameSite: 4,
|
||||
Path: "/",
|
||||
MaxAge: s.cfg.CommonInfo.AdminKeepTime,
|
||||
})
|
||||
engine.Use(sessions.Sessions(controller.SessionName, authStore))
|
||||
engine.Use(GinI18nLocalize(s.rootDir))
|
||||
s.s = &http.Server{
|
||||
Handler: engine,
|
||||
|
||||
BIN
screenshots/login.png
Normal file
BIN
screenshots/login.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
Reference in New Issue
Block a user