wg-portal/internal/server/handlers_peer.go

374 lines
11 KiB
Go
Raw Normal View History

2020-11-10 03:31:02 -05:00
package server
import (
"bytes"
2020-11-10 16:23:05 -05:00
"net"
2020-11-10 03:31:02 -05:00
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/h44z/wg-portal/internal/common"
"github.com/h44z/wg-portal/internal/ldap"
2021-02-08 16:56:02 -05:00
"github.com/sirupsen/logrus"
2020-11-10 16:23:05 -05:00
"github.com/tatsushid/go-fastping"
2020-11-10 03:31:02 -05:00
)
type LdapCreateForm struct {
Emails string `form:"email" binding:"required"`
Identifier string `form:"identifier" binding:"required,lte=20"`
}
func (s *Server) GetAdminEditPeer(c *gin.Context) {
device := s.users.GetDevice()
user := s.users.GetUserByKey(c.Query("pkey"))
currentSession, err := s.setFormInSession(c, user)
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "Session error", err.Error())
return
}
c.HTML(http.StatusOK, "admin_edit_client.html", struct {
2020-11-10 16:23:05 -05:00
Route string
Alerts []FlashData
Session SessionData
Static StaticData
2021-02-21 17:23:58 -05:00
Peer Peer
2020-11-10 16:23:05 -05:00
Device Device
EditableKeys bool
2020-11-10 03:31:02 -05:00
}{
2020-11-10 16:23:05 -05:00
Route: c.Request.URL.Path,
Alerts: s.getFlashes(c),
Session: currentSession,
Static: s.getStaticData(),
2021-02-21 17:23:58 -05:00
Peer: currentSession.FormData.(Peer),
2020-11-10 16:23:05 -05:00
Device: device,
EditableKeys: s.config.Core.EditableKeys,
2020-11-10 03:31:02 -05:00
})
}
func (s *Server) PostAdminEditPeer(c *gin.Context) {
currentUser := s.users.GetUserByKey(c.Query("pkey"))
urlEncodedKey := url.QueryEscape(c.Query("pkey"))
currentSession := s.getSessionData(c)
2021-02-21 17:23:58 -05:00
var formPeer Peer
2020-11-10 03:31:02 -05:00
if currentSession.FormData != nil {
2021-02-21 17:23:58 -05:00
formPeer = currentSession.FormData.(Peer)
2020-11-10 03:31:02 -05:00
}
2021-02-21 17:23:58 -05:00
if err := c.ShouldBind(&formPeer); err != nil {
_ = s.updateFormInSession(c, formPeer)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=bind")
return
}
// Clean list input
2021-02-21 17:23:58 -05:00
formPeer.IPs = common.ParseStringList(formPeer.IPsStr)
formPeer.AllowedIPs = common.ParseStringList(formPeer.AllowedIPsStr)
formPeer.IPsStr = common.ListToString(formPeer.IPs)
formPeer.AllowedIPsStr = common.ListToString(formPeer.AllowedIPs)
2020-11-10 03:31:02 -05:00
disabled := c.PostForm("isdisabled") != ""
now := time.Now()
if disabled && currentUser.DeactivatedAt == nil {
2021-02-21 17:23:58 -05:00
formPeer.DeactivatedAt = &now
2020-11-10 03:31:02 -05:00
} else if !disabled {
2021-02-21 17:23:58 -05:00
formPeer.DeactivatedAt = nil
2020-11-10 03:31:02 -05:00
}
// Update in database
2021-02-21 17:23:58 -05:00
if err := s.UpdateUser(formPeer, now); err != nil {
_ = s.updateFormInSession(c, formPeer)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "failed to update user: "+err.Error(), "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey+"&formerr=update")
return
}
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "changes applied successfully", "success")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/edit?pkey="+urlEncodedKey)
}
func (s *Server) GetAdminCreatePeer(c *gin.Context) {
device := s.users.GetDevice()
currentSession, err := s.setNewUserFormInSession(c)
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "Session error", err.Error())
return
}
c.HTML(http.StatusOK, "admin_edit_client.html", struct {
2020-11-10 16:23:05 -05:00
Route string
Alerts []FlashData
Session SessionData
Static StaticData
2021-02-21 17:23:58 -05:00
Peer Peer
2020-11-10 16:23:05 -05:00
Device Device
EditableKeys bool
2020-11-10 03:31:02 -05:00
}{
2020-11-10 16:23:05 -05:00
Route: c.Request.URL.Path,
Alerts: s.getFlashes(c),
Session: currentSession,
Static: s.getStaticData(),
2021-02-21 17:23:58 -05:00
Peer: currentSession.FormData.(Peer),
2020-11-10 16:23:05 -05:00
Device: device,
EditableKeys: s.config.Core.EditableKeys,
2020-11-10 03:31:02 -05:00
})
}
func (s *Server) PostAdminCreatePeer(c *gin.Context) {
currentSession := s.getSessionData(c)
2021-02-21 17:23:58 -05:00
var formPeer Peer
2020-11-10 03:31:02 -05:00
if currentSession.FormData != nil {
2021-02-21 17:23:58 -05:00
formPeer = currentSession.FormData.(Peer)
2020-11-10 03:31:02 -05:00
}
2021-02-21 17:23:58 -05:00
if err := c.ShouldBind(&formPeer); err != nil {
_ = s.updateFormInSession(c, formPeer)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=bind")
return
}
// Clean list input
2021-02-21 17:23:58 -05:00
formPeer.IPs = common.ParseStringList(formPeer.IPsStr)
formPeer.AllowedIPs = common.ParseStringList(formPeer.AllowedIPsStr)
formPeer.IPsStr = common.ListToString(formPeer.IPs)
formPeer.AllowedIPsStr = common.ListToString(formPeer.AllowedIPs)
2020-11-10 03:31:02 -05:00
disabled := c.PostForm("isdisabled") != ""
now := time.Now()
if disabled {
2021-02-21 17:23:58 -05:00
formPeer.DeactivatedAt = &now
2020-11-10 03:31:02 -05:00
}
2021-02-21 17:23:58 -05:00
if err := s.CreateUser(formPeer); err != nil {
_ = s.updateFormInSession(c, formPeer)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "failed to add user: "+err.Error(), "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/create?formerr=create")
return
}
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "client created successfully", "success")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin")
}
func (s *Server) GetAdminCreateLdapPeers(c *gin.Context) {
currentSession, err := s.setFormInSession(c, LdapCreateForm{Identifier: "Default"})
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "Session error", err.Error())
return
}
c.HTML(http.StatusOK, "admin_create_clients.html", struct {
Route string
2020-11-10 16:23:05 -05:00
Alerts []FlashData
2020-11-10 03:31:02 -05:00
Session SessionData
Static StaticData
Users []*ldap.UserCacheHolderEntry
FormData LdapCreateForm
Device Device
}{
Route: c.Request.URL.Path,
2020-11-10 16:23:05 -05:00
Alerts: s.getFlashes(c),
2020-11-10 03:31:02 -05:00
Session: currentSession,
Static: s.getStaticData(),
Users: s.ldapUsers.GetSortedUsers("sn", "asc"),
FormData: currentSession.FormData.(LdapCreateForm),
Device: s.users.GetDevice(),
})
}
func (s *Server) PostAdminCreateLdapPeers(c *gin.Context) {
currentSession := s.getSessionData(c)
var formData LdapCreateForm
if currentSession.FormData != nil {
formData = currentSession.FormData.(LdapCreateForm)
}
if err := c.ShouldBind(&formData); err != nil {
_ = s.updateFormInSession(c, formData)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "failed to bind form data: "+err.Error(), "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/createldap?formerr=bind")
return
}
emails := common.ParseStringList(formData.Emails)
for i := range emails {
// TODO: also check email addr for validity?
if !strings.ContainsRune(emails[i], '@') || s.ldapUsers.GetUserDNByMail(emails[i]) == "" {
_ = s.updateFormInSession(c, formData)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "invalid email address: "+emails[i], "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/createldap?formerr=mail")
return
}
}
2021-02-08 16:56:02 -05:00
logrus.Infof("creating %d ldap peers", len(emails))
2020-11-10 03:31:02 -05:00
for i := range emails {
if err := s.CreateUserByEmail(emails[i], formData.Identifier, false); err != nil {
_ = s.updateFormInSession(c, formData)
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "failed to add user: "+err.Error(), "danger")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/createldap?formerr=create")
return
}
}
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "client(s) created successfully", "success")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin/peer/createldap")
}
func (s *Server) GetAdminDeletePeer(c *gin.Context) {
currentUser := s.users.GetUserByKey(c.Query("pkey"))
if err := s.DeleteUser(currentUser); err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "Deletion error", err.Error())
return
}
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "user deleted successfully", "success")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin")
}
func (s *Server) GetPeerQRCode(c *gin.Context) {
user := s.users.GetUserByKey(c.Query("pkey"))
currentSession := s.getSessionData(c)
if !currentSession.IsAdmin && user.Email != currentSession.Email {
s.GetHandleError(c, http.StatusUnauthorized, "No permissions", "You don't have permissions to view this resource!")
return
}
png, err := user.GetQRCode()
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "QRCode error", err.Error())
return
}
c.Data(http.StatusOK, "image/png", png)
return
}
func (s *Server) GetPeerConfig(c *gin.Context) {
user := s.users.GetUserByKey(c.Query("pkey"))
currentSession := s.getSessionData(c)
if !currentSession.IsAdmin && user.Email != currentSession.Email {
s.GetHandleError(c, http.StatusUnauthorized, "No permissions", "You don't have permissions to view this resource!")
return
}
2021-02-21 17:23:58 -05:00
cfg, err := user.GetConfigFile(s.users.GetDevice())
2020-11-10 03:31:02 -05:00
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error())
return
}
c.Header("Content-Disposition", "attachment; filename="+user.GetConfigFileName())
c.Data(http.StatusOK, "application/config", cfg)
return
}
func (s *Server) GetPeerConfigMail(c *gin.Context) {
user := s.users.GetUserByKey(c.Query("pkey"))
currentSession := s.getSessionData(c)
if !currentSession.IsAdmin && user.Email != currentSession.Email {
s.GetHandleError(c, http.StatusUnauthorized, "No permissions", "You don't have permissions to view this resource!")
return
}
2021-02-21 17:23:58 -05:00
cfg, err := user.GetConfigFile(s.users.GetDevice())
2020-11-10 03:31:02 -05:00
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "ConfigFile error", err.Error())
return
}
png, err := user.GetQRCode()
if err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "QRCode error", err.Error())
return
}
// Apply mail template
var tplBuff bytes.Buffer
if err := s.mailTpl.Execute(&tplBuff, struct {
2021-02-21 17:23:58 -05:00
Client Peer
2020-11-10 03:31:02 -05:00
QrcodePngName string
PortalUrl string
}{
Client: user,
QrcodePngName: "wireguard-config.png",
PortalUrl: s.config.Core.ExternalUrl,
}); err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "Template error", err.Error())
return
}
// Send mail
attachments := []common.MailAttachment{
{
Name: user.GetConfigFileName(),
ContentType: "application/config",
Data: bytes.NewReader(cfg),
},
{
Name: "wireguard-config.png",
ContentType: "image/png",
Data: bytes.NewReader(png),
},
}
if err := common.SendEmailWithAttachments(s.config.Email, s.config.Core.MailFrom, "", "WireGuard VPN Configuration",
"Your mail client does not support HTML. Please find the configuration attached to this mail.", tplBuff.String(),
[]string{user.Email}, attachments); err != nil {
s.GetHandleError(c, http.StatusInternalServerError, "Email error", err.Error())
return
}
2020-11-10 16:23:05 -05:00
s.setFlashMessage(c, "mail sent successfully", "success")
2020-11-10 03:31:02 -05:00
c.Redirect(http.StatusSeeOther, "/admin")
}
2020-11-10 16:23:05 -05:00
func (s *Server) GetPeerStatus(c *gin.Context) {
user := s.users.GetUserByKey(c.Query("pkey"))
currentSession := s.getSessionData(c)
if !currentSession.IsAdmin && user.Email != currentSession.Email {
s.GetHandleError(c, http.StatusUnauthorized, "No permissions", "You don't have permissions to view this resource!")
return
}
if user.Peer == nil { // no peer means disabled
c.JSON(http.StatusOK, false)
return
}
isOnline := false
ping := make(chan bool)
defer close(ping)
for _, cidr := range user.IPs {
ip, _, _ := net.ParseCIDR(cidr)
var ra *net.IPAddr
if common.IsIPv6(ip.String()) {
ra, _ = net.ResolveIPAddr("ip6:ipv6-icmp", ip.String())
} else {
ra, _ = net.ResolveIPAddr("ip4:icmp", ip.String())
}
p := fastping.NewPinger()
p.AddIPAddr(ra)
p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
ping <- true
p.Stop()
}
p.OnIdle = func() {
ping <- false
p.Stop()
}
p.MaxRTT = 500 * time.Millisecond
p.RunLoop()
if <-ping {
isOnline = true
break
}
}
c.JSON(http.StatusOK, isOnline)
return
}