1
0
mirror of https://github.com/donaldzou/WGDashboard.git synced 2024-11-22 15:20:09 +01:00

Merge pull request #46 from donaldzou/v2.2-beta

V2.2 pull request
This commit is contained in:
Donald Zou 2021-08-14 23:57:07 -04:00 committed by GitHub
commit ff304027cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 8760 additions and 663 deletions

2
.gitignore vendored
View File

@ -10,4 +10,6 @@ __pycache__
src/wg-dashboard.ini
src/static/pic.xd
*.conf
private_key.txt
public_key.txt

402
README.md
View File

@ -4,7 +4,7 @@
<p align="center">
<img src="https://raw.githubusercontent.com/donaldzou/wireguard-dashboard/main/img/Group%202.png" width="128">
<img src="img/logo.png" width="128">
</p>
<h1 align="center"> Wireguard Dashboard</h1>
@ -17,167 +17,392 @@
<p align="center">Monitoring WireGuard is not convinient, need to login into server and type <code>wg show</code>. That's why this platform is being created, to view all configurations and manage them in a easier way.</p>
## 📣 What's New: Version 2.1
## 📣 What's New: Version v2.2
- Added **Ping** and **Traceroute** tools!
- Adjusted the calculation of data usage on each peers
- Added refresh interval of the dashboard
- Bug fixed when no configuration on fresh install ([Bug report](https://github.com/donaldzou/wireguard-dashboard/issues/23#issuecomment-869189672))
- Fixed crash when too many peers ([Bug report](https://github.com/donaldzou/wireguard-dashboard/issues/22#issuecomment-868840564))
- 🎉 **New Features**
- **Add new peers**: Now you can add peers directly on dashboard, it will generate a pair of private key and public key. You can also set its DNS, endpoint allowed IPs. Both can set a default value in the setting page. [❤️ in [#44](https://github.com/donaldzou/wireguard-dashboard/issues/44)]
- **QR Code:** You can add the private key in peer setting of your existed peer to create a QR code. Or just create a new one, dashboard will now be able to auto generate a private key and public key ;) Don't worry, all keys will be generated on your machine, and **will delete all key files after they got generated**. [❤️ in [#29](https://github.com/donaldzou/wireguard-dashboard/issues/29)]
- **Peer configuration file download:** Same as QR code, you now can download the peer configuration file, so you don't need to manually input all the details on the peer machine! [❤️ in [#40](https://github.com/donaldzou/wireguard-dashboard/issues/40)]
- **Search peers**: You can now search peers by their name.
- **Autostart on boot:** Added a tutorial on how to start the dashboard to on boot! Please read the [tutorial below](#autostart-wireguard-dashboard-on-boot). [❤️ in [#29](https://github.com/donaldzou/wireguard-dashboard/issues/29)]
- **Click to copy**: You can now click and copy all peer's public key and configuration's public key.
- ....
- 🪚 **Bug Fixed**
- When there are comments in the wireguard config file, will cause the dashboard to crash.
- Used regex to search for config files.
- **🧐 Other Changes**
- Moved all external CSS and JavaScript file to local hosting (Except Bootstrap Icon, due to large amount of SVG files).
- Updated Python dependencies
- Flask: `v1.1.2 => v2.0.1`
- Jinja: `v2.10.1 => v3.0.1`
- icmplib: `v2.1.1 => v3.0.1`
- Updated CSS/JS dependencies
- Bootstrap: `v4.5.3 => v4.6.0`
- UI adjustment
- Adjusted how peers will display in larger screens, used to be 1 row per peer, now is 3 peers in 1 row.
<hr>
## Table of Content
- [💡Features](https://github.com/donaldzou/wireguard-dashboard#-features)
- [📝 Requirement](https://github.com/donaldzou/wireguard-dashboard#-requirement)
- [🛠 Install](https://github.com/donaldzou/wireguard-dashboard#-install)
- [🪜 Usage](https://github.com/donaldzou/wireguard-dashboard#-usage)
- [✂️ Dashboard Configuration](https://github.com/donaldzou/wireguard-dashboard#%EF%B8%8F-dashboard-configuration)
- [❓How to update the dashboard?](https://github.com/donaldzou/wireguard-dashboard#-how-to-update-the-dashboard)
- [⚠️ Update from v1.x.x](https://github.com/donaldzou/wireguard-dashboard#%EF%B8%8F--update-from-v1xx)
- [🔍 Screenshot](https://github.com/donaldzou/wireguard-dashboard#-screenshot)
- [💡 Features](#-features)
- [📝 Requirement](#-requirement)
- [🛠 Install](#-install)
- [🪜 Usage](#-usage)
- [Start/Stop/Restart Wireguard Dashboard](#startstoprestart-wireguard-dashboard)
- [Autostart Wireguard Dashboard on boot](#autostart-wireguard-dashboard-on-boot)
- [✂️ Dashboard Configuration](#%EF%B8%8F-dashboard-configuration)
- [Dashboard Configuration file](#dashboard-configuration-file)
- [Generating QR code and peer configuration file (.conf)](#generating-qr-code-and-peer-configuration-file-conf)
- [❓ How to update the dashboard?](#-how-to-update-the-dashboard)
- [🔍 Screenshot](#-screenshot)
- [⏰ Changelog](#--changelog)
- [🛒 Dependencies](#-dependencies)
- [✨ Contributors](#-contributors)
## 💡 Features
- Add peers for each WireGuard configuration
- Manage peer
- Delete peers
- And many more coming up! Welcome to contribute to this project!
- Easy to use interface, provided username and password protection to the dashboard
- Add peers and edit (Allowed IPs, DNS, Private Key...)
- View peers and configuration real time details (Data Usage, Latest Handshakes...)
- Share your peer configuration with QR code or file download
- Testing tool: Ping and Traceroute to your peer's ip
- **And more functions are coming up!**
## 📝 Requirement
- Ubuntu or Debian based OS, other might work, but haven't test yet. Tested on the following OS:
- [x] Ubuntu 18.04.1 LTS
- [ ] If you have tested on other OS and it works perfectly please provide it to me in [#31](https://github.com/donaldzou/wireguard-dashboard/issues/31). Thank you!
- Recommend the following OS, tested by our beloved users:
- [x] Ubuntu 18.04.1 LTS - 20.04.1 LTS [@Me]
- [x] Debian GNU/Linux 10 (buster) [❤️ @[robchez](https://github.com/robchez)]
- [x] AlmaLinux 8.4 (Electric Cheetah) [❤️ @[barry-smithjr](https://github.com/)]
- [x] CentOS 7 [❤️ @[PrzemekSkw](https://github.com/PrzemekSkw)]
- ‼️ Make sure you have **Wireguard** and **Wireguard-Tools (`wg-quick`)** installed.‼️ <a href="https://www.wireguard.com/install/">How to install?</a>
- Configuration files under **/etc/wireguard**
> **If you have tested on other OS and it works perfectly please provide it to me in [#31](https://github.com/donaldzou/wireguard-dashboard/issues/31). Thank you!**
- **WireGuard** and **Wireguard-Tools (`wg-quick`)** are installed.
> Don't know how? Check this <a href="https://www.wireguard.com/install/">official documentation</a>
- Configuration files under **`/etc/wireguard`**, but please note the following sample
```ini
[Interface]
...
SaveConfig = true
# Need to include this line to allow WireGuard Tool to save your configuration
[Peer]
PublicKey = abcd1234
AllowedIPs = 1.2.3.4/32
# Must have for each peer
```
- **Note**:
- **For `[Interface]` in the `.conf` file, please make sure you have `SaveConfig = true` under `[Interface]`** (Bug mentioned in [#9](https://github.com/donaldzou/wireguard-dashboard/issues/9#issuecomment-852346481))
- **For peers, `PublicKey` & `AllowedIPs` is required.**
- Python 3.7+ & Pip3
## 🛠 Install
1. **Download Wireguard Dashboard**
```shell
$ git clone -b v2.1 https://github.com/donaldzou/Wireguard-Dashboard.git
2. **Install Python Dependencies**
git clone -b v2.2 https://github.com/donaldzou/wireguard-dashboard.git
2. Open the Wireguard Dashboard folder
```shell
$ cd Wireguard-Dashboard/src
$ python3 -m pip install -r requirements.txt
cd wireguard-dashboard/src
```
3. **Install & run Wireguard Dashboard**
3. Install Python Dependencies
```shell
$ sudo chmod -R 744 /etc/wireguard # Add read and execute permission of the wireguard config folder
$ sudo chmod u+x wgd.sh
$ ./wgd.sh start
python3 -m pip install -r requirements.txt
```
4. Give read, write and execute permission to root of the WireGuard configuration folder, you can change the path if your configuration files is not stored in `/etc/wireguard`
```shell
sudo chmod -R 744 /etc/wireguard
```
5. Install & run Wireguard Dashboard
```shell
sudo chmod u+x wgd.sh
./wgd.sh start
```
**Note**:
> For [`pivpn`](https://github.com/pivpn/pivpn) user, please use `sudo ./wgd.sh start` to run if your current account does not have the permission to run `wg show` and `wg-quick`.
4. **Access dashboard**
6. **Access dashboard**
Access your server with port `10086` ! e.g (http://your_server_ip:10086), continue to read to on how to change port and ip that dashboard is running with.
## 🪜 Usage
**1. Start/Stop/Restart Wireguard Dashboard**
#### Start/Stop/Restart Wireguard Dashboard
```shell
$ cd Wireguard-Dashboard/src
cd Wireguard-Dashboard/src
-----------------------------
$ ./wgd.sh start # Start the dashboard in background
./wgd.sh start # Start the dashboard in background
-----------------------------
$ ./wgd.sh debug # Start the dashboard in foreground (debug mode)
./wgd.sh debug # Start the dashboard in foreground (debug mode)
-----------------------------
$ ./wgd.sh stop # Stop the dashboard
./wgd.sh stop # Stop the dashboard
-----------------------------
$ ./wgd.sh restart # Restart the dasboard
./wgd.sh restart # Restart the dasboard
```
⚠️ **For first time user please also read the next section.**
#### Autostart Wireguard Dashboard on boot (>= v2.2)
In the `src` folder, it contained a file called `wg-dashboard.service`, we can use this file to let our system to autostart the dashboard after reboot. The following guide has tested on **Ubuntu**, most **Debian** based OS might be the same, but some might not. Please don't hesitate to provide your system if you have tested the autostart on another system.
1. Changing the directory to the dashboard's directory
```shell
cd wireguard-dashboard/src
```
2. Get the full path of the dashboard's directory
```shell
pwd
#Output: /root/wireguard-dashboard/src
```
For this example, the output is `/root/wireguard-dashboard/src`, your path might be different since it depends on where you downloaded the dashboard in the first place. **Copy the the output to somewhere, we will need this in the next step.**
3. Edit the service file, the service file is located in `wireguard-dashboard/src`, you can use other editor you like, here will be using `nano`
```shell
nano wg-dashboard.service
```
You will see something like this:
```ini
[Unit]
After=netword.service
[Service]
WorkingDirectory=<your dashboard directory full path here>
ExecStart=/usr/bin/python3 <your dashboard directory full path here>/dashboard.py
Restart=always
[Install]
WantedBy=default.target
```
Now, we need to replace both `<your dashboard directory full path here>` to the one you just copied from step 2. After doing this, the file will become something like this, your file might be different:
```ini
[Unit]
After=netword.service
[Service]
WorkingDirectory=/root/wireguard-dashboard/src
ExecStart=/usr/bin/python3 /root/wireguard-dashboard/src/dashboard.py
Restart=always
[Install]
WantedBy=default.target
```
**Be aware that after the value of `WorkingDirectory`, it does not have a `/` (slash).** And then save the file after you edited it
4. Copy the service file to systemd folder
```bash
$ cp wg-dashboard.service /etc/systemd/system/wg-dashboard.service
```
To make sure you copy the file successfully, you can use this command `cat /etc/systemd/system/wg-dashboard.service` to see if it will output the file you just edited.
5. Enable the service
```bash
$ sudo chmod 664 /etc/systemd/system/wg-dashboard.service
$ sudo systemctl daemon-reload
$ sudo systemctl enable wg-dashboard.service
$ sudo systemctl start wg-dashboard.service # <-- To start the service
```
6. Check if the service run correctly
```bash
$ sudo systemctl status wg-dashboard.service
```
And you should see something like this
```shell
● wg-dashboard.service
Loaded: loaded (/etc/systemd/system/wg-dashboard.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2021-08-03 22:31:26 UTC; 4s ago
Main PID: 6602 (python3)
Tasks: 1 (limit: 453)
Memory: 26.1M
CGroup: /system.slice/wg-dashboard.service
└─6602 /usr/bin/python3 /root/wireguard-dashboard/src/dashboard.py
Aug 03 22:31:26 ubuntu-wg systemd[1]: Started wg-dashboard.service.
Aug 03 22:31:27 ubuntu-wg python3[6602]: * Serving Flask app "Wireguard Dashboard" (lazy loading)
Aug 03 22:31:27 ubuntu-wg python3[6602]: * Environment: production
Aug 03 22:31:27 ubuntu-wg python3[6602]: WARNING: This is a development server. Do not use it in a production deployment.
Aug 03 22:31:27 ubuntu-wg python3[6602]: Use a production WSGI server instead.
Aug 03 22:31:27 ubuntu-wg python3[6602]: * Debug mode: off
Aug 03 22:31:27 ubuntu-wg python3[6602]: * Running on all addresses.
Aug 03 22:31:27 ubuntu-wg python3[6602]: WARNING: This is a development server. Do not use it in a production deployment.
Aug 03 22:31:27 ubuntu-wg python3[6602]: * Running on http://0.0.0.0:10086/ (Press CTRL+C to quit)
```
If you see `Active:` followed by `active (running) since...` then it means it run correctly.
7. Stop/Start/Restart the service
```bash
sudo systemctl stop wg-dashboard.service # <-- To stop the service
sudo systemctl start wg-dashboard.service # <-- To start the service
sudo systemctl restart wg-dashboard.service # <-- To restart the service
```
8. **And now you can reboot your system, and use the command at step 6 to see if it will auto start after the reboot, or just simply access the dashboard through your browser. If you have any questions or problem, please report it in the issue page.**
## ✂️ Dashboard Configuration
#### Dashboard Configuration file
Since version 2.0, Wireguard Dashboard will be using a configuration file called `wg-dashboard.ini`, (It will generate automatically after first time running the dashboard). More options will include in future versions, and for now it included the following config:
| | Description | Default Value |
| --------------- | ------------------------------------------------------------ | ------------------------ |
| **`[Account]`** | | |
| `username` | Dashboard login username | `admin` |
| `password` | Password, will be hash with SHA256 | `admin` hashed in SHA256 |
| **`[Server]`** | | |
| `wg_conf_path` | The path of all the Wireguard configurations | `/etc/wireguard` |
| `app_ip` | IP address the dashboard will run with | `0.0.0.0` |
| `app_port` | Port the the dashboard will run with | `10086` |
| `auth_req` | Does the dashboard need authentication to access | `true` |
| | If `auth_req = false` , user will not be access the **Setting** tab due to security consideration. **User can only change the file directly in system**. | |
| `version` | Dashboard Version | N/A |
| | Description | Default | Available in Setting |
| --------------- | ------------------------------------------------------------ | ------------------------ | -------------------- |
| **`[Account]`** | | | |
| `username` | Dashboard login username | `admin` | Yes |
| `password` | Password, will be hash with SHA256 | `admin` hashed in SHA256 | Yes |
| **`[Server]`** | | | |
| `wg_conf_path` | The path of all the Wireguard configurations | `/etc/wireguard` | Yes |
| `app_ip` | IP address the dashboard will run with | `0.0.0.0` | Yes |
| `app_port` | Port the the dashboard will run with | `10086` | Yes |
| `auth_req` | Does the dashboard need authentication to access | `true` | No |
| | If `auth_req = false` , user will not be access the **Setting** tab due to security consideration. **User can only edit the file directly in system**. | | |
| `version` | Dashboard Version | `v2.2` | No |
<p align=center>Latest Version: V2.1</p>
<p align=center>Latest Version: v2.2</p>
All these settings will be able to configure within the dashboard in **Settings** on the sidebar, without changing the actual file. **Except `version` and `auth_req` due to security consideration.**
**Except `auth_req` due to security consideration.**
#### Generating QR code and peer configuration file (.conf)
Starting version 2.2, dashboard can now generate QR code and configuration file for each peer. Here is a template of what each QR code encoded with and the same content will be inside the file:
```ini
[Interface]
PrivateKey = QWERTYUIOPO234567890YUSDAKFH10E1B12JE129U21=
Address = 0.0.0.0/32
DNS = 1.1.1.1
[Peer]
PublicKey = QWERTYUIOPO234567890YUSDAKFH10E1B12JE129U21=
AllowedIPs = 0.0.0.0/0
Endpoint = 0.0.0.0:51820
```
| | Description | Default Value | Available in Peer setting |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------- |
| **`[Interface]`** | | | |
| `PrivateKey` | The private key of this peer | Private key generated by WireGuard (`wg genkey`) or provided by user | Yes |
| `Address` | The `allowed_ips` of your peer | N/A | Yes |
| `DNS` | The DNS server your peer will use | `1.1.1.1` - Cloud flare DNS, you can change it when you adding the peer or in the peer setting. | Yes |
| **`[Peer]`** | | | |
| `PublicKey` | The public key of your server | N/A | No |
| `AllowedIPs` | IP ranges for which a peer will route traffic | `0.0.0.0/0` - Indicated a default route to send all internet and VPN traffic through that peer. | No |
| `Endpoint` | Your wireguard server ip and port, the dashboard will search for your server's default interface's ip. | `<your server default interface ip>:<listen port>` | No |
## ❓ How to update the dashboard?
1. Change your directory to `wireguard-dashboard`
```
$ cd wireguard-dashboard
```shell
cd wireguard-dashboard
```
2. Get the newest version
```
$ sudo git pull https://github.com/donaldzou/wireguard-dashboard.git v2.1 --force
```shell
sudo git pull https://github.com/donaldzou/wireguard-dashboard.git v2.2 --force
```
3. Update and install all python dependencies
```
$ python3 -m pip install -r requirements.txt
```shell
python3 -m pip install -r requirements.txt
```
4. Start the dashboard
```shell
./wgd.sh start
```
$ ./wgd.sh start
```
### ⚠️ **Update from v1.x.x**
1. Stop the dashboard if it is running.
2. You can use `git pull https://github.com/donaldzou/Wireguard-Dashboard.git v2.1` to get the new update inside `Wireguard-Dashboard` directory.
3. Proceed **Step 2 & 3** in the [Install](#-install) step down below.
## 🔍 Screenshot
![Index Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/index.png)
![Sign In Page](img/SignIn.png)
<p align=center>Sign In</p>
<p align=center>Index Page</p>
![Index Image](img/HomePage.png)
<p align=center>Home</p>
![Signin Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/signin.png)
![Configuration](img/Configuration.png)
<p align=center>Configuration</p>
<p align=center>Signin Page</p>
![Add Peer](img/AddPeer.png)
<p align=center>Add Peer</p>
![Configuration Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/configuration.png)
![Edit Peer](img/EditPeer.png)
<p align=center>Edit Peer</p>
<p align=center>Configuration Page</p>
![Delete Peer](img/DeletePeer.png)
<p align=center>Delete Peer</p>
![Settings Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/settings.png)
![Dashboard Setting](img/DashboardSetting.png)
<p align=center>Dashboard Setting</p>
<p align=center>Settings Page</p>
![Ping](img/Ping.png)
<p align=center>Ping</p>
![Traceroute](img/Traceroute.png)
<p align=center>Traceroute</p>
## ⏰ Changelog
#### v2.1 - Jul 2, 2021
- Added **Ping** and **Traceroute** tools!
- Adjusted the calculation of data usage on each peers
- Added refresh interval of the dashboard
- Bug fixed when no configuration on fresh install ([#23](https://github.com/donaldzou/wireguard-dashboard/issues/23))
- Fixed crash when too many peers ([#22](https://github.com/donaldzou/wireguard-dashboard/issues/22))
#### v2.0 - May 5, 2021
- Added login function to dashboard
- ***I'm not using the most ideal way to store the username and password, feel free to provide a better way to do this if you any good idea!***
- Added a config file to the dashboard
- Dashboard config can be change within the **Setting** tab on the side bar
- Adjusted UI
- And much more!
#### v1.1.2 - Apr 3, 2021
- Resolved issue [#3](https://github.com/donaldzou/wireguard-dashboard/issues/3).
#### v1.1.1 - Apr 2, 2021
- Able to add a friendly name to each peer. Thanks [#2](https://github.com/donaldzou/wireguard-dashboard/issues/2) !
#### v1.0 - Dec 27, 2020
- Added the function to remove peers
## 🛒 Dependencies
- CSS/JS
@ -185,14 +410,13 @@ All these settings will be able to configure within the dashboard in **Settings*
- [Bootstrap Icon](https://icons.getbootstrap.com) `v1.4.0`
- [jQuery](https://jquery.com) `v3.5.1`
- Python
- [Flask](https://pypi.org/project/Flask/) `v1.1.2`
- [Flask](https://pypi.org/project/Flask/) `v2.0.1`
- [TinyDB](https://pypi.org/project/tinydb/) `v4.3.0`
- [ifcfg](https://pypi.org/project/ifcfg/) `v0.21`
- [icmplib](https://pypi.org/project/icmplib/) `v2.1.1`
- [flask-qrcode](https://pypi.org/project/Flask-QRcode/) `v3.0.0`
## Contributors ✨
## ✨ Contributors
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors-)

BIN
img/AddPeer.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 221 KiB

BIN
img/Configuration.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

BIN
img/DashboardSetting.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

BIN
img/DeletePeer.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

BIN
img/EditPeer.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

BIN
img/HomePage.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

BIN
img/Ping.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

BIN
img/QRCode.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

BIN
img/SignIn.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

BIN
img/Traceroute.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 198 KiB

View File

Before

Width:  |  Height:  |  Size: 180 KiB

After

Width:  |  Height:  |  Size: 180 KiB

View File

@ -13,19 +13,24 @@ import configparser
import re
# PIP installed library
import ifcfg
from flask_qrcode import QRcode
from tinydb import TinyDB, Query
from icmplib import ping, multiping, traceroute, resolve, Host, Hop
# Dashboard Version
dashboard_version = 'v2.1'
dashboard_version = 'v2.2'
# Dashboard Config Name
dashboard_conf = 'wg-dashboard.ini'
# Default Wireguard IP
wg_ip = ifcfg.default_interface()['inet']
# Upgrade Required
update = ""
# Flask App Configuration
app = Flask("Wireguard Dashboard")
app.secret_key = secrets.token_urlsafe(16)
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Enable QR Code Generator
QRcode(app)
def get_conf_peer_key(config_name):
@ -34,7 +39,8 @@ def get_conf_peer_key(config_name):
peer_key = peer_key.decode("UTF-8").split()
return peer_key
except Exception:
return config_name+" is not running."
return config_name + " is not running."
def get_conf_running_peer_number(config_name):
running = 0
@ -59,6 +65,24 @@ def is_match(regex, text):
pattern = re.compile(regex)
return pattern.search(text) is not None
def read_conf_file_interface(config_name):
conf_location = wg_conf_path + "/" + config_name + ".conf"
f = open(conf_location, 'r')
file = f.read().split("\n")
data = {}
peers_start = 0
for i in range(len(file)):
if not is_match("#(.*)", file[i]):
if len(file[i]) > 0:
if file[i] != "[Interface]":
tmp = re.split(r'\s*=\s*', file[i], 1)
if len(tmp) == 2:
data[tmp[0]] = tmp[1]
f.close()
return data
def read_conf_file(config_name):
# Read Configuration File Start
conf_location = wg_conf_path + "/" + config_name + ".conf"
@ -70,7 +94,7 @@ def read_conf_file(config_name):
}
peers_start = 0
for i in range(len(file)):
if not is_match("^#(.*)",file[i]):
if not is_match("#(.*)", file[i]):
if file[i] == "[Peer]":
peers_start = i
break
@ -121,6 +145,7 @@ def get_latest_handshake(config_name, db, peers):
db.update({"latest_handshake": "(None)", "status": status}, peers.id == data_usage[count])
count += 2
def get_transfer(config_name, db, peers):
# Get transfer
try:
@ -155,6 +180,7 @@ def get_transfer(config_name, db, peers):
count += 3
def get_endpoint(config_name, db, peers):
# Get endpoint
try:
@ -167,22 +193,26 @@ def get_endpoint(config_name, db, peers):
db.update({"endpoint": data_usage[count + 1]}, peers.id == data_usage[count])
count += 2
def get_allowed_ip(config_name, db, peers, conf_peer_data):
# Get allowed ip
for i in conf_peer_data["Peers"]:
db.update({"allowed_ip": i.get('AllowedIPs', '(None)')}, peers.id == i["PublicKey"])
def get_conf_peers_data(config_name):
def get_all_peers_data(config_name):
db = TinyDB('db/' + config_name + '.json')
peers = Query()
conf_peer_data = read_conf_file(config_name)
for i in conf_peer_data['Peers']:
if not db.search(peers.id == i['PublicKey']):
search = db.search(peers.id == i['PublicKey'])
if not search:
db.insert({
"id": i['PublicKey'],
"private_key": "",
"DNS": "1.1.1.1",
"endpoint_allowed_ip": "0.0.0.0/0",
"name": "",
"total_receive": 0,
"total_sent": 0,
@ -193,6 +223,16 @@ def get_conf_peers_data(config_name):
"allowed_ip": 0,
"traffic": []
})
else:
# Update database since V2.2
update_db = {}
if "private_key" not in search[0]:
update_db['private_key'] = ''
if "DNS" not in search[0]:
update_db['DNS'] = '1.1.1.1'
if "endpoint_allowed_ip" not in search[0]:
update_db['endpoint_allowed_ip'] = '0.0.0.0/0'
db.update(update_db, peers.id == i['PublicKey'])
tic = time.perf_counter()
get_latest_handshake(config_name, db, peers)
@ -204,15 +244,16 @@ def get_conf_peers_data(config_name):
db.close()
def get_peers(config_name):
get_conf_peers_data(config_name)
def get_peers(config_name, search, sort_t):
get_all_peers_data(config_name)
db = TinyDB('db/' + config_name + '.json')
peer = Query()
print(search)
if len(search) == 0:
result = db.all()
result = sorted(result, key=lambda d: d['status'])
else:
result = db.search(peer.name.matches('(.*)(' + re.escape(search) + ')(.*)'))
result = sorted(result, key=lambda d: d[sort_t])
db.close()
return result
@ -262,8 +303,7 @@ def get_conf_status(config_name):
def get_conf_list():
conf = []
for i in os.listdir(wg_conf_path):
if not i.startswith('.'):
if ".conf" in i:
if is_match("^(.{1,}).(conf)$", i):
i = i.replace('.conf', '')
temp = {"conf": i, "status": get_conf_status(i), "public_key": get_conf_pub_key(i)}
if temp['status'] == "running":
@ -276,6 +316,88 @@ def get_conf_list():
return conf
def genKeys():
gen = subprocess.check_output('wg genkey > private_key.txt && wg pubkey < private_key.txt > public_key.txt',
shell=True)
private = open('private_key.txt')
private_key = private.readline().strip()
public = open('public_key.txt')
public_key = public.readline().strip()
data = {"private_key": private_key, "public_key": public_key}
private.close()
public.close()
os.remove('private_key.txt')
os.remove('public_key.txt')
return data
def genPubKey(private_key):
pri_key_file = open('private_key.txt', 'w')
pri_key_file.write(private_key)
pri_key_file.close()
try:
check = subprocess.check_output("wg pubkey < private_key.txt > public_key.txt", shell=True)
public = open('public_key.txt')
public_key = public.readline().strip()
os.remove('private_key.txt')
os.remove('public_key.txt')
return {"status": 'success', "msg": "", "data": public_key}
except subprocess.CalledProcessError as exc:
os.remove('private_key.txt')
return {"status": 'failed', "msg": "Key is not the correct length or format", "data": ""}
def checkKeyMatch(private_key, public_key, config_name):
result = genPubKey(private_key)
if result['status'] == 'failed':
return result
else:
db = TinyDB('db/' + config_name + '.json')
peers = Query()
match = db.search(peers.id == result['data'])
if len(match) != 1 or result['data'] != public_key:
return {'status': 'failed', 'msg': 'Please check your private key, it does not match with the public key.'}
else:
return {'status': 'success'}
def checkAllowedIP(public_key, ip, config_name):
db = TinyDB('db/' + config_name + '.json')
peers = Query()
peer = db.search(peers.id == public_key)
if len(peer) != 1:
return {'status': 'failed', 'msg': 'Peer does not exist'}
else:
existed_ip = db.search((peers.id != public_key) & (peers.allowed_ip == ip))
if len(existed_ip) != 0:
return {'status': 'failed', 'msg': "Allowed IP already taken by another peer."}
else:
return {'status': 'success'}
def checkIp(ip):
return is_match("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}", ip)
def cleanIp(ip):
return ip.replace(' ', '')
def cleanIpWithRange(ip):
return cleanIp(ip).split(',')
def checkIpWithRange(ip):
return is_match("((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|\/)){4}(0|8|16|24|32)(,|$)", ip)
def checkAllowedIPs(ip):
ip = cleanIpWithRange(ip)
for i in ip:
if not checkIpWithRange(i): return False
return True
@app.before_request
def auth_req():
conf = configparser.ConfigParser(strict=False)
@ -289,8 +411,11 @@ def auth_req():
request.endpoint != "signout" and \
request.endpoint != "auth" and \
"username" not in session:
print("User not loggedin - Attemped access: "+str(request.endpoint))
print("User not loggedin - Attemped access: " + str(request.endpoint))
if request.endpoint != "index":
session['message'] = "You need to sign in first!"
else:
session['message'] = ""
return redirect(url_for("signin"))
else:
if request.endpoint in ['signin', 'signout', 'auth', 'settings', 'update_acct', 'update_pwd',
@ -329,7 +454,9 @@ def settings():
required_auth = config.get("Server", "auth_req")
return render_template('settings.html', conf=get_conf_list(), message=message, status=status,
app_ip=config.get("Server", "app_ip"), app_port=config.get("Server", "app_port"),
required_auth=required_auth, wg_conf_path=config.get("Server", "wg_conf_path"))
required_auth=required_auth, wg_conf_path=config.get("Server", "wg_conf_path"),
peer_global_DNS=config.get("Peers", "peer_global_DNS"),
peer_endpoint_allowed_ip=config.get("Peers", "peer_endpoint_allowed_ip"))
@app.route('/auth', methods=['POST'])
@ -350,6 +477,10 @@ def auth():
@app.route('/update_acct', methods=['POST'])
def update_acct():
if len(request.form['username']) == 0:
session['message'] = "Username cannot be empty."
session['message_status'] = "danger"
return redirect(url_for("settings"))
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
config.set("Account", "username", request.form['username'])
@ -367,6 +498,45 @@ def update_acct():
return redirect(url_for("settings"))
@app.route('/update_peer_default_config', methods=['POST'])
def update_peer_default_config():
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
if len(request.form['peer_endpoint_allowed_ip']) == 0 or len(request.form['peer_global_DNS']) == 0:
session['message'] = "Peer DNS or Peer Endpoint Allowed IP cannot be empty."
session['message_status'] = "danger"
return redirect(url_for("settings"))
# Check DNS Format
DNS = request.form['peer_global_DNS']
DNS = cleanIp(DNS)
if not checkIp(DNS):
session['message'] = "Peer DNS Format Incorrect. Example: 1.1.1.1"
session['message_status'] = "danger"
return redirect(url_for("settings"))
# Check Endpoint Allowed IPs
ip = request.form['peer_endpoint_allowed_ip']
if not checkAllowedIPs(ip):
session[
'message'] = "Peer Endpoint Allowed IPs Format Incorrect. Example: 192.168.1.1/32 or 192.168.1.1/32,192.168.1.2/32"
session['message_status'] = "danger"
return redirect(url_for("settings"))
config.set("Peers", "peer_endpoint_allowed_ip", ','.join(cleanIpWithRange(ip)))
config.set("Peers", "peer_global_DNS", request.form['peer_global_DNS'])
try:
config.write(open(dashboard_conf, "w"))
session['message'] = "DNS and Enpoint Allowed IP update successfully!"
session['message_status'] = "success"
config.clear()
return redirect(url_for("settings"))
except Exception:
session['message'] = "DNS and Enpoint Allowed IP update failed."
session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings"))
@app.route('/update_pwd', methods=['POST'])
def update_pwd():
config = configparser.ConfigParser(strict=False)
@ -420,6 +590,22 @@ def update_wg_conf_path():
config.clear()
os.system('bash wgd.sh restart')
@app.route('/update_dashboard_sort', methods=['POST'])
def update_dashbaord_sort():
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
data = request.get_json()
sort_tag = ['name', 'status', 'allowed_ip']
if data['sort'] in sort_tag:
config.set("Server", "dashboard_sort", data['sort'])
else:
config.set("Server", "dashboard_sort", 'status')
config.write(open(dashboard_conf, "w"))
config.clear()
return "true"
@app.route('/update_dashboard_refresh_interval', methods=['POST'])
def update_dashboard_refresh_interval():
config = configparser.ConfigParser(strict=False)
@ -429,28 +615,30 @@ def update_dashboard_refresh_interval():
config.clear()
return "true"
@app.route('/get_ping_ip', methods=['POST'])
def get_ping_ip():
config = request.form['config']
db = TinyDB('db/' + config + '.json')
html = ""
for i in db.all():
html += '<optgroup label="'+i['name']+' - '+i['id']+'">'
html += '<optgroup label="' + i['name'] + ' - ' + i['id'] + '">'
allowed_ip = str(i['allowed_ip']).split(",")
for k in allowed_ip:
k = k.split("/")
if len(k) == 2:
html += "<option value="+k[0]+">"+k[0]+"</option>"
html += "<option value=" + k[0] + ">" + k[0] + "</option>"
endpoint = str(i['endpoint']).split(":")
if len(endpoint) == 2:
html += "<option value=" + endpoint[0] + ">" + endpoint[0] + "</option>"
html += "</optgroup>"
return html
@app.route('/ping_ip', methods=['POST'])
def ping_ip():
try:
result = ping(''+request.form['ip']+'', count=int(request.form['count']),privileged=True, source=None)
result = ping('' + request.form['ip'] + '', count=int(request.form['count']), privileged=True, source=None)
returnjson = {
"address": result.address,
"is_alive": result.is_alive,
@ -465,21 +653,24 @@ def ping_ip():
except Exception:
return "Error"
@app.route('/traceroute_ip', methods=['POST'])
def traceroute_ip():
try:
result = traceroute(''+request.form['ip']+'', first_hop=1, max_hops=30, count=1, fast=True)
result = traceroute('' + request.form['ip'] + '', first_hop=1, max_hops=30, count=1, fast=True)
returnjson = []
last_distance = 0
for hop in result:
if last_distance + 1 != hop.distance:
returnjson.append({"hop":"*", "ip":"*", "avg_rtt":"", "min_rtt":"", "max_rtt":""})
returnjson.append({"hop": hop.distance, "ip": hop.address, "avg_rtt": hop.avg_rtt, "min_rtt": hop.min_rtt, "max_rtt": hop.max_rtt})
returnjson.append({"hop": "*", "ip": "*", "avg_rtt": "", "min_rtt": "", "max_rtt": ""})
returnjson.append({"hop": hop.distance, "ip": hop.address, "avg_rtt": hop.avg_rtt, "min_rtt": hop.min_rtt,
"max_rtt": hop.max_rtt})
last_distance = hop.distance
return jsonify(returnjson)
except Exception:
return "Error"
@app.route('/', methods=['GET'])
def index():
return render_template('index.html', conf=get_conf_list())
@ -487,6 +678,8 @@ def index():
@app.route('/configuration/<config_name>', methods=['GET'])
def conf(config_name):
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
conf_data = {
"name": config_name,
"status": get_conf_status(config_name),
@ -501,26 +694,38 @@ def conf(config_name):
config_list = get_conf_list()
if config_name not in [conf['conf'] for conf in config_list]:
return render_template('index.html', conf=get_conf_list())
return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data, dashboard_refresh_interval=int(config.get("Server","dashboard_refresh_interval")))
return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data,
dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")),
DNS=config.get("Peers", "peer_global_DNS"),
endpoint_allowed_ip=config.get("Peers", "peer_endpoint_allowed_ip"), title=config_name)
@app.route('/get_config/<config_name>', methods=['GET'])
def get_conf(config_name):
config_interface = read_conf_file_interface(config_name)
search = request.args.get('search')
if len(search) == 0: search = ""
search = urllib.parse.unquote(search)
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
sort = config.get("Server", "dashboard_sort")
conf_data = {
"peer_data": get_peers(config_name),
"peer_data": get_peers(config_name, search, sort),
"name": config_name,
"status": get_conf_status(config_name),
"total_data_usage": get_conf_total_data(config_name),
"public_key": get_conf_pub_key(config_name),
"listen_port": get_conf_listen_port(config_name),
"running_peer": get_conf_running_peer_number(config_name),
"conf_address": config_interface['Address']
}
if conf_data['status'] == "stopped":
# return redirect('/')
conf_data['checked'] = "nope"
else:
conf_data['checked'] = "checked"
return render_template('get_conf.html', conf=get_conf_list(), conf_data=conf_data)
return render_template('get_conf.html', conf_data=conf_data, wg_ip=wg_ip, sort_tag=sort,
dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")))
@app.route('/switch/<config_name>', methods=['GET'])
@ -545,27 +750,43 @@ def switch(config_name):
@app.route('/add_peer/<config_name>', methods=['POST'])
def add_peer(config_name):
db = TinyDB("db/" + config_name + ".json")
peers = Query()
data = request.get_json()
public_key = data['public_key']
allowed_ips = data['allowed_ips']
endpoint_allowed_ip = data['endpoint_allowed_ip']
DNS = data['DNS']
keys = get_conf_peer_key(config_name)
if len(public_key) == 0 or len(DNS) == 0 or len(allowed_ips) == 0 or len(endpoint_allowed_ip) == 0:
return "Please fill in all required box."
if type(keys) != list:
return config_name+" is not running."
return config_name + " is not running."
if public_key in keys:
return "Key already exist."
return "Public key already exist."
if len(db.search(peers.allowed_ip.matches(allowed_ips))) != 0:
return "Allowed IP already taken by another peer."
if not checkIp(DNS):
return "DNS formate is incorrect. Example: 1.1.1.1"
if not checkAllowedIPs(endpoint_allowed_ip):
return "Endpoint Allowed IPs format is incorrect."
else:
status = ""
try:
status = subprocess.check_output(
"wg set " + config_name + " peer " + public_key + " allowed-ips " + allowed_ips, shell=True, stderr=subprocess.STDOUT)
"wg set " + config_name + " peer " + public_key + " allowed-ips " + allowed_ips, shell=True,
stderr=subprocess.STDOUT)
status = subprocess.check_output("wg-quick save " + config_name, shell=True, stderr=subprocess.STDOUT)
get_conf_peers_data(config_name)
db = TinyDB("db/" + config_name + ".json")
peers = Query()
db.update({"name": data['name']}, peers.id == public_key)
get_all_peers_data(config_name)
db.update({"name": data['name'], "private_key": data['private_key'], "DNS": data['DNS'],
"endpoint_allowed_ip": endpoint_allowed_ip},
peers.id == public_key)
db.close()
return "true"
except subprocess.CalledProcessError as exc:
db.close()
return exc.output.strip()
@ -579,7 +800,7 @@ def remove_peer(config_name):
delete_key = data['peer_id']
keys = get_conf_peer_key(config_name)
if type(keys) != list:
return config_name+" is not running."
return config_name + " is not running."
if delete_key not in keys:
db.close()
return "This key does not exist"
@ -595,19 +816,47 @@ def remove_peer(config_name):
return exc.output.strip()
@app.route('/save_peer_name/<config_name>', methods=['POST'])
def save_peer_name(config_name):
@app.route('/save_peer_setting/<config_name>', methods=['POST'])
def save_peer_setting(config_name):
data = request.get_json()
id = data['id']
name = data['name']
private_key = data['private_key']
DNS = data['DNS']
allowed_ip = data['allowed_ip']
endpoint_allowed_ip = data['endpoint_allowed_ip']
db = TinyDB("db/" + config_name + ".json")
peers = Query()
db.update({"name": name}, peers.id == id)
if len(db.search(peers.id == id)) == 1:
check_ip = checkAllowedIP(id, allowed_ip, config_name)
if private_key != "":
check_key = checkKeyMatch(private_key, id, config_name)
if check_key['status'] == "failed":
return jsonify(check_key)
if check_ip['status'] == "failed":
return jsonify(check_ip)
try:
if allowed_ip == "":
allowed_ip = '""'
change_ip = subprocess.check_output('wg set ' + config_name + " peer " + id + " allowed-ips " + allowed_ip,
shell=True, stderr=subprocess.STDOUT)
save_change_ip = subprocess.check_output('wg-quick save ' + config_name, shell=True,
stderr=subprocess.STDOUT)
if change_ip.decode("UTF-8") != "":
return jsonify({"status": "failed", "msg": change_ip.decode("UTF-8")})
db.update(
{"name": name, "private_key": private_key, "DNS": DNS, "endpoint_allowed_ip": endpoint_allowed_ip},
peers.id == id)
db.close()
return id + " " + name
return jsonify({"status": "success", "msg": ""})
except subprocess.CalledProcessError as exc:
return jsonify({"status": "failed", "msg": str(exc.output.decode("UTF-8").strip())})
else:
return jsonify({"status": "failed", "msg": "This peer does not exist."})
@app.route('/get_peer_name/<config_name>', methods=['POST'])
@app.route('/get_peer_data/<config_name>', methods=['POST'])
def get_peer_name(config_name):
data = request.get_json()
id = data['id']
@ -615,9 +864,76 @@ def get_peer_name(config_name):
peers = Query()
result = db.search(peers.id == id)
db.close()
return result[0]['name']
data = {"name": result[0]['name'], "allowed_ip": result[0]['allowed_ip'], "DNS": result[0]['DNS'],
"private_key": result[0]['private_key'], "endpoint_allowed_ip": result[0]['endpoint_allowed_ip']}
return jsonify(data)
@app.route('/generate_peer', methods=['GET'])
def generate_peer():
return jsonify(genKeys())
@app.route('/generate_public_key', methods=['POST'])
def generate_public_key():
data = request.get_json()
private_key = data['private_key']
return jsonify(genPubKey(private_key))
@app.route('/check_key_match/<config_name>', methods=['POST'])
def check_key_match(config_name):
data = request.get_json()
private_key = data['private_key']
public_key = data['public_key']
return jsonify(checkKeyMatch(private_key, public_key, config_name))
@app.route('/download/<config_name>', methods=['GET'])
def download(config_name):
print(request.headers.get('User-Agent'))
id = request.args.get('id')
db = TinyDB("db/" + config_name + ".json")
peers = Query()
print(id)
get_peer = db.search(peers.id == id)
print(get_peer)
if len(get_peer) == 1:
peer = get_peer[0]
if peer['private_key'] != "":
public_key = get_conf_pub_key(config_name)
listen_port = get_conf_listen_port(config_name)
endpoint = wg_ip + ":" + listen_port
private_key = peer['private_key']
allowed_ip = peer['allowed_ip']
DNS = peer['DNS']
endpoint_allowed_ip = peer['endpoint_allowed_ip']
filename = peer['name']
if len(filename) == 0:
filename = "Untitled_Peers"
else:
filename = peer['name']
# Clean filename
illegal_filename = [".", ",", "/", "?", "<", ">", "\\", ":", "*", '|' '\"', "com1", "com2", "com3",
"com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4",
"lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "con", "nul", "prn"]
for i in illegal_filename:
filename = filename.replace(i, "")
print(filename)
if len(filename) == 0:
filename = "Untitled_Peer"
filename = "".join(filename.split(' '))
filename = filename + "_" + config_name
def generate(private_key, allowed_ip, DNS, public_key, endpoint):
yield "[Interface]\nPrivateKey = " + private_key + "\nAddress = " + allowed_ip + "\nDNS = " + DNS + "\n\n[Peer]\nPublicKey = " + public_key + "\nAllowedIPs = "+endpoint_allowed_ip+"\nEndpoint = " + endpoint
return app.response_class(generate(private_key, allowed_ip, DNS, public_key, endpoint),
mimetype='text/conf',
headers={"Content-Disposition": "attachment;filename=" + filename + ".conf"})
else:
return redirect("/configuration/" + config_name)
def init_dashboard():
@ -633,7 +949,6 @@ def init_dashboard():
config['Account']['username'] = 'admin'
if "password" not in config['Account']:
config['Account']['password'] = '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918'
if "Server" not in config:
config['Server'] = {}
if 'wg_conf_path' not in config['Server']:
@ -648,6 +963,14 @@ def init_dashboard():
config['Server']['version'] = dashboard_version
if 'dashboard_refresh_interval' not in config['Server']:
config['Server']['dashboard_refresh_interval'] = '15000'
if 'dashboard_sort' not in config['Server']:
config['Server']['dashboard_sort'] = 'status'
if "Peers" not in config:
config['Peers'] = {}
if 'peer_global_DNS' not in config['Peers']:
config['Peers']['peer_global_DNS'] = '1.1.1.1'
if 'peer_endpoint_allowed_ip' not in config['Peers']:
config['Peers']['peer_endpoint_allowed_ip'] = '0.0.0.0/0'
config.write(open(dashboard_conf, "w"))
config.clear()

View File

@ -1,4 +1,5 @@
Flask==1.1.2
Flask==2.0.1
tinydb==4.3.0
ifcfg==0.21
icmplib==2.1.1
icmplib==3.0.1
flask-qrcode==3.0.0

Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 KiB

7
src/static/css/bootstrap.min.css vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,262 @@
body {
font-size: .875rem;
}
.feather {
width: 16px;
height: 16px;
vertical-align: text-bottom;
}
/*
* Sidebar
*/
.sidebar {
position: fixed;
top: 0;
bottom: 0;
left: 0;
z-index: 100; /* Behind the navbar */
padding: 48px 0 0; /* Height of navbar */
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}
/*@media (max-width: 767.98px) {*/
/* .sidebar {*/
/* top: 5rem;*/
/* }*/
/*}*/
.sidebar-sticky {
position: relative;
top: 0;
height: calc(100vh - 48px);
padding-top: .5rem;
overflow-x: hidden;
overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
}
@supports ((position: -webkit-sticky) or (position: sticky)) {
.sidebar-sticky {
position: -webkit-sticky;
position: sticky;
}
}
.sidebar .nav-link {
font-weight: 500;
color: #333;
transition: 0.2s cubic-bezier(0.82, -0.07, 0, 1.01);
}
.nav-link:hover {
padding-left: 30px;
}
.sidebar .nav-link .feather {
margin-right: 4px;
color: #999;
}
.sidebar .nav-link.active {
color: #007bff;
}
.sidebar .nav-link:hover .feather,
.sidebar .nav-link.active .feather {
color: inherit;
}
.sidebar-heading {
font-size: .75rem;
text-transform: uppercase;
}
/*
* Navbar
*/
.navbar-brand {
padding-top: .75rem;
padding-bottom: .75rem;
font-size: 1rem;
background-color: rgba(0, 0, 0, .25);
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
}
.navbar .navbar-toggler {
top: .25rem;
right: 1rem;
}
.navbar .form-control {
padding: .75rem 1rem;
border-width: 0;
border-radius: 0;
}
.form-control-dark {
color: #fff;
background-color: rgba(255, 255, 255, .1);
border-color: rgba(255, 255, 255, .1);
}
.form-control-dark:focus {
border-color: transparent;
box-shadow: 0 0 0 3px rgba(255, 255, 255, .25);
}
.dot{
width: 10px;
height: 10px;
border-radius: 50px;
display: inline-block;
margin-left: 10px;
}
.dot-running{
background-color: #28a745!important;
}
.dot-stopped{
background-color: #6c757d!important;
}
.info h6{
line-break: anywhere;
}
.btn-control{
border: none !important;
padding: 0 1rem 0 0;
}
.share_peer_btn_group .btn-control{
padding: 0 0 0 1rem;
}
.btn-control:hover{
background: white;
}
.btn-delete-peer:hover{
color: #dc3545;
}
.btn-setting-peer:hover{
color:#007bff
}
.btn-download-peer:hover{
color: #17a2b8;
}
.login-container{
padding: 2rem;
}
@media (max-width: 992px){
.card-col{
margin-bottom: 1rem;
}
}
.switch{
font-size: 2rem;
}
.switch:hover{
text-decoration: none
}
.btn-group-label:hover{
color: #007bff;
border-color: #007bff;
background: white;
}
/*.peer_data_group{*/
/* text-align: right;*/
/*}*/
@media (max-width: 768px) {
.peer_data_group{
text-align: left;
}
}
.index-switch{
text-align: right;
}
main{
margin-bottom: 3rem;
}
/*.add_btn{*/
/* position: fixed;*/
/* bottom: 1.75rem;*/
/* right: 1.75rem;*/
/* z-index: 1000;*/
/* padding: 0.75rem 1.5rem;*/
/* border-radius: 3rem;*/
/* font-size: 1rem;*/
/*}*/
@-webkit-keyframes rotating /* Safari and Chrome */ {
from {
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes rotating {
from {
-ms-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-webkit-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-ms-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-webkit-transform: rotate(360deg);
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.rotating::before {
-webkit-animation: rotating 0.75s linear infinite;
-moz-animation: rotating 0.75s linear infinite;
-ms-animation: rotating 0.75s linear infinite;
-o-animation: rotating 0.75s linear infinite;
animation: rotating 0.75s linear infinite;
}
.peer_private_key_textbox_switch{
position: absolute;
right: 2rem;
transform: translateY(-28px);
font-size: 1.2rem;
cursor: pointer;
}
.progress-bar{
transition: 0.3s ease-in-out;
}
.key{
transition: 0.2s ease-in-out;
cursor: pointer;
}
.key:hover{
color: #007bff;
}

View File

@ -1,198 +0,0 @@
body {
font-size: .875rem;
}
.feather {
width: 16px;
height: 16px;
vertical-align: text-bottom;
}
/*
* Sidebar
*/
.sidebar {
position: fixed;
top: 0;
bottom: 0;
left: 0;
z-index: 100; /* Behind the navbar */
padding: 48px 0 0; /* Height of navbar */
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}
/*@media (max-width: 767.98px) {*/
/* .sidebar {*/
/* top: 5rem;*/
/* }*/
/*}*/
.sidebar-sticky {
position: relative;
top: 0;
height: calc(100vh - 48px);
padding-top: .5rem;
overflow-x: hidden;
overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
}
@supports ((position: -webkit-sticky) or (position: sticky)) {
.sidebar-sticky {
position: -webkit-sticky;
position: sticky;
}
}
.sidebar .nav-link {
font-weight: 500;
color: #333;
transition: 0.2s cubic-bezier(0.82, -0.07, 0, 1.01);
}
.nav-link:hover {
padding-left: 30px;
}
.sidebar .nav-link .feather {
margin-right: 4px;
color: #999;
}
.sidebar .nav-link.active {
color: #007bff;
}
.sidebar .nav-link:hover .feather,
.sidebar .nav-link.active .feather {
color: inherit;
}
.sidebar-heading {
font-size: .75rem;
text-transform: uppercase;
}
/*
* Navbar
*/
.navbar-brand {
padding-top: .75rem;
padding-bottom: .75rem;
font-size: 1rem;
background-color: rgba(0, 0, 0, .25);
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
}
.navbar .navbar-toggler {
top: .25rem;
right: 1rem;
}
.navbar .form-control {
padding: .75rem 1rem;
border-width: 0;
border-radius: 0;
}
.form-control-dark {
color: #fff;
background-color: rgba(255, 255, 255, .1);
border-color: rgba(255, 255, 255, .1);
}
.form-control-dark:focus {
border-color: transparent;
box-shadow: 0 0 0 3px rgba(255, 255, 255, .25);
}
.dot{
width: 10px;
height: 10px;
border-radius: 50px;
display: inline-block;
margin-left: 10px;
}
.dot-running{
background-color: #28a745!important;
}
.dot-stopped{
background-color: #6c757d!important;
}
.info h6{
line-break: anywhere;
}
.btn-control{
border: none !important;
padding: 0;
padding-right: 0.5rem;
}
.btn-control:hover{
background: white;
}
.btn-delete-peer:hover{
color: #dc3545;
}
.btn-setting-peer:hover{
color:#007bff
}
.login-container{
padding: 2rem;
}
@media (max-width: 992px){
.card-col{
margin-bottom: 1rem;
}
}
.switch{
font-size: 2rem;
}
.switch:hover{
text-decoration: none
}
.btn-group-label:hover{
color: #007bff;
border-color: #007bff;
background: white;
}
.peer_data_group{
text-align: right;
}
@media (max-width: 768px) {
.peer_data_group{
text-align: left;
}
}
.index-switch{
text-align: right;
}
main{
margin-bottom: 3rem;
}
/*.add_btn{*/
/* position: fixed;*/
/* bottom: 1.75rem;*/
/* right: 1.75rem;*/
/* z-index: 1000;*/
/* padding: 0.75rem 1.5rem;*/
/* border-radius: 3rem;*/
/* font-size: 1rem;*/
/*}*/

View File

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

7045
src/static/js/bootstrap.bundle.js vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

7
src/static/js/bootstrap.bundle.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,332 @@
// Config Toggle
$("body").on("click", ".switch", function (){
$(this).siblings($(".spinner-border")).css("display", "inline-block");
$(this).remove()
location.replace("/switch/"+$(this).attr('id'));
})
// Generating Keys
function generate_key(){
$.ajax({
"url": "/generate_peer",
"method": "GET",
}).done(function(res){
$("#private_key").val(res.private_key)
$("#public_key").val(res.public_key)
$("#add_peer_alert").addClass("d-none");
$("#re_generate_key i").removeClass("rotating")
})
}
function generate_public_key(){
$.ajax({
"url": "/generate_public_key",
"method": "POST",
"headers":{"Content-Type": "application/json"},
"data": JSON.stringify({"private_key": $("#private_key").val()})
}).done(function(res){
if(res['status'] === "failed"){
$("#add_peer_alert").html(res['msg']+$("#add_peer_alert").html());
$("#add_peer_alert").removeClass("d-none");
}else{
$("#add_peer_alert").addClass("d-none");
}
$("#public_key").val(res['data'])
$("#re_generate_key i").removeClass("rotating")
})
}
// Add Peer
$("#private_key").change(function(){
if ($("#private_key").val().length > 0){
$("#re_generate_key i").addClass("rotating")
generate_public_key()
}else{
$("#public_key").removeAttr("disabled")
$("#public_key").val("")
}
})
$('#add_modal').on('show.bs.modal', function (event) {
generate_key()
})
$("#re_generate_key").click(function (){
$("#public_key").attr("disabled","disabled")
$("#re_generate_key i").addClass("rotating")
generate_key()
})
$("#save_peer").click(function(){
$(this).attr("disabled","disabled")
$(this).html("Saving...")
if ($("#allowed_ips").val() !== "" && $("#public_key").val() !== "" && $("#new_add_DNS").val() !== "" && $("#new_add_endpoint_allowed_ip").val() != ""){
var conf = $(this).attr('conf_id')
var data_list = [$("#private_key"), $("#allowed_ips"), $("#new_add_name"), $("#new_add_DNS"), $("#new_add_endpoint_allowed_ip")]
for (var i = 0; i < data_list.length; i++){
data_list[i].attr("disabled", "disabled")
}
$.ajax({
method: "POST",
url: "/add_peer/"+conf,
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({
"private_key":$("#private_key").val(),
"public_key":$("#public_key").val(),
"allowed_ips": $("#allowed_ips").val(),
"name":$("#new_add_name").val(),
"DNS": $("#new_add_DNS").val(),
"endpoint_allowed_ip": $("#new_add_endpoint_allowed_ip").val()
}),
success: function (response){
if(response != "true"){
$("#add_peer_alert").html(response+$("#add_peer_alert").html());
$("#add_peer_alert").removeClass("d-none");
}
else{
location.reload();
}
}
})
}else{
$("#add_peer_alert").html("Please fill in all required box.");
$("#add_peer_alert").removeClass("d-none");
}
})
var qrcodeModal = new bootstrap.Modal(document.getElementById('qrcode_modal'), {
keyboard: false
})
// QR Code
$("body").on("click", ".btn-qrcode-peer", function (){
qrcodeModal.toggle();
$("#qrcode_img").attr('src', $(this).attr('img_src'))
})
// Delete Peer Modal
var deleteModal = new bootstrap.Modal(document.getElementById('delete_modal'), {
keyboard: false
});
$("body").on("click", ".btn-delete-peer", function(){
var peer_id = $(this).attr("id");
$("#delete_peer").attr("peer_id", peer_id);
deleteModal.toggle();
})
$("#delete_peer").click(function(){
$(this).attr("disabled","disabled")
$(this).html("Deleting...")
var peer_id = $(this).attr("peer_id");
var config = $(this).attr("conf_id");
$.ajax({
method: "POST",
url: "/remove_peer/"+config,
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({"action": "delete", "peer_id": peer_id}),
success: function (response){
if(response !== "true"){
$("#remove_peer_alert").html(response+$("#add_peer_alert").html());
$("#remove_peer_alert").removeClass("d-none");
}
else{
deleteModal.toggle();
load_data($('#search_peer_textbox').val());
$('#alertToast').toast('show');
$('#alertToast .toast-body').html("Peer deleted!");
$("#delete_peer").removeAttr("disabled")
$("#delete_peer").html("Delete")
}
}
})
});
// Peer Setting Modal
var settingModal = new bootstrap.Modal(document.getElementById('setting_modal'), {
keyboard: false
})
$("body").on("click", ".btn-setting-peer", function(){
startProgressBar()
var peer_id = $(this).attr("id");
$("#save_peer_setting").attr("peer_id", peer_id);
$.ajax({
method: "POST",
url: "/get_peer_data/"+$("#setting_modal").attr("conf_id"),
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({"id": peer_id}),
success: function(response){
let peer_name = ((response['name'] === "") ? "Untitled Peer" : response['name']);
$("#setting_modal .peer_name").html(peer_name);
$("#setting_modal #peer_name_textbox").val(peer_name)
$("#setting_modal #peer_private_key_textbox").val(response['private_key'])
$("#setting_modal #peer_DNS_textbox").val(response['DNS'])
$("#setting_modal #peer_allowed_ip_textbox").val(response['allowed_ip'])
$("#setting_modal #peer_endpoint_allowed_ips").val(response['endpoint_allowed_ip'])
settingModal.toggle();
endProgressBar()
}
})
});
$('#setting_modal').on('hidden.bs.modal', function (event) {
$("#setting_peer_alert").addClass("d-none");
})
$("#peer_private_key_textbox").change(function(){
if ($(this).val().length > 0){
$.ajax({
"url": "/check_key_match/"+$("#save_peer_setting").attr("conf_id"),
"method": "POST",
"headers":{"Content-Type": "application/json"},
"data": JSON.stringify({
"private_key": $("#peer_private_key_textbox").val(),
"public_key": $("#save_peer_setting").attr("peer_id")
})
}).done(function(res){
if(res['status'] == "failed"){
$("#setting_peer_alert").html(res['msg']);
$("#setting_peer_alert").removeClass("d-none");
}else{
$("#setting_peer_alert").addClass("d-none");
}
})
}
})
$("#save_peer_setting").click(function (){
$(this).attr("disabled","disabled")
$(this).html("Saving...")
if ($("#peer_DNS_textbox").val() !== "" &&
$("#peer_allowed_ip_textbox").val() !== "" &&
$("#peer_endpoint_allowed_ips").val() != ""
){
var peer_id = $(this).attr("peer_id");
var conf_id = $(this).attr("conf_id");
var data_list = [$("#peer_name_textbox"), $("#peer_DNS_textbox"), $("#peer_private_key_textbox"), $("#peer_allowed_ip_textbox"), $("#peer_endpoint_allowed_ips")]
for (var i = 0; i < data_list.length; i++){
data_list[i].attr("disabled", "disabled")
}
$.ajax({
method: "POST",
url: "/save_peer_setting/"+conf_id,
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({
id: peer_id,
name: $("#peer_name_textbox").val(),
DNS: $("#peer_DNS_textbox").val(),
private_key: $("#peer_private_key_textbox").val(),
allowed_ip: $("#peer_allowed_ip_textbox").val(),
endpoint_allowed_ip: $("#peer_endpoint_allowed_ips").val()
}),
success: function (response){
if (response['status'] === "failed"){
$("#setting_peer_alert").html(response['msg']);
$("#setting_peer_alert").removeClass("d-none");
}else{
settingModal.toggle();
load_data($('#search_peer_textbox').val())
$('#alertToast').toast('show');
$('#alertToast .toast-body').html("Peer Saved!");
}
$("#save_peer_setting").removeAttr("disabled")
$("#save_peer_setting").html("Save")
for (var i = 0; i < data_list.length; i++){
data_list[i].removeAttr("disabled")
}
}
})
}else{
$("#setting_peer_alert").html("Please fill in all required box.");
$("#setting_peer_alert").removeClass("d-none");
}
})
$(".peer_private_key_textbox_switch").click(function (){
let mode = (($("#peer_private_key_textbox").attr('type') === 'password') ? "text":"password")
let icon = (($("#peer_private_key_textbox").attr('type') === 'password') ? "bi bi-eye-slash-fill":"bi bi-eye-fill")
$("#peer_private_key_textbox").attr('type',mode)
$(".peer_private_key_textbox_switch i").removeClass().addClass(icon)
})
// Search Peer
var typingTimer;
var doneTypingInterval = 200;
var $input = $('#search_peer_textbox');
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
function doneTyping () {
load_data($('#search_peer_textbox').val());
}
// Sorting
$("body").on("change", "#sort_by_dropdown", function (){
$.ajax({
method:"POST",
data: JSON.stringify({'sort':$("#sort_by_dropdown option:selected").val()}),
headers:{"Content-Type": "application/json"},
url: "/update_dashboard_sort",
success: function (res){
location.reload()
}
})
})
$("body").on("mouseenter", ".key", function(){
var label = $(this).parent().siblings().children()[1]
label.style.opacity = "100"
})
$("body").on("mouseout", ".key", function(){
var label = $(this).parent().siblings().children()[1]
label.style.opacity = "0"
setTimeout(function (){
label.innerHTML = "CLICK TO COPY"
},200)
});
$("body").on("click", ".key", function(){
var label = $(this).parent().siblings().children()[1]
copyToClipboard($(this))
label.innerHTML = "COPIED!"
})
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
$("body").on("click", ".update_interval", function(){
$.ajax({
method:"POST",
data: "interval="+$(this).attr("refresh-interval"),
url: "/update_dashboard_refresh_interval",
success: function (res){
location.reload()
}
})
});
$("body").on("click", ".refresh", function (){
load_data($('#search_peer_textbox').val());
});

2
src/static/js/jquery.min.js vendored Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

View File

@ -1,14 +1,25 @@
<html>
{% include "header.html" %}
{% with title=title%}
{% include "header.html"%}
{% endwith %}
<body>
{% include "navbar.html" %}
<div class="container-fluid">
{% include "sidebar.html" %}
<div id="config_body"></div>
<div class="col-md-9 ml-sm-auto col-lg-10 px-md-4 mt-4 mb-4">
<div class="form-group">
<input type="text" class="form-control" id="search_peer_textbox" placeholder="Search Peer..." value="" style="display: none">
</div>
</div>
<div id="config_body">
</div>
</div>
<div class="modal fade" id="add_modal" data-backdrop="static" data-keyboard="false" tabindex="-1"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Add a new peer</h5>
@ -23,17 +34,52 @@
</button>
</div>
<form id="add_peer_form">
<div class="form-group">
<label for="public_key">Public Key<code>*</code></label>
<input type="text" class="form-control" id="public_key" aria-describedby="public_key">
<div class="alert alert-warning" role="alert" style="font-size: 0.8rem">
To generate QR code for this new peer, you need to provide the private key, or use the generated key. If you don't need the QR code, simply remove the private key and insert your existed public key.
</div>
<div class="form-group">
<label for="allowed_ips">Allowed IPs<code>*</code></label>
<div>
<label for="private_key">Private Key</label>
</div>
<div class="input-group">
<input type="text" class="form-control" id="private_key" aria-describedby="public_key">
<div class="input-group-append">
<button type="button" class="btn btn-danger" id="re_generate_key">
<i class="bi bi-arrow-repeat"></i>
</button>
</div>
</div>
</div>
<div class="form-group">
<label for="public_key">Public Key <code>(Required)</code></label>
<input type="text" class="form-control" id="public_key" aria-describedby="public_key" disabled>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="new_add_name">Name</label>
<input type="text" class="form-control" id="new_add_name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="allowed_ips">Allowed IPs <code>(Required)</code></label>
<input type="text" class="form-control" id="allowed_ips">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="allowed_ips">Name</label>
<input type="text" class="form-control" id="new_add_name">
<label for="new_add_DNS">DNS <code>(Required)</code></label>
<input type="text" class="form-control" id="new_add_DNS" value="{{ DNS }}">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="new_add_endpoint_allowed_ip">Endpoint Allowed IPs <code>(Required)</code></label>
<input type="text" class="form-control" id="new_add_endpoint_allowed_ip" value="{{ endpoint_allowed_ip }}">
</div>
</div>
</div>
</form>
</div>
@ -72,7 +118,7 @@
<div class="modal fade" id="setting_modal" data-backdrop="static" data-keyboard="false" tabindex="-1"
aria-labelledby="staticBackdropLabel" aria-hidden="true" conf_id={{conf_data['name']}} peer_id="">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="peer_name"></h5>
@ -81,15 +127,55 @@
</button>
</div>
<div class="modal-body">
<div id="setting_peer_alert" class="alert alert-danger alert-dismissible fade show d-none" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="mb-3">
<label for="peer_name" class="form-label">Name</label>
<label for="peer_name_textbox" class="form-label">Name</label>
<input type="text" class="form-control" id="peer_name_textbox" placeholder="">
</div>
<div class="mb-3">
<label for="peer_private_key_textbox" class="form-label">Private Key <code>(Required for QR Code and download)</code></label>
<input type="password" class="form-control" id="peer_private_key_textbox" style="padding-right: 40px">
<a class="peer_private_key_textbox_switch"><i class="bi bi-eye-fill"></i></a>
</div>
<div class="mb-3">
<label for="peer_allowed_ip_textbox" class="form-label">Allowed IPs <code>(Required)</code></label>
<input type="text" class="form-control" id="peer_allowed_ip_textbox">
</div>
<div class="mb-3">
<label for="peer_DNS_textbox" class="form-label">DNS <code>(Required)</code></label>
<input type="text" class="form-control" id="peer_DNS_textbox">
</div>
<div class="mb-3">
<label for="peer_endpoint_allowed_ips" class="form-label">Endpoint Allowed IPs <code>(Required)</code></label>
<input type="text" class="form-control" id="peer_endpoint_allowed_ips">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="save_peer_name" conf_id={{conf_data['name']}} peer_id="">Save</button>
<button type="button" class="btn btn-primary" id="save_peer_setting" conf_id={{conf_data['name']}} peer_id="">Save</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="qrcode_modal" data-backdrop="static" data-keyboard="false" tabindex="-1"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="peer_name">QR Code</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<img src="" id="qrcode_img" style="width: 100%">
</div>
</div>
</div>
@ -111,158 +197,60 @@
</body>
{% include "footer.html" %}
<script>
$(".sb-{{conf_data['name']}}-url").addClass("active");
function load_data(){
var conf_name = "{{ conf_data['name'] }}"
$(".sb-"+conf_name+"-url").addClass("active");
// Progress Bar
let bar = $(".progress-bar")
function startProgressBar(){
bar.css("width","0%")
bar.css("opacity", "100")
bar.css("background", "rgb(255,69,69)")
bar.css("background", "linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)")
bar.css("width","25%")
setTimeout(function(){
stillLoadingProgressBar();
},300)
}
function stillLoadingProgressBar(){
bar.css("transition", "3s ease-in-out")
bar.css("width", "75%")
}
function endProgressBar(){
bar.css("transition", "0.3s ease-in-out")
bar.css("width","100%")
setTimeout(function(){
bar.css("opacity", "0")
},250)
}
function load_data(search){
startProgressBar()
$.ajax({
method: "GET",
url: "/get_config/"+"{{conf_data['name']}}",
url: "/get_config/"+conf_name+"?search="+encodeURIComponent(search),
headers:{
"Content-Type": "application/json"
},
async:false,
success: function (response){
$("#config_body").html(response);
$("[refresh-interval={{ dashboard_refresh_interval }}]").addClass("active")
$("#search_peer_textbox").css("display", "block")
if (bar.css("width") !== "0%"){
endProgressBar()
}
}
})
}
$(document).ready(function(){
load_data();
load_data($('#search_peer_textbox').val());
setInterval(function(){
load_data();
load_data($('#search_peer_textbox').val());
}, {{dashboard_refresh_interval}})
});
$("body").on("click", ".update_interval", function(){
$.ajax({
method:"POST",
data: "interval="+$(this).attr("refresh-interval"),
url: "/update_dashboard_refresh_interval",
success: function (res){
location.reload()
}
})
});
$("body").on("click", ".refresh", function (){
load_data();
});
</script>
<script>
$("body").on("click", ".switch", function (){
$(this).siblings($(".spinner-border")).css("display", "inline-block");
$(this).remove()
location.replace("/switch/"+$(this).attr('id'));
})
$("#save_peer").click(function(){
if ($("#allowed_ips") != "" && $("#public_key") != ""){
var conf = $(this).attr('conf_id')
$.ajax({
method: "POST",
url: "/add_peer/"+conf,
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({"public_key":$("#public_key").val(),
"allowed_ips": $("#allowed_ips").val(),
"name":$("#new_add_name").val()}),
success: function (response){
if(response != "true"){
$("#add_peer_alert").html(response+$("#add_peer_alert").html());
$("#add_peer_alert").removeClass("d-none");
}
else{
location.reload();
}
}
})
}
})
var deleteModal = new bootstrap.Modal(document.getElementById('delete_modal'), {
keyboard: false
});
$("body").on("click", ".btn-delete-peer", function(){
var peer_id = $(this).attr("id");
$("#delete_peer").attr("peer_id", peer_id);
deleteModal.toggle();
})
$("#delete_peer").click(function(){
var peer_id = $(this).attr("peer_id");
var config = $(this).attr("conf_id");
$.ajax({
method: "POST",
url: "/remove_peer/"+config,
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({"action": "delete", "peer_id": peer_id}),
success: function (response){
if(response !== "true"){
$("#remove_peer_alert").html(response+$("#add_peer_alert").html());
$("#remove_peer_alert").removeClass("d-none");
}
else{
deleteModal.toggle();
load_data();
$('#alertToast').toast('show');
$('#alertToast .toast-body').html("Peer deleted!");
}
}
})
});
var settingModal = new bootstrap.Modal(document.getElementById('setting_modal'), {
keyboard: false
})
$("body").on("click", ".btn-setting-peer", function(){
settingModal.toggle();
var peer_id = $(this).attr("id");
$("#save_peer_name").attr("peer_id", peer_id);
$.ajax({
method: "POST",
url: "/get_peer_name/"+$("#setting_modal").attr("conf_id"),
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({"id": peer_id}),
success: function(response){
if (response == ""){
$("#setting_modal .peer_name").html("Untitled Peer");
$("#peer_name_textbox").val("")
}else{
$("#setting_modal .peer_name").html(response);
$("#peer_name_textbox").val(response)
}
}
})
});
$("#save_peer_name").click(function (){
var peer_id = $(this).attr("peer_id");
$.ajax({
method: "POST",
url: "/save_peer_name/"+"{{conf_data['name']}}",
headers:{
"Content-Type": "application/json"
},
data: JSON.stringify({id: peer_id, name: $("#peer_name_textbox").val()}),
success: function (response){
settingModal.toggle();
load_data();
$('#alertToast').toast('show');
$('#alertToast .toast-body').html("Name Saved!");
}
})
})
</script>
<script src="{{ url_for('static',filename='js/configuration.js') }}"></script>
</html>

View File

@ -1,9 +1,3 @@
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js"
integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s"
crossorigin="anonymous"></script>
<script src="{{ url_for('static',filename='tools.js') }}"></script>
<script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
<script src="{{ url_for('static',filename='js/bootstrap.bundle.js') }}"></script>
<script src="{{ url_for('static',filename='js/tools.js') }}"></script>

View File

@ -39,34 +39,72 @@
</div>
<div class="w-100"></div>
<div class="col-sm">
<small class="text-muted"><strong>PUBLIC KEY</strong></small>
<h6 style="text-transform: uppercase;"><samp>{{conf_data['public_key']}}</samp></h6>
<small class="text-muted">
<strong>PUBLIC KEY</strong>
<strong style="margin-left: auto!important; opacity: 0; transition: 0.2s ease-in-out" class="text-primary">CLICK TO COPY</strong></small>
</small>
<h6 style="text-transform: uppercase;"><samp class="key">{{conf_data['public_key']}}</samp></h6>
</div>
<div class="col-sm">
<small class="text-muted"><strong>LISTEN PORT</strong></small>
<h6 style="text-transform: uppercase;"><samp>{{conf_data['listen_port']}}</samp></h6>
</div>
<div class="col-sm">
<small class="text-muted"><strong>ADDRESS</strong></small>
<h6 style="text-transform: uppercase;"><samp>{{conf_data['conf_address']}}</samp></h6>
</div>
</div>
<hr>
<div class="button-div mb-3" style="text-align: right;">
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-outline-primary btn-sm btn-group-label refresh"><i class="bi bi-arrow-repeat"></i></button>
<button type="button" class="btn btn-outline-primary btn-sm update_interval" refresh-interval="5000">5s</button>
<button type="button" class="btn btn-outline-primary btn-sm update_interval" refresh-interval="10000">10s</button>
<button type="button" class="btn btn-outline-primary btn-sm update_interval" refresh-interval="30000">30s</button>
<button type="button" class="btn btn-outline-primary btn-sm update_interval" refresh-interval="60000">1m</button>
<div class="button-div mb-3">
<div class="row">
<div class="col-sm">
<div class="form-group">
<label for="sort_by_dropdown"><small class="text-muted">Sort Peers By</small></label>
<select class="form-control" id="sort_by_dropdown">
<option value="status" {% if sort_tag == "status" %} {{ "selected" }} {% endif %}>Status</option>
<option value="name" {% if sort_tag == "name" %} {{ "selected" }} {% endif %}>Name</option>
<option value="allowed_ip" {% if sort_tag == "allowed_ip" %} {{ "selected" }} {% endif %}>Allowed IP</option>
</select>
</div>
<button type="button" class="btn btn-primary add_btn btn-sm" data-toggle="modal" data-target="#add_modal">
<i class="bi bi-plus-circle-fill"></i> PEER
</div>
<div class="col-sm">
<div class="form-group">
<label><small class="text-muted">Refresh Interval</small></label><br>
<div class="btn-group" role="group" style="width: 100%">
<button style="width: 20%" type="button" class="btn btn-outline-primary btn-group-label refresh"><i class="bi bi-arrow-repeat"></i></button>
<button style="width: 20%" type="button" class="btn btn-outline-primary update_interval {% if dashboard_refresh_interval == 5000 %} {{ "active" }} {% endif %}" refresh-interval="5000">5s</button>
<button style="width: 20%" type="button" class="btn btn-outline-primary update_interval {% if dashboard_refresh_interval == 10000 %} {{ "active" }} {% endif %}" refresh-interval="10000">10s</button>
<button style="width: 20%" type="button" class="btn btn-outline-primary update_interval {% if dashboard_refresh_interval == 30000 %} {{ "active" }} {% endif %}" refresh-interval="30000">30s</button>
<button style="width: 20%" type="button" class="btn btn-outline-primary update_interval {% if dashboard_refresh_interval == 60000 %} {{ "active" }} {% endif %}" refresh-interval="60000">1m</button>
</div>
</div>
</div>
<div class="col-sm">
<div class="form-group">
<label><small class="text-muted">Add</small></label><br>
<button type="button" class="btn btn-primary add_btn" data-toggle="modal" data-target="#add_modal" style="width: 100%">
<i class="bi bi-plus-circle-fill"></i> Add Peer
</button>
</div>
</div>
</div>
<hr>
</div>
</div>
<div class="row">
{% if conf_data['peer_data']|length == 0 %}
<div class="col-12" style="text-align: center; margin-top: 1.5rem">
<h3 class="text-muted">Oops! No peers found ‘︿’</h3>
</div>
{% endif %}
{% for i in conf_data['peer_data']%}
<div class="col-sm-6 col-md-4">
<div class="card mb-3">
<div class="card-header">
<div class="row">
<div class="col-sm">
<div class="col-12">
<div class="card-header-body ">
{% if not i['name']%}
{{ "Untitled Peer" }}
@ -76,20 +114,19 @@
<span class="dot dot-{{i['status']}}"></span>
</div>
</div>
<div class="col-sm peer_data_group">
<div class="col-12 peer_data_group">
<p class="text-primary" style="text-transform: uppercase; display: inline-block; margin-bottom: 0; margin-right: 1rem"><i class="bi bi-arrow-down-right"></i> {{i['total_receive']}} GB</p>
<p class="text-success" style="text-transform: uppercase; display: inline-block; margin-bottom: 0"><i class="bi bi-arrow-up-right"></i> {{i['total_sent']}} GB</p>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm">
<small class="text-muted"><strong>PEER</strong></small>
<h6><samp class="ml-auto">{{i['id']}}</samp></h6>
<small class="text-muted" style="display: flex">
<strong>PEER</strong>
<strong style="margin-left: auto!important; opacity: 0; transition: 0.2s ease-in-out" class="text-primary">CLICK TO COPY</strong></small>
<h6><samp class="ml-auto key">{{i['id']}}</samp></h6>
</div>
<div class="col-sm">
<small class="text-muted"><strong>ALLOWED IP</strong></small>
@ -101,20 +138,39 @@
<small class="text-muted"><strong>LATEST HANDSHAKE</strong></small>
<h6 style="text-transform: uppercase;">{{i['latest_handshake']}}</h6>
</div>
<div class="w-100"></div>
<div class="col-sm">
<small class="text-muted"><strong>END POINT</strong></small>
<h6 style="text-transform: uppercase;">{{i['endpoint']}}</h6>
</div>
<div class="w-100"></div>
<div class="col-sm">
<div class="button-group">
<hr>
<div class="button-group" style="display:flex">
<button type="button" class="btn btn-outline-primary btn-setting-peer btn-control" id="{{i['id']}}" data-toggle="modal"><i class="bi bi-gear-fill"></i></button>
<button type="button" class="btn btn-outline-danger btn-delete-peer btn-control" id="{{i['id']}}" data-toggle="modal"><i class="bi bi-x-circle-fill"></i></button>
{% if i['private_key'] %}
<div class="share_peer_btn_group" style="margin-left: auto !important; display: inline">
<button type="button" class="btn btn-outline-success btn-qrcode-peer btn-control" img_src="{{ qrcode("[Interface]\nPrivateKey = "+i['private_key']+"\nAddress = "+i['allowed_ip']+"\nDNS = "+i['DNS']+"\n\n[Peer]\nPublicKey = "+conf_data['public_key']+"\nAllowedIPs = "+i['endpoint_allowed_ip']+"\nEndpoint = "+wg_ip+":"+conf_data['listen_port']) }}">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="width: 19px;" fill="#28a745"><path d="M3 11h8V3H3v8zm2-6h4v4H5V5zM3 21h8v-8H3v8zm2-6h4v4H5v-4zM13 3v8h8V3h-8zm6 6h-4V5h4v4zM13 13h2v2h-2zM15 15h2v2h-2zM13 17h2v2h-2zM17 17h2v2h-2zM19 19h2v2h-2zM15 19h2v2h-2zM17 13h2v2h-2zM19 15h2v2h-2z"/></svg>
</button>
<a href="/download/{{ conf_data['name'] }}?id={{ i['id']|urlencode }}" class="btn btn-outline-info btn-download-peer btn-control">
<i class="bi bi-download"></i>
</a>
</div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{%endfor%}
</div>
</main>

View File

@ -1,10 +1,10 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Wireguard Dashboard</title>
<link rel="icon" href="{{ url_for('static',filename='logo.png') }}"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='dashboard.css') }}">
<title>Wireguard Dashboard | {{ title }}</title>
<link rel="icon" href="{{ url_for('static',filename='img/logo.png') }}"/>
<link rel="stylesheet" href="{{ url_for('static',filename='css/bootstrap.min.css') }}">
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='css/dashboard.css') }}">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>

View File

@ -1,5 +1,9 @@
<html>
{% include "header.html" %}
{% with %}
{% set title="Home" %}
{% include "header.html"%}
{% endwith %}
<body>
{% include "navbar.html" %}
<div class="container-fluid">

View File

@ -5,3 +5,6 @@
<span class="navbar-toggler-icon"></span>
</button>
</nav>
<div class="progress" style="height: 3px; position: fixed; width: 100%; z-index: 10000; background-color: transparent">
<div class="progress-bar" role="progressbar" style="z-index: 10000; width: 0%"></div>
</div>

View File

@ -1,12 +1,15 @@
<html>
{% include "header.html" %}
<body>
{% include "navbar.html" %}
<div class="container-fluid">
{% with %}
{% set title="Settings" %}
{% include "header.html"%}
{% endwith %}
<body>
{% include "navbar.html" %}
<div class="container-fluid">
{% include "sidebar.html" %}
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4">
<div class="setting-container mt-4">
{% if message != ""%}
{% if message != "" %}
<div class="alert alert-{{ status }}" role="alert">
{{ message }}
</div>
@ -17,24 +20,47 @@
<form action="/update_acct" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control mb-4" id="username" name="username" value="{{ session['username'] }}">
<button type="submit" class="btn btn-success" >Update Account</button>
<input type="text" class="form-control mb-4" id="username" name="username"
value="{{ session['username'] }}" required>
<button type="submit" class="btn btn-success">Update Account</button>
</div>
</form>
<hr>
<h3>New Peer Default Settings</h3>
<form action="/update_peer_default_config" method="post">
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="username">DNS</label>
<input type="text" class="form-control mb-4" id="peer_global_DNS" name="peer_global_DNS"
value="{{ peer_global_DNS }}" required>
</div>
<div class="col-sm">
<label for="username">Peer Endpoint Allowed IPs</label>
<input type="text" class="form-control mb-4" id="peer_endpoint_allowed_ip" name="peer_endpoint_allowed_ip"
value="{{ peer_endpoint_allowed_ip }}" required>
</div>
</div>
<button class="btn btn-success" type="submit">Update Peer Default Settings</button>
</div>
</form>
<hr>
<h3>WireGuard Configuration Path</h3>
<form action="/update_wg_conf_path" method="post" class="update_wg_conf_path">
<div class="form-group">
<label for="username">Path</label>
<input type="text" class="form-control mb-4" id="wg_conf_path" name="wg_conf_path" value="{{ wg_conf_path }}">
<p>Remember to remove <code>/</code> at the end of your path. e.g <code>/etc/wireguard</code></p>
<input type="text" class="form-control mb-4" id="wg_conf_path" name="wg_conf_path"
value="{{ wg_conf_path }}">
<p>Remember to remove <code>/</code> at the end of your path. e.g <code>/etc/wireguard</code>
</p>
<button class="btn btn-danger change_path">Update Path & Restart Dashboard</button>
</div>
</form>
<hr>
<h3>Security</h3>
<form action="/update_pwd", method="post">
<form action="/update_pwd" , method="post">
<div class="form-group">
<label for="currentpass">Current Password</label>
<input type="password" class="form-control mb-2" id="currentpass" name="currentpass">
@ -52,22 +78,27 @@
<div class="form-group">
<div class="row">
<div class="col-sm">
<label for="app_ip" >Dashboard IP</label>
<label for="app_ip">Dashboard IP</label>
<input type="text" class="form-control mb-2" id="app_ip" name="app_ip" value="{{ app_ip }}">
<p><small class="text-danger mb-4">0.0.0.0 means it can be access by anyone with your server IP Address.</small></p>
<p><small class="text-danger mb-4">0.0.0.0 means it can be access by anyone with your server
IP Address.</small></p>
</div>
<div class="col-sm">
<label for="app_port">Dashboard Port</label>
<input type="text" class="form-control mb-4" id="app_port" name="app_port" value="{{ app_port }}">
<input type="text" class="form-control mb-4" id="app_port" name="app_port"
value="{{ app_port }}">
</div>
</div>
<button type="button" class="btn btn-danger confirm_modal" data-toggle="modal" data-target="#confirmModal">Update Configuration & Restart</button>
<button type="button" class="btn btn-danger confirm_modal" data-toggle="modal"
data-target="#confirmModal">Update Configuration & Restart
</button>
</div>
</form>
</div>
</main>
<!-- Modal -->
<div class="modal fade" id="confirmModal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal fade" id="confirmModal" data-backdrop="static" data-keyboard="false" tabindex="-1"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
@ -90,41 +121,41 @@
</div>
</div>
</div>
</div>
</body>
</div>
</body>
{% include "footer.html" %}
<script>
$(".sb-settings-url").addClass("active")
$(".confirm_modal").click(function (){
$(".confirm_modal").click(function () {
$(".app_new_ip").html($("#app_ip")[0].value)
$(".app_new_port").html($("#app_port")[0].value)
})
$(".confirm_restart").click(function (){
$(".confirm_restart").click(function () {
$(".cancel_restart").remove()
countdown = 7;
$.post('/update_app_ip_port', $('.update_app_ip_port').serialize())
url = $("#app_ip")[0].value+":"+$("#app_port")[0].value;
url = $("#app_ip")[0].value + ":" + $("#app_port")[0].value;
$(".confirm_restart").attr("disabled", "disabled")
setInterval(function (){
if (countdown === 0){
window.location.replace("http://"+url);
setInterval(function () {
if (countdown === 0) {
window.location.replace("http://" + url);
}
$(".confirm_restart").html("Redirecting you in "+countdown+" seconds.")
$(".confirm_restart").html("Redirecting you in " + countdown + " seconds.")
countdown--;
},1000)
}, 1000)
});
$(".change_path").click(function (){
$(".change_path").click(function () {
$(this).attr("disabled", "disabled");
countdown = 5;
setInterval(function (){
if (countdown === 0){
setInterval(function () {
if (countdown === 0) {
location.reload()
}
$(".change_path").html("Redirecting you in "+countdown+" seconds.")
$(".change_path").html("Redirecting you in " + countdown + " seconds.")
countdown--;
},1000)
}, 1000)
$.post('/update_wg_conf_path', $('.update_wg_conf_path').serialize())
});

View File

@ -5,7 +5,7 @@
<title>Wireguard Dashboard | Login</title>
<link rel="icon" href="{{ url_for('static',filename='logo.png') }}"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='dashboard.css') }}">
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='css/dashboard.css') }}">
</head>
<body>
{% include "navbar.html" %}

11
src/wg-dashboard.service Normal file
View File

@ -0,0 +1,11 @@
[Unit]
After=netword.service
[Service]
WorkingDirectory=<your dashboard directory full path here>
ExecStart=/usr/bin/python3 <your dashboard directory full path here>dashboard.py
Restart=always
[Install]
WantedBy=default.target

4
src/wgd.sh Normal file → Executable file
View File

@ -93,9 +93,9 @@ if [ "$#" != 1 ];
stop_wgd
sleep 2
printf "Wireguard Dashboard is stopped. \n"
start_wgd_debug
start_wgd
else
start_wgd_debug
start_wgd
fi
elif [ "$1" = "debug" ]; then
if check_wgd_status; then