Skip to content

Commit

Permalink
Login disable (#35)
Browse files Browse the repository at this point in the history
Add ability to disable authentication
  • Loading branch information
ngoduykhanh authored Oct 9, 2020
1 parent c205a04 commit 9dca2b7
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 41 deletions.
41 changes: 27 additions & 14 deletions handler/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package handler
import (
"encoding/json"
"fmt"
rice "github.com/GeertJohan/go.rice"
"net/http"
"strings"
"time"

rice "github.com/GeertJohan/go.rice"

"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
Expand Down Expand Up @@ -81,12 +82,13 @@ func WireGuardClients() echo.HandlerFunc {

clientDataList, err := util.GetClients(true)
if err != nil {
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, fmt.Sprintf("Cannot get client list: %v", err)})
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{
false, fmt.Sprintf("Cannot get client list: %v", err),
})
}

return c.Render(http.StatusOK, "clients.html", map[string]interface{}{
"baseData": model.BaseData{Active: ""},
"username": currentUser(c),
"baseData": model.BaseData{Active: "", CurrentUser: currentUser(c)},
"clientDataList": clientDataList,
})
}
Expand All @@ -100,7 +102,9 @@ func GetClients() echo.HandlerFunc {

clientDataList, err := util.GetClients(true)
if err != nil {
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, fmt.Sprintf("Cannot get client list: %v", err)})
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{
false, fmt.Sprintf("Cannot get client list: %v", err),
})
}

return c.JSON(http.StatusOK, clientDataList)
Expand Down Expand Up @@ -171,7 +175,9 @@ func NewClient() echo.HandlerFunc {
presharedKey, err := wgtypes.GenerateKey()
if err != nil {
log.Error("Cannot generated preshared key: ", err)
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, "Cannot generate Wireguard preshared key"})
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{
false, "Cannot generate Wireguard preshared key",
})
}

client.PrivateKey = key.String()
Expand Down Expand Up @@ -213,7 +219,9 @@ func UpdateClient() echo.HandlerFunc {
serverInterface := model.ServerInterface{}
if err := db.Read("server", "interfaces", &serverInterface); err != nil {
log.Error("Cannot fetch server interface config from database: ", err)
return c.JSON(http.StatusBadRequest, jsonHTTPResponse{false, fmt.Sprintf("Cannot fetch server config: %s", err)})
return c.JSON(http.StatusBadRequest, jsonHTTPResponse{
false, fmt.Sprintf("Cannot fetch server config: %s", err),
})
}

// validate the input Allocation IPs
Expand Down Expand Up @@ -346,8 +354,7 @@ func WireGuardServer() echo.HandlerFunc {
}

return c.Render(http.StatusOK, "server.html", map[string]interface{}{
"baseData": model.BaseData{Active: "wg-server"},
"username": currentUser(c),
"baseData": model.BaseData{Active: "wg-server", CurrentUser: currentUser(c)},
"serverInterface": server.Interface,
"serverKeyPair": server.KeyPair,
})
Expand Down Expand Up @@ -429,8 +436,7 @@ func GlobalSettings() echo.HandlerFunc {
}

return c.Render(http.StatusOK, "global_settings.html", map[string]interface{}{
"baseData": model.BaseData{Active: "global-settings"},
"username": currentUser(c),
"baseData": model.BaseData{Active: "global-settings", CurrentUser: currentUser(c)},
"globalSettings": globalSettings,
})
}
Expand Down Expand Up @@ -511,13 +517,18 @@ func SuggestIPAllocation() echo.HandlerFunc {
allocatedIPs, err := util.GetAllocatedIPs("")
if err != nil {
log.Error("Cannot suggest ip allocation. Failed to get list of allocated ip addresses: ", err)
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, "Cannot suggest ip allocation: failed to get list of allocated ip addresses"})
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{
false, "Cannot suggest ip allocation: failed to get list of allocated ip addresses",
})
}
for _, cidr := range server.Interface.Addresses {
ip, err := util.GetAvailableIP(cidr, allocatedIPs)
if err != nil {
log.Error("Failed to get available ip from a CIDR: ", err)
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, fmt.Sprintf("Cannot suggest ip allocation: failed to get available ip from network %s", cidr)})
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{
false,
fmt.Sprintf("Cannot suggest ip allocation: failed to get available ip from network %s", cidr),
})
}
suggestedIPs = append(suggestedIPs, fmt.Sprintf("%s/32", ip))
}
Expand Down Expand Up @@ -554,7 +565,9 @@ func ApplyServerConfig(tmplBox *rice.Box) echo.HandlerFunc {
err = util.WriteWireGuardServerConfig(tmplBox, server, clients, settings)
if err != nil {
log.Error("Cannot apply server config: ", err)
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{false, fmt.Sprintf("Cannot apply server config: %v", err)})
return c.JSON(http.StatusInternalServerError, jsonHTTPResponse{
false, fmt.Sprintf("Cannot apply server config: %v", err),
})
}

return c.JSON(http.StatusOK, jsonHTTPResponse{true, "Applied server config successfully"})
Expand Down
22 changes: 12 additions & 10 deletions handler/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,21 @@ import (

"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/ngoduykhanh/wireguard-ui/util"
)

// validSession to redirect user to the login page if they are not
// authenticated or session expired.
// validSession to redirect user to the login page if they are not authenticated or session expired.
func validSession(c echo.Context) {
sess, _ := session.Get("session", c)
cookie, err := c.Cookie("session_token")
if err != nil || sess.Values["session_token"] != cookie.Value {
nextURL := c.Request().URL
if nextURL != nil {
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("/login?next=%s", c.Request().URL))
} else {
c.Redirect(http.StatusTemporaryRedirect, "/login")
if !util.DisableLogin {
sess, _ := session.Get("session", c)
cookie, err := c.Cookie("session_token")
if err != nil || sess.Values["session_token"] != cookie.Value {
nextURL := c.Request().URL
if nextURL != nil {
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("/login?next=%s", c.Request().URL))
} else {
c.Redirect(http.StatusTemporaryRedirect, "/login")
}
}
}
}
Expand Down
45 changes: 32 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,39 +1,54 @@
package main

import (
"flag"
"fmt"
"net/http"
"time"

rice "github.com/GeertJohan/go.rice"
"github.com/labstack/echo/v4"
"github.com/ngoduykhanh/wireguard-ui/handler"
"github.com/ngoduykhanh/wireguard-ui/router"
"github.com/ngoduykhanh/wireguard-ui/util"
"net/http"
"time"
)

var appVersion = "development"
var gitCommit = "N/A"
var gitRef = "N/A"
var buildTime = fmt.Sprintf(time.Now().UTC().Format("01-02-2006 15:04:05"))
// command-line banner information
var (
appVersion = "development"
gitCommit = "N/A"
gitRef = "N/A"
buildTime = fmt.Sprintf(time.Now().UTC().Format("01-02-2006 15:04:05"))
)

func init() {
// command-line flags
flagDisableLogin := flag.Bool("disable-login", false, "Disable login page. Turn off authentication.")
flag.Parse()

// update runtime config
util.DisableLogin = *flagDisableLogin

func main() {
// print app information
fmt.Println("Wireguard UI")
fmt.Println("App Version\t:", appVersion)
fmt.Println("Git Commit\t:", gitCommit)
fmt.Println("Git Ref\t\t:", gitRef)
fmt.Println("Build Time\t:", buildTime)
fmt.Println("Git Repo\t:", "https://github.com/ngoduykhanh/wireguard-ui")

// set app extra data
extraData := make(map[string]string)
extraData["appVersion"] = appVersion
fmt.Println("Authentication\t:", !util.DisableLogin)

// initialize DB
err := util.InitDB()
if err != nil {
fmt.Print("Cannot init database: ", err)
}
}

func main() {
// set app extra data
extraData := make(map[string]string)
extraData["appVersion"] = appVersion

// create rice box for embedded template
tmplBox := rice.MustFindBox("templates")
Expand All @@ -45,8 +60,12 @@ func main() {
app := router.New(tmplBox, extraData)

app.GET("/", handler.WireGuardClients())
app.GET("/login", handler.LoginPage())
app.POST("/login", handler.Login())

if !util.DisableLogin {
app.GET("/login", handler.LoginPage())
app.POST("/login", handler.Login())
}

app.GET("/logout", handler.Logout())
app.POST("/new-client", handler.NewClient())
app.POST("/update-client", handler.UpdateClient())
Expand Down
2 changes: 1 addition & 1 deletion model/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Client struct {
ID string `json:"id"`
PrivateKey string `json:"private_key"`
PublicKey string `json:"public_key"`
PresharedKey string `json:"preshared_key"`
PresharedKey string `json:"preshared_key"`
Name string `json:"name"`
Email string `json:"email"`
AllocatedIPs []string `json:"allocated_ips"`
Expand Down
3 changes: 2 additions & 1 deletion model/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ type Interface struct {

// BaseData struct to pass value to the base template
type BaseData struct {
Active string
Active string
CurrentUser string
}
6 changes: 4 additions & 2 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@
<button style="margin-left: 0.5em;" type="button" class="btn btn-outline-danger btn-sm" data-toggle="modal"
data-target="#modal_apply_config"><i class="nav-icon fas fa-check"></i> Apply
Config</button>
{{if .baseData.CurrentUser}}
<button onclick="location.href='/logout';" style="margin-left: 0.5em;" type="button"
class="btn btn-outline-danger btn-sm"><i class="nav-icon fas fa-sign-out-alt"></i> Logout</button>
{{end}}
</div>
</nav>
<!-- /.navbar -->
Expand All @@ -87,15 +89,15 @@
<i class="nav-icon fas fa-2x fa-user"></i>
</div>
<div class="info">
<a href="#" class="d-block">{{template "username" .}}</a>
<a href="#" class="d-block">{{if .baseData.CurrentUser}} {{.baseData.CurrentUser}} {{else}} Administrator {{end}}</a>
</div>
</div>

<!-- Sidebar Menu -->
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<li class="nav-item">
<a href="/" class="nav-link {{if eq .baseData.Active "" }}active{{end}}">
<a href="/" class="nav-link {{if eq .baseData.Active ""}}active{{end}}">
<i class="nav-icon fas fa-user-secret"></i>
<p>
Wireguard Clients
Expand Down
6 changes: 6 additions & 0 deletions util/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package util

// Runtime config
var (
DisableLogin bool
)

0 comments on commit 9dca2b7

Please sign in to comment.