mirror of
https://github.com/ngoduykhanh/wireguard-ui.git
synced 2025-04-19 19:59:13 +03:00
Fixes security issue & Adds support to sent configuration via email (#83)
This commit is contained in:
parent
7edcd1b80c
commit
1711530dda
13 changed files with 335 additions and 76 deletions
12
README.md
12
README.md
|
@ -21,6 +21,18 @@ You can take a look at this example of [docker-compose.yml](https://github.com/n
|
||||||
```
|
```
|
||||||
docker-compose up
|
docker-compose up
|
||||||
```
|
```
|
||||||
|
### Environment Variables
|
||||||
|
|
||||||
|
|
||||||
|
Set the `SESSION_SECRET` environment variable to a random value.
|
||||||
|
|
||||||
|
In order to sent the wireguard configuration to clients via email (using sendgrid api) set the following environment variables
|
||||||
|
|
||||||
|
```
|
||||||
|
SENDGRID_API_KEY: Your sendgrid api key
|
||||||
|
EMAIL_FROM: the email address you registered on sendgrid
|
||||||
|
EMAIL_FROM_NAME: the sender's email address
|
||||||
|
```
|
||||||
|
|
||||||
### Using binary file
|
### Using binary file
|
||||||
|
|
||||||
|
|
|
@ -29,6 +29,9 @@ function renderClientList(data) {
|
||||||
<div class="btn-group">
|
<div class="btn-group">
|
||||||
<button onclick="location.href='/download?clientid=${obj.Client.id}'" type="button"
|
<button onclick="location.href='/download?clientid=${obj.Client.id}'" type="button"
|
||||||
class="btn btn-outline-success btn-sm">Download</button>
|
class="btn btn-outline-success btn-sm">Download</button>
|
||||||
|
<button type="button" class="btn btn-outline-warning btn-sm" data-toggle="modal"
|
||||||
|
data-target="#modal_email_client" data-clientid="${obj.Client.id}"
|
||||||
|
data-clientname="${obj.Client.name}">Email</button>
|
||||||
<button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal"
|
<button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal"
|
||||||
data-target="#modal_edit_client" data-clientid="${obj.Client.id}"
|
data-target="#modal_edit_client" data-clientid="${obj.Client.id}"
|
||||||
data-clientname="${obj.Client.name}">Edit</button>
|
data-clientname="${obj.Client.name}">Edit</button>
|
||||||
|
|
|
@ -2,8 +2,14 @@ version: '3'
|
||||||
|
|
||||||
services:
|
services:
|
||||||
wg:
|
wg:
|
||||||
image: ngoduykhanh/wireguard-ui:latest
|
build: .
|
||||||
|
#image: ngoduykhanh/wireguard-ui:latest
|
||||||
container_name: wgui
|
container_name: wgui
|
||||||
|
environment:
|
||||||
|
- SENDGRID_API_KEY
|
||||||
|
- EMAIL_FROM
|
||||||
|
- EMAIL_FROM_NAME
|
||||||
|
- SESSION_SECRET
|
||||||
ports:
|
ports:
|
||||||
- 5000:5000
|
- 5000:5000
|
||||||
logging:
|
logging:
|
||||||
|
|
10
emailer/interface.go
Normal file
10
emailer/interface.go
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
package emailer
|
||||||
|
|
||||||
|
type Attachment struct {
|
||||||
|
Name string
|
||||||
|
Data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type Emailer interface {
|
||||||
|
Send(toName string, to string, subject string, content string, attachments []Attachment) error
|
||||||
|
}
|
54
emailer/sendgrid.go
Normal file
54
emailer/sendgrid.go
Normal file
|
@ -0,0 +1,54 @@
|
||||||
|
package emailer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
|
||||||
|
"github.com/sendgrid/sendgrid-go"
|
||||||
|
"github.com/sendgrid/sendgrid-go/helpers/mail"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SendgridApiMail struct {
|
||||||
|
apiKey string
|
||||||
|
fromName string
|
||||||
|
from string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSendgridApiMail(apiKey, fromName, from string) *SendgridApiMail {
|
||||||
|
ans := SendgridApiMail{apiKey: apiKey, fromName: fromName, from: from}
|
||||||
|
return &ans
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *SendgridApiMail) Send(toName string, to string, subject string, content string, attachments []Attachment) error {
|
||||||
|
m := mail.NewV3Mail()
|
||||||
|
|
||||||
|
mailFrom := mail.NewEmail(o.fromName, o.from)
|
||||||
|
mailContent := mail.NewContent("text/html", content)
|
||||||
|
mailTo := mail.NewEmail(toName, to)
|
||||||
|
|
||||||
|
m.SetFrom(mailFrom)
|
||||||
|
m.AddContent(mailContent)
|
||||||
|
|
||||||
|
personalization := mail.NewPersonalization()
|
||||||
|
personalization.AddTos(mailTo)
|
||||||
|
personalization.Subject = subject
|
||||||
|
|
||||||
|
m.AddPersonalizations(personalization)
|
||||||
|
|
||||||
|
toAdd := make([]*mail.Attachment, 0, len(attachments))
|
||||||
|
for i := range attachments {
|
||||||
|
var att mail.Attachment
|
||||||
|
encoded := base64.StdEncoding.EncodeToString(attachments[i].Data)
|
||||||
|
att.SetContent(encoded)
|
||||||
|
att.SetType("text/plain")
|
||||||
|
att.SetFilename(attachments[i].Name)
|
||||||
|
att.SetDisposition("attachment")
|
||||||
|
toAdd = append(toAdd, &att)
|
||||||
|
}
|
||||||
|
|
||||||
|
m.AddAttachment(toAdd...)
|
||||||
|
request := sendgrid.GetRequest(o.apiKey, "/v3/mail/send", "https://api.sendgrid.com")
|
||||||
|
request.Method = "POST"
|
||||||
|
request.Body = mail.GetRequestBody(m)
|
||||||
|
_, err := sendgrid.API(request)
|
||||||
|
return err
|
||||||
|
}
|
2
go.mod
2
go.mod
|
@ -14,6 +14,8 @@ require (
|
||||||
github.com/leodido/go-urn v1.2.0 // indirect
|
github.com/leodido/go-urn v1.2.0 // indirect
|
||||||
github.com/rs/xid v1.2.1
|
github.com/rs/xid v1.2.1
|
||||||
github.com/sdomino/scribble v0.0.0-20191024200645-4116320640ba
|
github.com/sdomino/scribble v0.0.0-20191024200645-4116320640ba
|
||||||
|
github.com/sendgrid/rest v2.6.4+incompatible // indirect
|
||||||
|
github.com/sendgrid/sendgrid-go v3.10.0+incompatible
|
||||||
github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086
|
github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086
|
||||||
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20200324154536-ceff61240acf
|
golang.zx2c4.com/wireguard/wgctrl v0.0.0-20200324154536-ceff61240acf
|
||||||
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
|
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
|
||||||
|
|
4
go.sum
4
go.sum
|
@ -103,6 +103,10 @@ github.com/rs/xid v1.2.1 h1:mhH9Nq+C1fY2l1XIpgxIiUOfNpRBYH1kKcr+qfKgjRc=
|
||||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||||
github.com/sdomino/scribble v0.0.0-20191024200645-4116320640ba h1:8QAc9wFAf2b/9cAXskm0wBylObZ0bTpRcaP7ThjLPVQ=
|
github.com/sdomino/scribble v0.0.0-20191024200645-4116320640ba h1:8QAc9wFAf2b/9cAXskm0wBylObZ0bTpRcaP7ThjLPVQ=
|
||||||
github.com/sdomino/scribble v0.0.0-20191024200645-4116320640ba/go.mod h1:W6zxGUBCXRR5QugSd/nFcFVmwoGnvpjiNY/JwT03Wew=
|
github.com/sdomino/scribble v0.0.0-20191024200645-4116320640ba/go.mod h1:W6zxGUBCXRR5QugSd/nFcFVmwoGnvpjiNY/JwT03Wew=
|
||||||
|
github.com/sendgrid/rest v2.6.4+incompatible h1:lq6gAQxLwVBf3mVyCCSHI6mgF+NfaJFJHjT0kl6SSo8=
|
||||||
|
github.com/sendgrid/rest v2.6.4+incompatible/go.mod h1:kXX7q3jZtJXK5c5qK83bSGMdV6tsOE70KbHoqJls4lE=
|
||||||
|
github.com/sendgrid/sendgrid-go v3.10.0+incompatible h1:aSYyurHxEZSDy7kxhvZ4fH0inNkEEmRssZNbAmETR2c=
|
||||||
|
github.com/sendgrid/sendgrid-go v3.10.0+incompatible/go.mod h1:QRQt+LX/NmgVEvmdRw0VT/QgUn499+iza2FnDca9fg8=
|
||||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||||
github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086 h1:RYiqpb2ii2Z6J4x0wxK46kvPBbFuZcdhS+CIztmYgZs=
|
github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086 h1:RYiqpb2ii2Z6J4x0wxK46kvPBbFuZcdhS+CIztmYgZs=
|
||||||
github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086/go.mod h1:PLPIyL7ikehBD1OAjmKKiOEhbvWyHGaNDjquXMcYABo=
|
github.com/skip2/go-qrcode v0.0.0-20191027152451-9434209cb086/go.mod h1:PLPIyL7ikehBD1OAjmKKiOEhbvWyHGaNDjquXMcYABo=
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
@ -13,6 +14,7 @@ import (
|
||||||
"github.com/labstack/echo-contrib/session"
|
"github.com/labstack/echo-contrib/session"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
"github.com/labstack/gommon/log"
|
"github.com/labstack/gommon/log"
|
||||||
|
"github.com/ngoduykhanh/wireguard-ui/emailer"
|
||||||
"github.com/ngoduykhanh/wireguard-ui/model"
|
"github.com/ngoduykhanh/wireguard-ui/model"
|
||||||
"github.com/ngoduykhanh/wireguard-ui/util"
|
"github.com/ngoduykhanh/wireguard-ui/util"
|
||||||
"github.com/rs/xid"
|
"github.com/rs/xid"
|
||||||
|
@ -77,8 +79,6 @@ func Logout() echo.HandlerFunc {
|
||||||
// WireGuardClients handler
|
// WireGuardClients handler
|
||||||
func WireGuardClients() echo.HandlerFunc {
|
func WireGuardClients() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
clientDataList, err := util.GetClients(true)
|
clientDataList, err := util.GetClients(true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -97,8 +97,6 @@ func WireGuardClients() echo.HandlerFunc {
|
||||||
// GetClients handler return a list of Wireguard client data
|
// GetClients handler return a list of Wireguard client data
|
||||||
func GetClients() echo.HandlerFunc {
|
func GetClients() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
clientDataList, err := util.GetClients(true)
|
clientDataList, err := util.GetClients(true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -114,8 +112,6 @@ func GetClients() echo.HandlerFunc {
|
||||||
// GetClient handler return a of Wireguard client data
|
// GetClient handler return a of Wireguard client data
|
||||||
func GetClient() echo.HandlerFunc {
|
func GetClient() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
clientID := c.Param("id")
|
clientID := c.Param("id")
|
||||||
clientData, err := util.GetClientByID(clientID, true)
|
clientData, err := util.GetClientByID(clientID, true)
|
||||||
|
@ -130,8 +126,6 @@ func GetClient() echo.HandlerFunc {
|
||||||
// NewClient handler
|
// NewClient handler
|
||||||
func NewClient() echo.HandlerFunc {
|
func NewClient() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
client := new(model.Client)
|
client := new(model.Client)
|
||||||
c.Bind(client)
|
c.Bind(client)
|
||||||
|
@ -194,11 +188,53 @@ func NewClient() echo.HandlerFunc {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EmailClient handler to sent the configuration via email
|
||||||
|
func EmailClient(mailer emailer.Emailer, emailSubject, emailContent string) echo.HandlerFunc {
|
||||||
|
type clientIdEmailPayload struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(c echo.Context) error {
|
||||||
|
var payload clientIdEmailPayload
|
||||||
|
c.Bind(&payload)
|
||||||
|
// TODO validate email
|
||||||
|
|
||||||
|
clientData, err := util.GetClientByID(payload.ID, true)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorf("Cannot generate client id %s config file for downloading: %v", payload.ID, err)
|
||||||
|
return c.JSON(http.StatusNotFound, jsonHTTPResponse{false, "Client not found"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// build config
|
||||||
|
server, _ := util.GetServer()
|
||||||
|
globalSettings, _ := util.GetGlobalSettings()
|
||||||
|
config := util.BuildClientConfig(*clientData.Client, server, globalSettings)
|
||||||
|
|
||||||
|
cfg_att := emailer.Attachment{"wg0.conf", []byte(config)}
|
||||||
|
qrdata, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(clientData.QRCode, "data:image/png;base64,"))
|
||||||
|
if err != nil {
|
||||||
|
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, "decoding: " + err.Error()})
|
||||||
|
}
|
||||||
|
qr_att := emailer.Attachment{"wg.png", qrdata}
|
||||||
|
err = mailer.Send(
|
||||||
|
clientData.Client.Name,
|
||||||
|
payload.Email,
|
||||||
|
emailSubject,
|
||||||
|
emailContent,
|
||||||
|
[]emailer.Attachment{cfg_att, qr_att},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, err.Error()})
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.JSON(http.StatusOK, jsonHTTPResponse{true, "Email sent successfully"})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateClient handler to update client information
|
// UpdateClient handler to update client information
|
||||||
func UpdateClient() echo.HandlerFunc {
|
func UpdateClient() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
_client := new(model.Client)
|
_client := new(model.Client)
|
||||||
c.Bind(_client)
|
c.Bind(_client)
|
||||||
|
@ -257,8 +293,6 @@ func UpdateClient() echo.HandlerFunc {
|
||||||
// SetClientStatus handler to enable / disable a client
|
// SetClientStatus handler to enable / disable a client
|
||||||
func SetClientStatus() echo.HandlerFunc {
|
func SetClientStatus() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
data := make(map[string]interface{})
|
data := make(map[string]interface{})
|
||||||
err := json.NewDecoder(c.Request().Body).Decode(&data)
|
err := json.NewDecoder(c.Request().Body).Decode(&data)
|
||||||
|
@ -320,8 +354,6 @@ func DownloadClient() echo.HandlerFunc {
|
||||||
// RemoveClient handler
|
// RemoveClient handler
|
||||||
func RemoveClient() echo.HandlerFunc {
|
func RemoveClient() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
client := new(model.Client)
|
client := new(model.Client)
|
||||||
c.Bind(client)
|
c.Bind(client)
|
||||||
|
@ -346,8 +378,6 @@ func RemoveClient() echo.HandlerFunc {
|
||||||
// WireGuardServer handler
|
// WireGuardServer handler
|
||||||
func WireGuardServer() echo.HandlerFunc {
|
func WireGuardServer() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
server, err := util.GetServer()
|
server, err := util.GetServer()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -365,8 +395,6 @@ func WireGuardServer() echo.HandlerFunc {
|
||||||
// WireGuardServerInterfaces handler
|
// WireGuardServerInterfaces handler
|
||||||
func WireGuardServerInterfaces() echo.HandlerFunc {
|
func WireGuardServerInterfaces() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
serverInterface := new(model.ServerInterface)
|
serverInterface := new(model.ServerInterface)
|
||||||
c.Bind(serverInterface)
|
c.Bind(serverInterface)
|
||||||
|
@ -396,8 +424,6 @@ func WireGuardServerInterfaces() echo.HandlerFunc {
|
||||||
// WireGuardServerKeyPair handler to generate private and public keys
|
// WireGuardServerKeyPair handler to generate private and public keys
|
||||||
func WireGuardServerKeyPair() echo.HandlerFunc {
|
func WireGuardServerKeyPair() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
// gen Wireguard key pair
|
// gen Wireguard key pair
|
||||||
key, err := wgtypes.GeneratePrivateKey()
|
key, err := wgtypes.GeneratePrivateKey()
|
||||||
|
@ -428,8 +454,6 @@ func WireGuardServerKeyPair() echo.HandlerFunc {
|
||||||
// GlobalSettings handler
|
// GlobalSettings handler
|
||||||
func GlobalSettings() echo.HandlerFunc {
|
func GlobalSettings() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
globalSettings, err := util.GetGlobalSettings()
|
globalSettings, err := util.GetGlobalSettings()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -446,8 +470,6 @@ func GlobalSettings() echo.HandlerFunc {
|
||||||
// GlobalSettingSubmit handler to update the global settings
|
// GlobalSettingSubmit handler to update the global settings
|
||||||
func GlobalSettingSubmit() echo.HandlerFunc {
|
func GlobalSettingSubmit() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
globalSettings := new(model.GlobalSetting)
|
globalSettings := new(model.GlobalSetting)
|
||||||
c.Bind(globalSettings)
|
c.Bind(globalSettings)
|
||||||
|
@ -477,8 +499,6 @@ func GlobalSettingSubmit() echo.HandlerFunc {
|
||||||
// MachineIPAddresses handler to get local interface ip addresses
|
// MachineIPAddresses handler to get local interface ip addresses
|
||||||
func MachineIPAddresses() echo.HandlerFunc {
|
func MachineIPAddresses() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
// get private ip addresses
|
// get private ip addresses
|
||||||
interfaceList, err := util.GetInterfaceIPs()
|
interfaceList, err := util.GetInterfaceIPs()
|
||||||
|
@ -503,8 +523,6 @@ func MachineIPAddresses() echo.HandlerFunc {
|
||||||
// SuggestIPAllocation handler to get the list of ip address for client
|
// SuggestIPAllocation handler to get the list of ip address for client
|
||||||
func SuggestIPAllocation() echo.HandlerFunc {
|
func SuggestIPAllocation() echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
server, err := util.GetServer()
|
server, err := util.GetServer()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -541,8 +559,6 @@ func SuggestIPAllocation() echo.HandlerFunc {
|
||||||
// ApplyServerConfig handler to write config file and restart Wireguard server
|
// ApplyServerConfig handler to write config file and restart Wireguard server
|
||||||
func ApplyServerConfig(tmplBox *rice.Box) echo.HandlerFunc {
|
func ApplyServerConfig(tmplBox *rice.Box) echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
// access validation
|
|
||||||
validSession(c)
|
|
||||||
|
|
||||||
server, err := util.GetServer()
|
server, err := util.GetServer()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -9,20 +9,30 @@ import (
|
||||||
"github.com/ngoduykhanh/wireguard-ui/util"
|
"github.com/ngoduykhanh/wireguard-ui/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
// validSession to redirect user to the login page if they are not authenticated or session expired.
|
func ValidSession(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
func validSession(c echo.Context) {
|
return func(c echo.Context) error {
|
||||||
if !util.DisableLogin {
|
if !isValidSession(c) {
|
||||||
|
nextURL := c.Request().URL
|
||||||
|
if nextURL != nil && c.Request().Method == http.MethodGet {
|
||||||
|
return c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("/login?next=%s", c.Request().URL))
|
||||||
|
} else {
|
||||||
|
return c.Redirect(http.StatusTemporaryRedirect, "/login")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return next(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isValidSession(c echo.Context) bool {
|
||||||
|
if util.DisableLogin {
|
||||||
|
return true
|
||||||
|
}
|
||||||
sess, _ := session.Get("session", c)
|
sess, _ := session.Get("session", c)
|
||||||
cookie, err := c.Cookie("session_token")
|
cookie, err := c.Cookie("session_token")
|
||||||
if err != nil || sess.Values["session_token"] != cookie.Value {
|
if err != nil || sess.Values["session_token"] != cookie.Value {
|
||||||
nextURL := c.Request().URL
|
return false
|
||||||
if nextURL != nil {
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("/login?next=%s", c.Request().URL))
|
|
||||||
} else {
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, "/login")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// currentUser to get username of logged in user
|
// currentUser to get username of logged in user
|
||||||
|
|
55
main.go
55
main.go
|
@ -4,10 +4,13 @@ import (
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
rice "github.com/GeertJohan/go.rice"
|
rice "github.com/GeertJohan/go.rice"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
|
|
||||||
|
"github.com/ngoduykhanh/wireguard-ui/emailer"
|
||||||
"github.com/ngoduykhanh/wireguard-ui/handler"
|
"github.com/ngoduykhanh/wireguard-ui/handler"
|
||||||
"github.com/ngoduykhanh/wireguard-ui/router"
|
"github.com/ngoduykhanh/wireguard-ui/router"
|
||||||
"github.com/ngoduykhanh/wireguard-ui/util"
|
"github.com/ngoduykhanh/wireguard-ui/util"
|
||||||
|
@ -21,6 +24,15 @@ var (
|
||||||
buildTime = fmt.Sprintf(time.Now().UTC().Format("01-02-2006 15:04:05"))
|
buildTime = fmt.Sprintf(time.Now().UTC().Format("01-02-2006 15:04:05"))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultEmailSubject = "Your wireguard configuration"
|
||||||
|
defaultEmailContent = `Hi,</br>
|
||||||
|
<p>in this email you can file your personal configuration for our wireguard server.</p>
|
||||||
|
|
||||||
|
<p>Best</p>
|
||||||
|
`
|
||||||
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
// command-line flags
|
// command-line flags
|
||||||
flagDisableLogin := flag.Bool("disable-login", false, "Disable login page. Turn off authentication.")
|
flagDisableLogin := flag.Bool("disable-login", false, "Disable login page. Turn off authentication.")
|
||||||
|
@ -30,6 +42,10 @@ func init() {
|
||||||
// update runtime config
|
// update runtime config
|
||||||
util.DisableLogin = *flagDisableLogin
|
util.DisableLogin = *flagDisableLogin
|
||||||
util.BindAddress = *flagBindAddress
|
util.BindAddress = *flagBindAddress
|
||||||
|
util.SendgridApiKey = os.Getenv("SENDGRID_API_KEY")
|
||||||
|
util.EmailFrom = os.Getenv("EMAIL_FROM")
|
||||||
|
util.EmailFromName = os.Getenv("EMAIL_FROM_NAME")
|
||||||
|
util.SessionSecret = []byte(os.Getenv("SESSION_SECRET"))
|
||||||
|
|
||||||
// print app information
|
// print app information
|
||||||
fmt.Println("Wireguard UI")
|
fmt.Println("Wireguard UI")
|
||||||
|
@ -60,31 +76,34 @@ func main() {
|
||||||
assetHandler := http.FileServer(rice.MustFindBox("assets").HTTPBox())
|
assetHandler := http.FileServer(rice.MustFindBox("assets").HTTPBox())
|
||||||
|
|
||||||
// register routes
|
// register routes
|
||||||
app := router.New(tmplBox, extraData)
|
app := router.New(tmplBox, extraData, util.SessionSecret)
|
||||||
|
|
||||||
app.GET("/", handler.WireGuardClients())
|
app.GET("/", handler.WireGuardClients(), handler.ValidSession)
|
||||||
|
|
||||||
if !util.DisableLogin {
|
if !util.DisableLogin {
|
||||||
app.GET("/login", handler.LoginPage())
|
app.GET("/login", handler.LoginPage())
|
||||||
app.POST("/login", handler.Login())
|
app.POST("/login", handler.Login())
|
||||||
}
|
}
|
||||||
|
|
||||||
app.GET("/logout", handler.Logout())
|
sendmail := emailer.NewSendgridApiMail(util.SendgridApiKey, util.EmailFromName, util.EmailFrom)
|
||||||
app.POST("/new-client", handler.NewClient())
|
|
||||||
app.POST("/update-client", handler.UpdateClient())
|
app.GET("/logout", handler.Logout(), handler.ValidSession)
|
||||||
app.POST("/client/set-status", handler.SetClientStatus())
|
app.POST("/new-client", handler.NewClient(), handler.ValidSession)
|
||||||
app.POST("/remove-client", handler.RemoveClient())
|
app.POST("/update-client", handler.UpdateClient(), handler.ValidSession)
|
||||||
app.GET("/download", handler.DownloadClient())
|
app.POST("/email-client", handler.EmailClient(sendmail, defaultEmailSubject, defaultEmailContent), handler.ValidSession)
|
||||||
app.GET("/wg-server", handler.WireGuardServer())
|
app.POST("/client/set-status", handler.SetClientStatus(), handler.ValidSession)
|
||||||
app.POST("wg-server/interfaces", handler.WireGuardServerInterfaces())
|
app.POST("/remove-client", handler.RemoveClient(), handler.ValidSession)
|
||||||
app.POST("wg-server/keypair", handler.WireGuardServerKeyPair())
|
app.GET("/download", handler.DownloadClient(), handler.ValidSession)
|
||||||
app.GET("/global-settings", handler.GlobalSettings())
|
app.GET("/wg-server", handler.WireGuardServer(), handler.ValidSession)
|
||||||
app.POST("/global-settings", handler.GlobalSettingSubmit())
|
app.POST("wg-server/interfaces", handler.WireGuardServerInterfaces(), handler.ValidSession)
|
||||||
app.GET("/api/clients", handler.GetClients())
|
app.POST("wg-server/keypair", handler.WireGuardServerKeyPair(), handler.ValidSession)
|
||||||
app.GET("/api/client/:id", handler.GetClient())
|
app.GET("/global-settings", handler.GlobalSettings(), handler.ValidSession)
|
||||||
app.GET("/api/machine-ips", handler.MachineIPAddresses())
|
app.POST("/global-settings", handler.GlobalSettingSubmit(), handler.ValidSession)
|
||||||
app.GET("/api/suggest-client-ips", handler.SuggestIPAllocation())
|
app.GET("/api/clients", handler.GetClients(), handler.ValidSession)
|
||||||
app.GET("/api/apply-wg-config", handler.ApplyServerConfig(tmplBox))
|
app.GET("/api/client/:id", handler.GetClient(), handler.ValidSession)
|
||||||
|
app.GET("/api/machine-ips", handler.MachineIPAddresses(), handler.ValidSession)
|
||||||
|
app.GET("/api/suggest-client-ips", handler.SuggestIPAllocation(), handler.ValidSession)
|
||||||
|
app.GET("/api/apply-wg-config", handler.ApplyServerConfig(tmplBox), handler.ValidSession)
|
||||||
|
|
||||||
// servers other static files
|
// servers other static files
|
||||||
app.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", assetHandler)))
|
app.GET("/static/*", echo.WrapHandler(http.StripPrefix("/static/", assetHandler)))
|
||||||
|
|
|
@ -6,7 +6,7 @@ import (
|
||||||
"reflect"
|
"reflect"
|
||||||
"text/template"
|
"text/template"
|
||||||
|
|
||||||
"github.com/GeertJohan/go.rice"
|
rice "github.com/GeertJohan/go.rice"
|
||||||
"github.com/gorilla/sessions"
|
"github.com/gorilla/sessions"
|
||||||
"github.com/labstack/echo-contrib/session"
|
"github.com/labstack/echo-contrib/session"
|
||||||
"github.com/labstack/echo/v4"
|
"github.com/labstack/echo/v4"
|
||||||
|
@ -44,9 +44,9 @@ func (t *TemplateRegistry) Render(w io.Writer, name string, data interface{}, c
|
||||||
}
|
}
|
||||||
|
|
||||||
// New function
|
// New function
|
||||||
func New(tmplBox *rice.Box, extraData map[string]string) *echo.Echo {
|
func New(tmplBox *rice.Box, extraData map[string]string, secret []byte) *echo.Echo {
|
||||||
e := echo.New()
|
e := echo.New()
|
||||||
e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
|
e.Use(session.Middleware(sessions.NewCookieStore(secret)))
|
||||||
|
|
||||||
// read html template file to string
|
// read html template file to string
|
||||||
tmplBaseString, err := tmplBox.String("base.html")
|
tmplBaseString, err := tmplBox.String("base.html")
|
||||||
|
|
|
@ -30,6 +30,34 @@ Wireguard Clients
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<div class="modal fade" id="modal_email_client">
|
||||||
|
<div class="modal-dialog">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h4 class="modal-title">Email Configuration</h4>
|
||||||
|
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||||
|
<span aria-hidden="true">×</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form name="frm_email_client" id="frm_email_client">
|
||||||
|
<div class="modal-body">
|
||||||
|
<input type="hidden" id="_client_id" name="_client_id">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="_client_email" class="control-label">Email</label>
|
||||||
|
<input type="text" class="form-control" id="_client_email" name="client_email">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer justify-content-between">
|
||||||
|
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
|
||||||
|
<button type="submit" class="btn btn-success">Send</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<!-- /.modal-content -->
|
||||||
|
</div>
|
||||||
|
<!-- /.modal-dialog -->
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="modal fade" id="modal_edit_client">
|
<div class="modal fade" id="modal_edit_client">
|
||||||
<div class="modal-dialog">
|
<div class="modal-dialog">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
|
@ -243,6 +271,8 @@ Wireguard Clients
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Edit client modal event
|
// Edit client modal event
|
||||||
$(document).ready(function () {
|
$(document).ready(function () {
|
||||||
$("#modal_edit_client").on('shown.bs.modal', function (event) {
|
$("#modal_edit_client").on('shown.bs.modal', function (event) {
|
||||||
|
@ -308,6 +338,31 @@ Wireguard Clients
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// submitEmailClient function for sending an email to the client with the configuration
|
||||||
|
function submitEmailClient() {
|
||||||
|
const client_id = $("#_client_id").val();
|
||||||
|
const email = $("#_client_email").val();
|
||||||
|
const data = {"id": client_id, "email": email};
|
||||||
|
$.ajax({
|
||||||
|
cache: false,
|
||||||
|
method: 'POST',
|
||||||
|
url: '/email-client',
|
||||||
|
dataType: 'json',
|
||||||
|
contentType: "application/json",
|
||||||
|
data: JSON.stringify(data),
|
||||||
|
success: function(resp) {
|
||||||
|
$("#modal_email_client").modal('hide');
|
||||||
|
toastr.success('Sent email to client successfully');
|
||||||
|
// Refresh the home page (clients page) after sending email successfully
|
||||||
|
location.reload();
|
||||||
|
},
|
||||||
|
error: function(jqXHR, exception) {
|
||||||
|
const responseJson = jQuery.parseJSON(jqXHR.responseText);
|
||||||
|
toastr.error(responseJson['message']);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// submitEditClient function for updating an existing client
|
// submitEditClient function for updating an existing client
|
||||||
function submitEditClient() {
|
function submitEditClient() {
|
||||||
const client_id = $("#_client_id").val();
|
const client_id = $("#_client_id").val();
|
||||||
|
@ -350,13 +405,48 @@ Wireguard Clients
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Edit client form validation
|
// submitHandler
|
||||||
$(document).ready(function () {
|
function submitHandler(form) {
|
||||||
$.validator.setDefaults({
|
const formId = $(form).attr('id');
|
||||||
submitHandler: function () {
|
if (formId === "frm_edit_client") {
|
||||||
submitEditClient();
|
submitEditClient();
|
||||||
|
}else if (formId === "frm_email_client") {
|
||||||
|
submitEmailClient();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$("#modal_email_client").on('shown.bs.modal', function (event) {
|
||||||
|
let modal = $(this);
|
||||||
|
const button = $(event.relatedTarget);
|
||||||
|
const client_id = button.data('clientid');
|
||||||
|
$.ajax({
|
||||||
|
cache: false,
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/client/' + client_id,
|
||||||
|
dataType: 'json',
|
||||||
|
contentType: "application/json",
|
||||||
|
success: function (resp) {
|
||||||
|
const client = resp.Client;
|
||||||
|
|
||||||
|
modal.find(".modal-title").text("Email Client " + client.name);
|
||||||
|
modal.find("#_client_id").val(client.id);
|
||||||
|
modal.find("#_client_email").val(client.email);
|
||||||
|
},
|
||||||
|
error: function (jqXHR, exception) {
|
||||||
|
const responseJson = jQuery.parseJSON(jqXHR.responseText);
|
||||||
|
toastr.error(responseJson['message']);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
$(document).ready(function () {
|
||||||
|
$.validator.setDefaults({
|
||||||
|
submitHandler: function (form) {
|
||||||
|
//submitEditClient();
|
||||||
|
submitHandler(form);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Edit client form validation
|
||||||
$("#frm_edit_client").validate({
|
$("#frm_edit_client").validate({
|
||||||
rules: {
|
rules: {
|
||||||
client_name: {
|
client_name: {
|
||||||
|
@ -388,6 +478,33 @@ Wireguard Clients
|
||||||
$(element).removeClass('is-invalid');
|
$(element).removeClass('is-invalid');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Email client form validation
|
||||||
|
$("#frm_email_client").validate({
|
||||||
|
rules: {
|
||||||
|
client_email: {
|
||||||
|
required: true,
|
||||||
|
email: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
messages: {
|
||||||
|
client_email: {
|
||||||
|
required: "Please enter an email address",
|
||||||
|
email: "Please enter a valid email address"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
errorElement: 'span',
|
||||||
|
errorPlacement: function (error, element) {
|
||||||
|
error.addClass('invalid-feedback');
|
||||||
|
element.closest('.form-group').append(error);
|
||||||
|
},
|
||||||
|
highlight: function (element, errorClass, validClass) {
|
||||||
|
$(element).addClass('is-invalid');
|
||||||
|
},
|
||||||
|
unhighlight: function (element, errorClass, validClass) {
|
||||||
|
$(element).removeClass('is-invalid');
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
{{end}}
|
{{end}}
|
|
@ -4,4 +4,10 @@ package util
|
||||||
var (
|
var (
|
||||||
DisableLogin bool
|
DisableLogin bool
|
||||||
BindAddress string
|
BindAddress string
|
||||||
|
SendgridApiKey string
|
||||||
|
EmailFrom string
|
||||||
|
EmailFromName string
|
||||||
|
EmailSubject string
|
||||||
|
EmailContent string
|
||||||
|
SessionSecret []byte
|
||||||
)
|
)
|
||||||
|
|
Loading…
Add table
Reference in a new issue