Compare commits

...

51 Commits

Author SHA1 Message Date
Donald Zou
c32ccfc9ed Merge pull request #51 from donaldzou/v2.2.1
V2.2.1
2021-08-16 15:29:49 -04:00
Donald Cheng Hong Zou
ef818388c8 Update dashboard.py 2021-08-16 15:28:43 -04:00
Donald Cheng Hong Zou
f5aa45a3e1 Update README.md 2021-08-16 15:27:10 -04:00
Donald Cheng Hong Zou
b7a047a743 Bug fixed 2021-08-16 15:26:15 -04:00
Donald Zou
05ec985453 Update README.md 2021-08-16 12:23:56 -04:00
Donald Cheng Hong Zou
88ed9c3e79 Update README.md 2021-08-15 02:23:35 -04:00
Donald Zou
3fb03c8dfe Update README.md 2021-08-15 00:16:36 -04:00
Donald Zou
ff304027cd Merge pull request #46 from donaldzou/v2.2-beta
V2.2 pull request
2021-08-14 23:57:07 -04:00
Donald Cheng Hong Zou
3140d46c94 Finalizing the documentation 2021-08-14 23:43:30 -04:00
Donald Cheng Hong Zou
9d476af384 v2.2beta almost done!!!!! 2021-08-14 23:30:05 -04:00
Donald Cheng Hong Zou
0d380672f3 v2.2 beta 4 2021-08-14 17:13:16 -04:00
Donald Cheng Hong Zou
e2fb8dca5b Update README.md 2021-08-06 00:08:30 -04:00
Donald Cheng Hong Zou
eaba4c90c5 Edit Readme 2021-08-06 00:00:32 -04:00
Donald Cheng Hong Zou
b4ca7373f3 Update Readme 2021-08-05 23:47:18 -04:00
Donald Cheng Hong Zou
905c068ed5 v2.2-beta4
Finished testing the QR code function and finish debugging the peer file download function.
2021-08-05 23:15:50 -04:00
Donald Cheng Hong Zou
02886dd420 Remove public and private key txt 2021-08-05 01:39:32 -04:00
Donald Cheng Hong Zou
5bf7754d6c Update README.md 2021-08-05 01:21:44 -04:00
Donald Cheng Hong Zou
7a0a3055c4 Update README.md 2021-08-05 01:16:22 -04:00
Donald Cheng Hong Zou
bf73efb3b4 Update README.md 2021-08-05 01:15:17 -04:00
Donald Cheng Hong Zou
b4da212158 Update README.md 2021-08-05 01:07:10 -04:00
Donald Cheng Hong Zou
4a04d42600 v2.2-beta3
Finished QR code function and starting to test.
2021-08-05 00:45:15 -04:00
Donald Cheng Hong Zou
42bbfbe538 v2.2-beta update 2021-08-03 18:45:40 -04:00
Donald Cheng Hong Zou
31ec2430c4 Update README.md 2021-08-03 18:06:43 -04:00
Donald Cheng Hong Zou
f0b56c9f1d Update README.md 2021-08-03 18:06:22 -04:00
Donald Zou
6f9f01c991 Update README.md 2021-07-12 16:35:07 -04:00
Donald Cheng Hong Zou
b822ccb19d Update README.md 2021-07-11 13:07:27 -04:00
Donald Zou
dcb11671f3 Update README.md 2021-07-11 12:49:58 -04:00
Donald Zou
282599d36f Update README.md 2021-07-05 16:09:02 -04:00
Donald Zou
f11acdc68f Update README.md 2021-07-05 15:35:23 -04:00
Donald Zou
971e127cfd Update README.md 2021-07-03 10:30:54 -04:00
Donald Zou
9b2c59d529 Delete wg0.conf 2021-07-02 14:35:34 -04:00
Donald Zou
14dc049a66 Update README.md 2021-07-02 14:31:33 -04:00
Donald Zou
d3d0e7c615 Merge pull request #24 from donaldzou/v2.1-beta
v2.1 Merge
2021-07-02 13:28:36 -04:00
Donald Zou
89423ccb8b Merge branch 'main' into v2.1-beta 2021-07-02 13:28:29 -04:00
Donald Cheng Hong Zou
746f31f70c Update README.md 2021-07-02 13:25:35 -04:00
Donald Cheng Hong Zou
3aa9eab2bd Commit June 2 2021-07-02 13:23:04 -04:00
Donald Zou
1bcc8fed5e Update README.md 2021-07-02 12:00:12 -04:00
Donald Zou
1213a030e3 Update README.md 2021-05-13 19:54:37 -04:00
Donald Zou
3b2344b477 Delete .github/workflows directory 2021-05-13 19:51:54 -04:00
Donald Zou
c53b0fe2d4 Create main.yml 2021-05-13 19:38:22 -04:00
Donald Cheng Hong Zou
0a92269456 v2.0-beta-6 Commit 2021-05-13 18:47:59 -04:00
Donald Cheng Hong Zou
1cb8906893 v2.0-beta-6 Commit 2021-05-13 18:21:10 -04:00
Donald Cheng Hong Zou
f76579fe5e v2.0-beta-6 Commit 2021-05-13 18:00:40 -04:00
Donald Zou
db05ff5e98 Update README.md 2021-05-08 12:35:22 -04:00
Donald Zou
a05d6979ec Update README.md 2021-05-07 15:27:37 -04:00
Donald Zou
be40d17172 Update README.md 2021-05-07 15:25:23 -04:00
Donald Zou
9e11339979 Update README.md 2021-05-06 11:20:28 -04:00
Donald Zou
a56129afe0 Update README.md 2021-05-05 17:25:23 -04:00
Donald Zou
8933ea999c Update README.md 2021-05-05 15:52:13 -04:00
Donald Zou
ae3b8f6494 Merge pull request #19 from donaldzou/v2.0-beta-6
v2.0 merge to main
2021-05-05 15:29:41 -04:00
Donald Cheng Hong Zou
33487ee03f v2.0-beta-6 Commit 2021-05-05 15:16:32 -04:00
49 changed files with 9210 additions and 704 deletions

5
.gitignore vendored
View File

@@ -8,5 +8,8 @@ src/test.py
tmp
__pycache__
src/wg-dashboard.ini
src/wg-dashboard.ini
src/static/pic.xd
*.conf
private_key.txt
public_key.txt

440
README.md
View File

@@ -1,171 +1,417 @@
<hr>
<p align=center>Please provide your OS name and version if you can run the dashboard on it perfectly in <a href="https://github.com/donaldzou/wireguard-dashboard/issues/31">#31</a>, since I only tested on Ubuntu. Thank you!</p>
<hr>
<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>
<p align="center">
<img src="http://ForTheBadge.com/images/badges/made-with-python.svg">
</p>
<p align="center">
<a href="https://github.com/donaldzou/wireguard-dashboard/releases/latest"><img src="https://img.shields.io/github/v/release/donaldzou/wireguard-dashboard"></a>
</p>
<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>
<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 v2.2
## 📣 What's New: Version 2.0
### ⚠️ **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.0` to get the new update inside `Wireguard-Dashboard` directory.
3. Proceed **Step 2 & 3** in the Install step down below.
- 🎉 **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>
- 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!***
## Table of Content
- 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!
- [💡 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
- **No need to re-configure existing WireGuard configuration! It can search for existed configuration files.**
- 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!**
- Manage peer
- Delete peers
- And many more coming up! Welcome to contribute to this project!
## 📝 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!
- 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,
# or if you just want it to monitor your WireGuard Interface and don't need to
# make any changes with the dashboard, you can set it to false.
[Peer]
PublicKey = abcd1234
AllowedIPs = 1.2.3.4/32
# Must have for each peer
```
- **Note: For peers, `PublicKey` & `AllowedIPs` is required.**
- Python 3.7+ & Pip3
```
$ sudo apt-get install python3 python3-pip
```
## 🛠 Install
1. **Download Wireguard Dashboard**
1. Download Wireguard Dashboard
```shell
git clone -b v2.2 https://github.com/donaldzou/wireguard-dashboard.git
2. Open the Wireguard Dashboard folder
```
$ git clone -b v2.0 https://github.com/donaldzou/Wireguard-Dashboard.git
```
```shell
cd wireguard-dashboard/src
```
3. Install Python Dependencies
**2. Install Python Dependencies**
```shell
python3 -m pip install -r requirements.txt
```
```
$ cd Wireguard-Dashboard/src
$ 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`
**3. Install & run Wireguard Dashboard**
```shell
sudo chmod -R 744 /etc/wireguard
```
```
$ sudo sh wgd.sh start
```
5. Install & run Wireguard 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.
```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`.
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
```
$ cd Wireguard-Dashboard/src
$ sudo sh wgd.sh start # Start the dashboard in background
$ sudo sh wgd.sh debug # Start the dashboard in foreground (debug mode)
$ sudo sh wgd.sh stop # Stop the dashboard
$ sudo sh wgd.sh restart # Restart the dasboard
$ sudo sh wgd.sh update # Update the dashboard
```shell
cd Wireguard-Dashboard/src
-----------------------------
./wgd.sh start # Start the dashboard in background
-----------------------------
./wgd.sh debug # Start the dashboard in foreground (debug mode)
-----------------------------
./wgd.sh stop # Stop the dashboard
-----------------------------
./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:
### `[Account]`
| | 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 |
`username` - Username (Default: `admin`)
<p align=center>Latest Version: v2.2</p>
`password` - Password, will be hash with SHA256 (Default: `admin`).
**Except `auth_req` due to security consideration.**
### `[Server]`
#### Generating QR code and peer configuration file (.conf)
`wg_conf_path` - The path of all the Wireguard configurations (Default: `/etc/wireguard`)
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:
`app_ip` - IP address the flask will run with (Default: `0.0.0.0`)
`app_port` - Port the flask will run with (Default: `10086`)
`auth_req` - Does the dashboard need authentication (Default: `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
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.**
```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. | Yes |
| `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>` | Yes |
## ❓ How to update the dashboard?
```
$ cd wireguard-dashboard
$ sudo sh wgd.sh update # Perform update
$ sudo sh wgd.sh start # Start dashboard
```
1. Change your directory to `wireguard-dashboard`
```shell
cd wireguard-dashboard
```
2. Get the newest version
```shell
sudo git stash
sudo git pull https://github.com/donaldzou/wireguard-dashboard.git v2.2 --force
```
3. Update and install all python dependencies
```shell
python3 -m pip install -r requirements.txt
```
4. Start the dashboard
```shell
./wgd.sh start
```
## 🔍 Screenshot
![Index Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/index.png)
![Sign In Page](img/SignIn.png)
<p align=center>Index Page</p>
![Index Image](img/HomePage.png)
![Signin Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/signin.png)
![Configuration](img/Configuration.png)
<p align=center>Signin Page</p>
![Add Peer](img/AddPeer.png)
![Configuration Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/configuration.png)
![Edit Peer](img/EditPeer.png)
<p align=center>Configuration Page</p>
![Delete Peer](img/DeletePeer.png)
![Settings Image](https://github.com/donaldzou/Wireguard-Dashboard/raw/main/src/static/settings.png)
![Dashboard Setting](img/DashboardSetting.png)
<p align=center>Settings Page</p>
![Ping](img/Ping.png)
## Contributors ✨
![Traceroute](img/Traceroute.png)
## ⏰ 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
- [Bootstrap](https://getbootstrap.com/docs/4.6/getting-started/introduction/) `v4.6.0`
- [Bootstrap Icon](https://icons.getbootstrap.com) `v1.4.0`
- [jQuery](https://jquery.com) `v3.5.1`
- Python
- [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
<!-- 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

@@ -1,37 +1,45 @@
dashboard_version = 'v2.0'
# Python Built-in Library
import os
from flask import Flask, request, render_template, redirect, url_for, session, abort
from flask import Flask, request, render_template, redirect, url_for, session, abort, jsonify
import subprocess
from datetime import datetime, date, time, timedelta
import time
from operator import itemgetter
import secrets
import hashlib
import json, urllib.request
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.2.1'
# 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
conf_data = {}
# Enable QR Code Generator
QRcode(app)
def get_conf_peer_key(config_name):
keys = []
try:
peer_key = subprocess.check_output("wg show " + config_name + " peers", shell=True)
peer_key = peer_key.decode("UTF-8").split()
return peer_key
except Exception:
return "stopped"
peer_key = peer_key.decode("UTF-8").split()
for i in peer_key: keys.append(i)
return keys
return config_name + " is not running."
def get_conf_running_peer_number(config_name):
@@ -52,9 +60,32 @@ def get_conf_running_peer_number(config_name):
count += 2
return running
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"
conf_location = wg_conf_path + "/" + config_name + ".conf"
f = open(conf_location, 'r')
file = f.read().split("\n")
conf_peer_data = {
@@ -63,73 +94,59 @@ def read_conf_file(config_name):
}
peers_start = 0
for i in range(len(file)):
if file[i] == "[Peer]":
peers_start = i
break
else:
if len(file[i]) > 0:
if file[i] != "[Interface]":
tmp = file[i].replace(" ", "").split("=", 1)
if len(tmp) == 2:
conf_peer_data['Interface'][tmp[0]] = tmp[1]
if not is_match("#(.*)", file[i]):
if file[i] == "[Peer]":
peers_start = i
break
else:
if len(file[i]) > 0:
if file[i] != "[Interface]":
tmp = re.split(r'\s*=\s*', file[i], 1)
if len(tmp) == 2:
conf_peer_data['Interface'][tmp[0]] = tmp[1]
conf_peers = file[peers_start:]
peer = -1
for i in conf_peers:
if i == "[Peer]":
peer += 1
conf_peer_data["Peers"].append({})
else:
if len(i) > 0:
tmp = i.replace(" ", "").split("=", 1)
if len(tmp) == 2:
conf_peer_data["Peers"][peer][tmp[0]] = tmp[1]
if not is_match("#(.*)", i):
if i == "[Peer]":
peer += 1
conf_peer_data["Peers"].append({})
elif peer > -1:
if len(i) > 0:
tmp = re.split('\s*=\s*', i, 1)
if len(tmp) == 2:
conf_peer_data["Peers"][peer][tmp[0]] = tmp[1]
f.close()
# Read Configuration File End
return conf_peer_data
def get_latest_handshake(config_name, db, peers):
# Get latest handshakes
try:
data_usage = subprocess.check_output("wg show " + config_name + " latest-handshakes", shell=True)
except Exception:
return "stopped"
data_usage = data_usage.decode("UTF-8").split()
count = 0
now = datetime.now()
b = timedelta(minutes=2)
for i in range(int(len(data_usage) / 2)):
minus = now - datetime.fromtimestamp(int(data_usage[count + 1]))
if minus < b:
status = "running"
else:
status = "stopped"
if int(data_usage[count + 1]) > 0:
db.update({"latest_handshake": str(minus).split(".")[0], "status": status},
peers.id == data_usage[count])
else:
db.update({"latest_handshake": "(None)", "status": status}, peers.id == data_usage[count])
count += 2
def get_conf_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']):
db.insert({
"id": i['PublicKey'],
"name": "",
"total_receive": 0,
"total_sent": 0,
"total_data": 0,
"endpoint": 0,
"status": 0,
"latest_handshake": 0,
"allowed_ip": 0,
"traffic": []
})
# Get latest handshakes
try:
data_usage = subprocess.check_output("wg show " + config_name + " latest-handshakes", shell=True)
except Exception:
return "stopped"
data_usage = data_usage.decode("UTF-8").split()
count = 0
now = datetime.now()
b = timedelta(minutes=2)
for i in range(int(len(data_usage) / 2)):
minus = now - datetime.fromtimestamp(int(data_usage[count + 1]))
if minus < b:
status = "running"
else:
status = "stopped"
if int(data_usage[count + 1]) > 0:
db.update({"latest_handshake": str(minus).split(".")[0], "status": status},
peers.id == data_usage[count])
else:
db.update({"latest_handshake": "(None)", "status": status}, peers.id == data_usage[count])
count += 2
def get_transfer(config_name, db, peers):
# Get transfer
try:
data_usage = subprocess.check_output("wg show " + config_name + " transfer", shell=True)
@@ -141,28 +158,30 @@ def get_conf_peers_data(config_name):
cur_i = db.search(peers.id == data_usage[count])
total_sent = cur_i[0]['total_sent']
total_receive = cur_i[0]['total_receive']
traffic = cur_i[0]['traffic']
cur_total_sent = round(int(data_usage[count + 2]) / (1024 ** 3), 4)
cur_total_receive = round(int(data_usage[count + 1]) / (1024 ** 3), 4)
if cur_i[0]["status"] == "running":
if total_sent <= cur_total_sent:
if total_sent <= cur_total_sent and total_receive <= cur_total_receive:
total_sent = cur_total_sent
else: total_sent += cur_total_sent
if total_receive <= cur_total_receive:
total_receive = cur_total_receive
else: total_receive += cur_total_receive
db.update({"total_receive": round(total_receive,4),
"total_sent": round(total_sent,4),
else:
now = datetime.now()
ctime = now.strftime("%d/%m/%Y %H:%M:%S")
traffic.append(
{"time": ctime, "total_receive": round(total_receive, 4), "total_sent": round(total_sent, 4),
"total_data": round(total_receive + total_sent, 4)})
total_sent = 0
total_receive = 0
db.update({"traffic": traffic}, peers.id == data_usage[count])
db.update({"total_receive": round(total_receive, 4),
"total_sent": round(total_sent, 4),
"total_data": round(total_receive + total_sent, 4)}, peers.id == data_usage[count])
# Will get implement in the future
# traffic = db.search(peers.id == data_usage[count])[0]['traffic']
# traffic.append({"time": current_time, "total_receive": round(int(data_usage[count + 1]) / (1024 ** 3), 4),
# "total_sent": round(int(data_usage[count + 2]) / (1024 ** 3), 4)})
# db.update({"traffic": traffic}, peers.id == data_usage[count])
count += 3
def get_endpoint(config_name, db, peers):
# Get endpoint
try:
data_usage = subprocess.check_output("wg show " + config_name + " endpoints", shell=True)
@@ -174,16 +193,68 @@ def get_conf_peers_data(config_name):
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"])
db.update({"allowed_ip": i.get('AllowedIPs', '(None)')}, peers.id == i["PublicKey"])
def get_peers(config_name):
get_conf_peers_data(config_name)
def get_all_peers_data(config_name):
db = TinyDB('db/' + config_name + '.json')
result = db.all()
result = sorted(result, key=lambda d: d['status'])
peers = Query()
conf_peer_data = read_conf_file(config_name)
for i in conf_peer_data['Peers']:
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,
"total_data": 0,
"endpoint": 0,
"status": 0,
"latest_handshake": 0,
"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)
get_transfer(config_name, db, peers)
get_endpoint(config_name, db, peers)
get_allowed_ip(config_name, db, peers, conf_peer_data)
toc = time.perf_counter()
print(f"Finish fetching data in {toc - tic:0.4f} seconds")
db.close()
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()
else:
result = db.search(peer.name.matches('(.*)(' + re.escape(search) + ')(.*)'))
result = sorted(result, key=lambda d: d[sort_t])
db.close()
return result
@@ -209,9 +280,15 @@ def get_conf_total_data(config_name):
upload_total = 0
download_total = 0
for i in db.all():
upload_total += round(i['total_sent'],4)
download_total += round(i['total_receive'],4)
upload_total += i['total_sent']
download_total += i['total_receive']
for k in i['traffic']:
upload_total += k['total_sent']
download_total += k['total_receive']
total = round(upload_total + download_total, 4)
upload_total = round(upload_total, 4)
download_total = round(download_total, 4)
db.close()
return [total, upload_total, download_total]
@@ -226,20 +303,100 @@ 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:
i = i.replace('.conf', '')
temp = {"conf": i, "status": get_conf_status(i), "public_key": get_conf_pub_key(i)}
# get_conf_peers_data(i)
if temp['status'] == "running":
temp['checked'] = 'checked'
else:
temp['checked'] = ""
conf.append(temp)
conf = sorted(conf, key=itemgetter('conf'))
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":
temp['checked'] = 'checked'
else:
temp['checked'] = ""
conf.append(temp)
if len(conf) > 0:
conf = sorted(conf, key=itemgetter('conf'))
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|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|"+
"18|19|20|21|22|23|24|25|26|27|28|29|30|31|32)(,|$)", ip)
def checkAllowedIPs(ip):
ip = cleanIpWithRange(ip)
for i in ip:
if not checkIpWithRange(i): return False
return True
@app.before_request
@@ -255,13 +412,18 @@ def auth_req():
request.endpoint != "signout" and \
request.endpoint != "auth" and \
"username" not in session:
print("not loggedin")
session['message'] = "You need to sign in first!"
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', 'update_app_ip_port', 'update_wg_conf_path']:
if request.endpoint in ['signin', 'signout', 'auth', 'settings', 'update_acct', 'update_pwd',
'update_app_ip_port', 'update_wg_conf_path']:
return redirect(url_for("index"))
@app.route('/signin', methods=['GET'])
def signin():
message = ""
@@ -279,7 +441,6 @@ def signout():
return render_template('signin.html', message=message)
@app.route('/settings', methods=['GET'])
def settings():
message = ""
@@ -292,14 +453,20 @@ def settings():
session.pop("message")
session.pop("message_status")
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"))
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"),
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'])
def auth():
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
password = hashlib.sha256(request.form['password'].encode())
if password.hexdigest() == config["Account"]["password"] and request.form['username'] == config["Account"]["username"]:
if password.hexdigest() == config["Account"]["password"] and request.form['username'] == config["Account"][
"username"]:
session['username'] = request.form['username']
config.clear()
return redirect(url_for("index"))
@@ -308,8 +475,13 @@ def auth():
config.clear()
return redirect(url_for("signin"))
@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'])
@@ -326,12 +498,53 @@ def update_acct():
config.clear()
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)
config.read(dashboard_conf)
if hashlib.sha256(request.form['currentpass'].encode()).hexdigest() == config.get("Account", "password"):
if hashlib.sha256(request.form['newpass'].encode()).hexdigest() == hashlib.sha256(request.form['repnewpass'].encode()).hexdigest():
if hashlib.sha256(request.form['newpass'].encode()).hexdigest() == hashlib.sha256(
request.form['repnewpass'].encode()).hexdigest():
config.set("Account", "password", hashlib.sha256(request.form['repnewpass'].encode()).hexdigest())
try:
config.write(open(dashboard_conf, "w"))
@@ -355,6 +568,7 @@ def update_pwd():
config.clear()
return redirect(url_for("settings"))
@app.route('/update_app_ip_port', methods=['POST'])
def update_app_ip_port():
config = configparser.ConfigParser(strict=False)
@@ -365,6 +579,7 @@ def update_app_ip_port():
config.clear()
os.system('bash wgd.sh restart')
@app.route('/update_wg_conf_path', methods=['POST'])
def update_wg_conf_path():
config = configparser.ConfigParser(strict=False)
@@ -376,17 +591,96 @@ def update_wg_conf_path():
config.clear()
os.system('bash wgd.sh restart')
# @app.route('/check_update_dashboard', methods=['GET'])
# def check_update_dashboard():
# return have_update
@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)
config.read(dashboard_conf)
config.set("Server", "dashboard_refresh_interval", str(request.form['interval']))
config.write(open(dashboard_conf, "w"))
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'] + '">'
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>"
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)
returnjson = {
"address": result.address,
"is_alive": result.is_alive,
"min_rtt": result.min_rtt,
"avg_rtt": result.avg_rtt,
"max_rtt": result.max_rtt,
"package_sent": result.packets_sent,
"package_received": result.packets_received,
"package_loss": result.packet_loss
}
return jsonify(returnjson)
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)
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})
last_distance = hop.distance
return jsonify(returnjson)
except Exception:
return "Error"
@app.route('/', methods=['GET'])
def index():
print(request.referrer)
return render_template('index.html', conf=get_conf_list())
@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),
@@ -396,27 +690,43 @@ def conf(config_name):
conf_data['checked'] = "nope"
else:
conf_data['checked'] = "checked"
return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data)
config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf)
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")),
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):
db = TinyDB('db/' + config_name + '.json')
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'])
@@ -441,12 +751,27 @@ 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."
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:
@@ -454,23 +779,30 @@ def add_peer(config_name):
"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_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()
# return redirect('/configuration/'+config_name)
@app.route('/remove_peer/<config_name>', methods=['POST'])
def remove_peer(config_name):
if get_conf_status(config_name) == "stopped":
return "Your need to turn on "+config_name+" first."
return "Your need to turn on " + config_name + " first."
db = TinyDB("db/" + config_name + ".json")
peers = Query()
data = request.get_json()
delete_key = data['peer_id']
keys = get_conf_peer_key(config_name)
if type(keys) != list:
return config_name + " is not running."
if delete_key not in keys:
db.close()
return "This key does not exist"
else:
try:
@@ -478,31 +810,134 @@ def remove_peer(config_name):
stderr=subprocess.STDOUT)
status = subprocess.check_output("wg-quick save " + config_name, shell=True, stderr=subprocess.STDOUT)
db.remove(peers.id == delete_key)
db.close()
return "true"
except subprocess.CalledProcessError as exc:
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()
if len(db.search(peers.id == id)) == 1:
check_ip = checkAllowedIP(id, allowed_ip, config_name)
if not checkIpWithRange(endpoint_allowed_ip):
return jsonify({"status": "failed", "msg": "Endpoint Allowed IPs format is incorrect."})
db.update({"name": name}, peers.id == id)
return id + " " + 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 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']
db = TinyDB("db/" + config_name + ".json")
peers = Query()
result = db.search(peers.id == id)
return result[0]['name']
db.close()
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():
# Set Default INI File
@@ -517,7 +952,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']:
@@ -530,15 +964,29 @@ def init_dashboard():
config['Server']['auth_req'] = 'true'
if 'version' not in config['Server'] or config['Server']['version'] != dashboard_version:
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()
def check_update():
conf = configparser.ConfigParser(strict=False)
conf.read(dashboard_conf)
data = urllib.request.urlopen("https://api.github.com/repos/donaldzou/wireguard-dashboard/releases").read()
output = json.loads(data)
if conf.get("Server", "version") == output[0]["tag_name"]:
release = []
for i in output:
if i["prerelease"] == False: release.append(i)
if conf.get("Server", "version") == release[0]["tag_name"]:
return "false"
else:
return "true"
@@ -554,4 +1002,3 @@ if __name__ == "__main__":
wg_conf_path = config.get("Server", "wg_conf_path")
config.clear()
app.run(host=app_ip, debug=False, port=app_port)

View File

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

View File

@@ -1 +0,0 @@
!function(a){"use strict";function l(t,e){this.$element=a(t),this.options=a.extend({},this.defaults(),e),this.render()}l.VERSION="3.6.0",l.DEFAULTS={on:"On",off:"Off",onstyle:"primary",offstyle:"light",size:"normal",style:"",width:null,height:null},l.prototype.defaults=function(){return{on:this.$element.attr("data-on")||l.DEFAULTS.on,off:this.$element.attr("data-off")||l.DEFAULTS.off,onstyle:this.$element.attr("data-onstyle")||l.DEFAULTS.onstyle,offstyle:this.$element.attr("data-offstyle")||l.DEFAULTS.offstyle,size:this.$element.attr("data-size")||l.DEFAULTS.size,style:this.$element.attr("data-style")||l.DEFAULTS.style,width:this.$element.attr("data-width")||l.DEFAULTS.width,height:this.$element.attr("data-height")||l.DEFAULTS.height}},l.prototype.render=function(){this._onstyle="btn-"+this.options.onstyle,this._offstyle="btn-"+this.options.offstyle;var t="large"===this.options.size||"lg"===this.options.size?"btn-lg":"small"===this.options.size||"sm"===this.options.size?"btn-sm":"mini"===this.options.size||"xs"===this.options.size?"btn-xs":"",e=a('<label for="'+this.$element.prop("id")+'" class="btn">').html(this.options.on).addClass(this._onstyle+" "+t),s=a('<label for="'+this.$element.prop("id")+'" class="btn">').html(this.options.off).addClass(this._offstyle+" "+t),o=a('<span class="toggle-handle btn btn-light">').addClass(t),i=a('<div class="toggle-group">').append(e,s,o),l=a('<div class="toggle btn" data-toggle="toggle" role="button">').addClass(this.$element.prop("checked")?this._onstyle:this._offstyle+" off").addClass(t).addClass(this.options.style);this.$element.wrap(l),a.extend(this,{$toggle:this.$element.parent(),$toggleOn:e,$toggleOff:s,$toggleGroup:i}),this.$toggle.append(i);var n=this.options.width||Math.max(e.outerWidth(),s.outerWidth())+o.outerWidth()/2,h=this.options.height||Math.max(e.outerHeight(),s.outerHeight());e.addClass("toggle-on"),s.addClass("toggle-off"),this.$toggle.css({width:n,height:h}),this.options.height&&(e.css("line-height",e.height()+"px"),s.css("line-height",s.height()+"px")),this.update(!0),this.trigger(!0)},l.prototype.toggle=function(){this.$element.prop("checked")?this.off():this.on()},l.prototype.on=function(t){if(this.$element.prop("disabled"))return!1;this.$toggle.removeClass(this._offstyle+" off").addClass(this._onstyle),this.$element.prop("checked",!0),t||this.trigger()},l.prototype.off=function(t){if(this.$element.prop("disabled"))return!1;this.$toggle.removeClass(this._onstyle).addClass(this._offstyle+" off"),this.$element.prop("checked",!1),t||this.trigger()},l.prototype.enable=function(){this.$toggle.removeClass("disabled"),this.$toggle.removeAttr("disabled"),this.$element.prop("disabled",!1)},l.prototype.disable=function(){this.$toggle.addClass("disabled"),this.$toggle.attr("disabled","disabled"),this.$element.prop("disabled",!0)},l.prototype.update=function(t){this.$element.prop("disabled")?this.disable():this.enable(),this.$element.prop("checked")?this.on(t):this.off(t)},l.prototype.trigger=function(t){this.$element.off("change.bs.toggle"),t||this.$element.change(),this.$element.on("change.bs.toggle",a.proxy(function(){this.update()},this))},l.prototype.destroy=function(){this.$element.off("change.bs.toggle"),this.$toggleGroup.remove(),this.$element.removeData("bs.toggle"),this.$element.unwrap()};var t=a.fn.bootstrapToggle;a.fn.bootstrapToggle=function(o){var i=Array.prototype.slice.call(arguments,1)[0];return this.each(function(){var t=a(this),e=t.data("bs.toggle"),s="object"==typeof o&&o;e||t.data("bs.toggle",e=new l(this,s)),"string"==typeof o&&e[o]&&"boolean"==typeof i?e[o](i):"string"==typeof o&&e[o]&&e[o]()})},a.fn.bootstrapToggle.Constructor=l,a.fn.toggle.noConflict=function(){return a.fn.bootstrapToggle=t,this},a(function(){a("input[type=checkbox][data-toggle^=toggle]").bootstrapToggle()}),a(document).on("click.bs.toggle","div[data-toggle^=toggle]",function(t){a(this).find("input[type=checkbox]").bootstrapToggle("toggle"),t.preventDefault()})}(jQuery);

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,164 +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
}

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,336 @@
// 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");
$(this).removeAttr("disabled")
$(this).html("Save")
}
})
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");
$("#save_peer_setting").removeAttr("disabled")
$("#save_peer_setting").html("Save")
}
})
$(".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

68
src/static/js/tools.js Normal file
View File

@@ -0,0 +1,68 @@
$(".ip_dropdown").change(function (){
$(".modal.show .btn").removeAttr("disabled")
});
$(".conf_dropdown").change(function (){
$(".modal.show .ip_dropdown").html('<option value="none" selected="selected" disabled>Loading...')
$.ajax({
url: "/get_ping_ip",
method: "POST",
data: "config="+$(this).children("option:selected").val(),
success: function (res){
$(".modal.show .ip_dropdown").html("")
$(".modal.show .ip_dropdown").append('<option value="none" selected="selected" disabled>Choose an IP')
$(".modal.show .ip_dropdown").append(res)
}
})
});
// Ping Tools
$(".send_ping").click(function (){
$(this).attr("disabled","disabled")
$(this).html("Pinging...")
$("#ping_modal .form-control").attr("disabled","disabled")
$.ajax({
method:"POST",
data: "ip="+$(':selected', $("#ping_modal .ip_dropdown")).val()+"&count="+$("#ping_modal .ping_count").val(),
url: "/ping_ip",
success: function (res){
$(".ping_result tbody").html("")
html = '<tr><th scope="row">Address</th><td>'+res['address']+'</td></tr>' +
'<tr><th scope="row">Is Alive</th><td>'+res['is_alive']+'</td></tr>' +
'<tr><th scope="row">Min RTT</th><td>'+res['min_rtt']+'ms</td></tr>' +
'<tr><th scope="row">Average RTT </th><td>'+res['avg_rtt']+'ms</td></tr>' +
'<tr><th scope="row">Max RTT</th><td>'+res['max_rtt']+'ms</td></tr>' +
'<tr><th scope="row">Package Sent</th><td>'+res['package_sent']+'</td></tr>' +
'<tr><th scope="row">Package Received</th><td>'+res['package_received']+'</td></tr>' +
'<tr><th scope="row">Package Loss</th><td>'+res['package_loss']+'</td></tr>'
$(".ping_result tbody").html(html)
$(".send_ping").removeAttr("disabled")
$(".send_ping").html("Ping")
$("#ping_modal .form-control").removeAttr("disabled")
}
})
});
// Traceroute Tools
$(".send_traceroute").click(function (){
$(this).attr("disabled","disabled")
$(this).html("Tracing...");
$("#traceroute_modal .form-control").attr("disabled","disabled")
$.ajax({
url: "/traceroute_ip",
method: "POST",
data: "ip="+$(':selected', $("#traceroute_modal .ip_dropdown")).val(),
success: function (res){
$(".traceroute_result tbody").html("");
for (i in res){
$(".traceroute_result tbody").append('<tr><th scope="row">'+res[i]['hop']+'</th><td>'+res[i]['ip']+'</td><td>'+res[i]['avg_rtt']+'</td><td>'+res[i]['min_rtt']+'</td><td>'+res[i]['max_rtt']+'</td></tr>')
}
$(".send_traceroute").removeAttr("disabled");
$(".send_traceroute").html("Traceroute");
$("#traceroute_modal .form-control").removeAttr("disabled")
}
})
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

View File

@@ -1,18 +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 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>
<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>
@@ -26,15 +33,54 @@
<span aria-hidden="true">&times;</span>
</button>
</div>
<form>
<form id="add_peer_form">
<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">
<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</label>
<input type="text" class="form-control" id="public_key" aria-describedby="public_key">
</div>
<div class="form-group">
<label for="allowed_ips">Allowed IPs</label>
<input type="text" class="form-control" id="allowed_ips">
<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="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>
<div class="modal-footer">
@@ -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 class="mb-3">
<label for="peer_name" class="form-label">Name</label>
<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_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>
@@ -107,140 +193,64 @@
</div>
</div>
</div>
{% include "tools.html" %}
</body>
{% include "footer.html" %}
<script>
$(".sb-{{conf_data['name']}}-url").addClass("active");
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(){
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);
$("#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();
}, 15000)
load_data($('#search_peer_textbox').val());
}, {{dashboard_refresh_interval}})
});
</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()}),
success: function (response){
if(response != "true"){
$("#add_peer_alert").html(response+$("#add_peer_alert").html());
$("#add_peer_alert").removeClass("d-none");
}
else{
location.reload();
}
}
})
}
})
$("body").on("click", ".btn-delete-peer", function(){
var peer_id = $(this).attr("id");
$("#delete_peer").attr("peer_id", peer_id);
})
$(".btn-delete-peer").click(function(){
});
$("#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{
location.reload();
}
}
})
});
var myModal = new bootstrap.Modal(document.getElementById('setting_modal'), {
keyboard: false
})
$("body").on("click", ".btn-setting-peer", function(){
myModal.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){
myModal.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,8 +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='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

@@ -1,4 +1,4 @@
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4 mt-4">
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4 mt-4 mb-4">
<div class="info mt-4">
<div class="row">
<div class="col">
@@ -39,81 +39,138 @@
</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>
<hr>
<div class="button-div" style="text-align: right;">
<button type="button" class="btn btn-outline-primary btn-sm mb-3" data-toggle="modal" data-target="#add_modal">
<strong>ADD PEER</strong>
</button>
</div>
</div>
{% for i in conf_data['peer_data']%}
<div class="card mb-3">
<div class="card-header">
<div class="row">
<div class="col">
<div class="card-header-body ">
{% if not i['name']%}
{{ "Untitled Peer" }}
{% else %}
{{i['name']}}
{% endif %}
<span class="dot dot-{{i['status']}}"></span>
</div>
</div>
<div class="col" style="text-align: right">
<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>STATUS</strong></small>#}
{# <h6 style="text-transform: uppercase;">{{i['status']}}<span class="dot dot-{{i['status']}}"></span></h6>#}
{# </div>#}
<div class="col-sm">
<small class="text-muted"><strong>PEER</strong></small>
<h6><samp class="ml-auto">{{i['id']}}</samp></h6>
</div>
<div class="col-sm">
<small class="text-muted"><strong>ALLOWED IP</strong></small>
<h6 style="text-transform: uppercase;">{{i['allowed_ip']}}</h6>
</div>
<div class="w-100"></div>
<div class="col-sm">
<small class="text-muted"><strong>LATEST HANDSHAKE</strong></small>
<h6 style="text-transform: uppercase;">{{i['latest_handshake']}}</h6>
</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">
<!-- <small class="text-muted"><strong>ACTION</strong></small> -->
<div class="button-group">
<hr>
<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" data-target="#delete_modal"><i class="bi bi-x-circle-fill"></i></button>
</div>
</div>
</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>
{%endfor%}
<hr>
<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>
</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-12">
<div class="card-header-body ">
{% if not i['name']%}
{{ "Untitled Peer" }}
{% else %}
{{i['name']}}
{% endif %}
<span class="dot dot-{{i['status']}}"></span>
</div>
</div>
<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" 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>
<h6 style="text-transform: uppercase;">{{i['allowed_ip']}}</h6>
</div>
<div class="w-100"></div>
<div class="col-sm">
<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">
<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,13 +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') }}">
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<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">
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.1/dist/chart.min.js"></script>
</head>

View File

@@ -1,11 +1,18 @@
<html>
{% include "header.html" %}
{% with %}
{% set title="Home" %}
{% 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">
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-md-4 mb-4">
<h1 class="pb-4 mt-4">Home</h1>
{% if conf == [] %}
<p class="text-muted">You don't have any WireGuard configurations yet. Please check the configuration folder or change it in "Settings". By default the folder is "/etc/wireguard".</p>
{% endif %}
{% for i in conf%}
<div class="card mt-3">
<div class="card-body">
@@ -24,7 +31,7 @@
<small class="text-muted"><strong>PUBLIC KEY</strong></small>
<h6 style="text-transform: uppercase; margin:0 !important;"><samp>{{i['public_key']}}</samp></h6>
</div>
<div class="col-md">
<div class="col-md index-switch">
{% if i['checked'] == "checked" %}
<a href="#" id="{{i['conf']}}" {{i['checked']}} class="switch text-primary tt"><i class="bi bi-toggle2-on"></i></a>
{% else %}
@@ -40,6 +47,7 @@
{%endfor%}
</main>
</div>
{% include "tools.html" %}
</body>
{% include "footer.html" %}
<script>

View File

@@ -4,4 +4,7 @@
data-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
</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,39 +1,67 @@
<html>
{% include "header.html" %}
<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 != ""%}
<div class="alert alert-{{ status }}" role="alert">
{{ message }}
</div>
{% endif %}
<h1 class="pb-4">Settings</h1>
{% if required_auth == "true" %}
<h3>Account</h3>
<form action="/update_acct" method="post">
<div class="form-group">
{% 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 != "" %}
<div class="alert alert-{{ status }}" role="alert">
{{ message }}
</div>
{% endif %}
<h1 class="pb-4">Settings</h1>
{% if required_auth == "true" %}
<h3>Account</h3>
<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>
</form>
<hr>
<h3>WireGuard Configuration Path</h3>
<form action="/update_wg_conf_path" method="post" class="update_wg_conf_path">
<div class="form-group">
<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 }}">
<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">
<div class="form-group">
</div>
</form>
<hr>
<h3>Security</h3>
<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">
<label for="newpass">New Password</label>
@@ -41,37 +69,42 @@
<label for="repnewpass">Repeat New Password</label>
<input type="password" class="form-control mb-4" id="repnewpass" name="repnewpass">
<button type="submit" class="btn btn-danger">Update Password</button>
</div>
</form>
<hr>
{% endif %}
<h3>Dashboard Configuration</h3>
<form action="/update_app_ip_port" method="post" class="update_app_ip_port">
<div class="form-group">
<div class="row">
<div class="col-sm">
<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>
</div>
</form>
<hr>
{% endif %}
<h3>Dashboard Configuration</h3>
<form action="/update_app_ip_port" method="post" class="update_app_ip_port">
<div class="form-group">
<div class="row">
<div class="col-sm">
<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>
</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 }}">
</div>
</div>
<button type="button" class="btn btn-danger confirm_modal" data-toggle="modal" data-target="#confirmModal">Update Configuration & Restart</button>
<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 }}">
</div>
</form>
</div>
<button type="button" class="btn btn-danger confirm_modal" data-toggle="modal"
data-target="#confirmModal">Update Configuration & Restart
</button>
</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-dialog">
<div class="modal-content">
<div class="modal-header">
</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-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Confirm Dashboard Configuration</h5>
</div>
<div class="modal-body">
</div>
<div class="modal-body">
<small>Dashboard Original IP</small>
<p>{{ app_ip }}</p>
<small style="font-weight: bold" class="text-bold">Dashboard New IP</small>
@@ -80,49 +113,49 @@
<p>{{ app_port }}</p>
<small style="font-weight: bold" class="text-bold">Dashboard New Port</small>
<p class="app_new_port text-bold text-danger" style="font-weight: bold"></p>
</div>
<div class="modal-footer">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary cancel_restart" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger confirm_restart">Confirm & Restart Dashboard</button>
</div>
</div>
</div>
</div>
</div>
</body>
</div>
</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

@@ -8,7 +8,9 @@
<li class="nav-item"><a class="nav-link sb-settings-url" href="/settings">Settings</a></li>
{% endif %}
{% if session['update'] == "true" %}
<li class="nav-item sb-update-li"><a class="nav-link sb-update-url" href="https://github.com/donaldzou/wireguard-dashboard/#-how-to-update-the-dashboard">New Update Available!<span class="dot dot-running"></span></a></li>
<li class="nav-item sb-update-li">
<a class="nav-link sb-update-url" href="https://github.com/donaldzou/wireguard-dashboard#-how-to-update-the-dashboard">New Update Available!<span class="dot dot-running"></span></a>
</li>
{% endif %}
</ul>
<hr>
@@ -21,6 +23,16 @@
{%endfor%}
</ul>
<hr>
<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
<span>Tools</span>
</h6>
<ul class="nav flex-column">
<ul class="nav flex-column">
<li class="nav-item"><a class="nav-link" data-toggle="modal" data-target="#ping_modal" href="#">Ping</a></li>
<li class="nav-item"><a class="nav-link" data-toggle="modal" data-target="#traceroute_modal" href="#">Traceroute</a></li>
</ul>
</ul>
<hr>
{% if "username" in session %}
<ul class="nav flex-column">
<li class="nav-item"><a class="nav-link text-danger" href="/signout" style="font-weight: bold">Sign Out</a></li>

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" %}
@@ -29,10 +29,6 @@
<label for="password" class="text-left">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Keep you login</label>
</div>
<button type="submit" class="btn btn-dark" style="width: 100%;">Sign In</button>
</form>
</div>

121
src/templates/tools.html Normal file
View File

@@ -0,0 +1,121 @@
<div class="modal fade" id="ping_modal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Ping</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm">
<div class="mb-3">
<small>Configuration</small>
<select class="form-control mt-2 conf_dropdown">
<option value="none" selected="selected" disabled>Select Configuration</option>
{% for i in conf%}
<option value="{{ i['conf'] }}">{{ i['conf'] }}</option>
{%endfor%}
</select>
</div>
</div>
<div class="col-sm">
<div class="mb-3">
<small>IP</small>
<select class="form-control mt-2 ip_dropdown">
<option value="none" selected="selected" disabled>Choose an IP</option>
</select>
</div>
</div>
<div class="col-sm">
<div class="mb-3">
<small>Ping Count</small>
<input type="number" class="form-control mt-2 ping_count" min=1 value=4>
</div>
</div>
</div>
<hr>
<div class="ping_result">
<table class="table">
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary send_ping" disabled>Ping</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="traceroute_modal" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Traceroute</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm">
<div class="mb-3">
<small>Configuration</small>
<select class="form-control mt-2 conf_dropdown">
<option value="none" selected="selected" disabled>Select Configuration</option>
{% for i in conf%}
<option value="{{ i['conf'] }}">{{ i['conf'] }}</option>
{%endfor%}
</select>
</div>
</div>
<div class="col-sm">
<div class="mb-3">
<small>IP</small>
<select class="form-control mt-2 ip_dropdown">
<option value="none" selected="selected" disabled>Choose an IP</option>
</select>
</div>
</div>
</div>
<button class="btn btn-primary send_traceroute" disabled>Traceroute</button>
<hr>
<div class="traceroute_result">
<table class="table table-sm">
<thead>
<tr>
<th scope="col">Hop</th>
<th scope="col">IP</th>
<th scope="col">Avg RTT</th>
<th scope="col">Min RTT</th>
<th scope="col">Max RTT</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="update_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="modal-title" id="staticBackdropLabel">How to update dashboard</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<pre><code>$ sudo sh wgd.sh stop</code><br><code>$ sudo sh wgd.sh update</code><br><code>$ sudo sh wgd.sh start</code></pre>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

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

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

@@ -4,7 +4,7 @@ app_name="dashboard.py"
dashes='------------------------------------------------------------'
help () {
printf "<Wireguard Dashboard> by Donald Zou - https://github.com/donaldzou \n"
printf "Usage: sh wg-dashboard.sh <option>"
printf "Usage: sh wgd.sh <option>"
printf "\n \n"
printf "Available options: \n"
printf " start: To start Wireguard Dashboard.\n"
@@ -25,6 +25,7 @@ check_wgd_status(){
}
start_wgd () {
printf "%s" "$PLATFORM"
printf "Starting Wireguard Dashboard in the background. \n"
if [ ! -d "log" ]
then mkdir "log"
@@ -44,7 +45,6 @@ start_wgd_debug() {
}
update_wgd() {
new_ver=$(python3 -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/wireguard-dashboard/releases').read(); output = json.loads(data);print(output[0]['tag_name'])")
printf "%s\n" "$dashes"
printf "Are you sure you want to update to the %s? (Y/N): " "$new_ver"
@@ -63,7 +63,7 @@ update_wgd() {
exit 1
else
printf "%s\n" "$dashes"
printf "Cancel update. \n"
printf "CANCEL update. \n"
printf "%s\n" "$dashes"
fi
}
@@ -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