Skip to content

Commit

Permalink
feat: protect your website with a password
Browse files Browse the repository at this point in the history
  • Loading branch information
jeessy2 committed Sep 10, 2020
1 parent 539eac8 commit 54105d9
Show file tree
Hide file tree
Showing 10 changed files with 147 additions and 39 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
- 间隔5分钟同步一次
- 支持多个域名同时解析,公司必备
- 支持多级域名
- 网页中配置,简单又方便
- 网页中方便快速查看最近50条日志
- 网页中配置,简单又方便,可设置登录用户名和密码
- 网页中方便快速查看最近50条日志,不需要跑docker中查看

## 系统中使用
- 下载并解压[https://github.com/jeessy2/ddns-go/releases](https://github.com/jeessy2/ddns-go/releases)
Expand All @@ -28,15 +28,16 @@ docker run -d \

## 使用IPV6
- 前提:你的电脑或终端能正常获取IPV6
- Windows/Mac系统推荐在 `系统中使用`,Windows/Mac桌面版的docker不支持主机网络
- Linux的x86或arm架构,如服务器、群晖、xx盒子等等,推荐使用docker host模式,简单点
- Windows/Mac系统推荐在 `系统中使用`,Windows/Mac桌面版的docker不支持`--net=host`
- Linux的x86或arm架构,如服务器、群晖、xx盒子等等,推荐使用`--net=host`模式,简单点
```
docker run -d \
--name ddns-go \
--restart=always \
--net=host \
jeessy/ddns-go
```
- [可选] 使用IPV6后,建议设置登录用户名和密码

![avatar](ddns-web.png)

Expand Down
48 changes: 42 additions & 6 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"os"
"regexp"
"sync"

"gopkg.in/yaml.v2"
)
Expand All @@ -30,6 +31,7 @@ type Config struct {
Domains []string
}
DNS DNSConfig
User
}

// DNSConfig DNS配置
Expand All @@ -39,21 +41,55 @@ type DNSConfig struct {
Secret string
}

// InitConfigFromFile 获得配置
func (conf *Config) InitConfigFromFile() error {
// ConfigCache ConfigCache
var configCache *Config
var lock sync.Mutex

// GetConfigCache 获得配置
func GetConfigCache() (conf Config, err error) {
if configCache != nil {
return *configCache, nil
}
lock.Lock()
defer lock.Unlock()

configCache = &Config{}

configFilePath := util.GetConfigFilePath()
_, err := os.Stat(configFilePath)
_, err = os.Stat(configFilePath)
if err != nil {
log.Println("没有找到配置文件!请在网页中输入")
return err
return *configCache, err
}

byt, err := ioutil.ReadFile(configFilePath)
if err != nil {
log.Println("config.yaml读取失败")
return *configCache, err
}

yaml.Unmarshal(byt, configCache)
return *configCache, nil
}

// SaveConfig 保存配置
func (conf *Config) SaveConfig() (err error) {
byt, err := yaml.Marshal(conf)
if err != nil {
log.Println(err)
return err
}
yaml.Unmarshal(byt, conf)
return nil

err = ioutil.WriteFile(util.GetConfigFilePath(), byt, 0600)
if err != nil {
log.Println(err)
return
}

// 清空配置缓存
configCache = nil

return
}

// GetIpv4Addr 获得IPV4地址
Expand Down
59 changes: 59 additions & 0 deletions config/uesr.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package config

import (
"bytes"
"encoding/base64"
"net/http"
"strings"
)

// User 登录用户
type User struct {
Username string
Password string
}

// ViewFunc func
type ViewFunc func(http.ResponseWriter, *http.Request)

// BasicAuth basic auth
func BasicAuth(f ViewFunc) ViewFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 帐号或密码为空。跳过
conf, _ := GetConfigCache()
if conf.Username == "" && conf.Password == "" {
// 执行被装饰的函数
f(w, r)
return
}

// 认证帐号密码
basicAuthPrefix := "Basic "

// 获取 request header
auth := r.Header.Get("Authorization")
// 如果是 http basic auth
if strings.HasPrefix(auth, basicAuthPrefix) {
// 解码认证信息
payload, err := base64.StdEncoding.DecodeString(
auth[len(basicAuthPrefix):],
)
if err == nil {
pair := bytes.SplitN(payload, []byte(":"), 2)
if len(pair) == 2 &&
bytes.Equal(pair[0], []byte(conf.Username)) &&
bytes.Equal(pair[1], []byte(conf.Password)) {
// 执行被装饰的函数
f(w, r)
return
}
}
}

// 认证失败,提示 401 Unauthorized
// Restricted 可以改成其他的值
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
// 401 状态码
w.WriteHeader(http.StatusUnauthorized)
}
}
Binary file modified ddns-web.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 2 additions & 3 deletions dns/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ func RunTimer() {

// RunOnce RunOnce
func RunOnce() {
conf := &config.Config{}
err := conf.InitConfigFromFile()
conf, err := config.GetConfigCache()
if err != nil {
return
}
Expand All @@ -82,7 +81,7 @@ func RunOnce() {
default:
dnsSelected = &Alidns{}
}
dnsSelected.Init(conf)
dnsSelected.Init(&conf)
dnsSelected.AddUpdateIpv4DomainRecords()
dnsSelected.AddUpdateIpv6DomainRecords()
}
Expand Down
7 changes: 4 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"ddns-go/config"
"ddns-go/dns"
"ddns-go/static"
"ddns-go/util"
Expand All @@ -17,9 +18,9 @@ func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(static.AssetFile())))
http.Handle("/favicon.ico", http.StripPrefix("/", http.FileServer(static.AssetFile())))

http.HandleFunc("/", web.Writing)
http.HandleFunc("/save", web.Save)
http.HandleFunc("/logs", web.Logs)
http.HandleFunc("/", config.BasicAuth(web.Writing))
http.HandleFunc("/save", config.BasicAuth(web.Save))
http.HandleFunc("/logs", config.BasicAuth(web.Logs))

// 打开浏览器
go util.OpenExplorer("http://127.0.0.1:" + port)
Expand Down
23 changes: 23 additions & 0 deletions static/pages/writing.html
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,29 @@ <h5 class="portlet__head">IPV6</h5>
</div>
</div>

<div class="portlet">
<h5 class="portlet__head">其它配置</h5>
<div class="portlet__body">

<div class="form-group row">
<label for="Username" class="col-sm-2 col-form-label">登录用户名</label>
<div class="col-sm-10">
<input class="form-control" name="Username" id="Username" value="{{.Username}}" aria-describedby="Username_help">
<small id="Username_help" class="form-text text-muted">为保护你的信息安全, 建议输入</small>
</div>
</div>

<div class="form-group row">
<label for="Password" class="col-sm-2 col-form-label">登录密码</label>
<div class="col-sm-10">
<input class="form-control" type="password" name="Password" id="Password" value="{{.Password}}" aria-describedby="password_help">
<small id="password_help" class="form-text text-muted">为保护你的信息安全, 建议输入</small>
</div>
</div>

</div>
</div>

<button type="submit" class="btn btn-primary">Save</button>

</form>
Expand Down
4 changes: 2 additions & 2 deletions util/staticPagesData.go

Large diffs are not rendered by default.

22 changes: 6 additions & 16 deletions web/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,19 @@ package web
import (
"ddns-go/config"
"ddns-go/dns"
"ddns-go/util"
"io/ioutil"
"log"
"net/http"
"strings"

"gopkg.in/yaml.v2"
)

// Save 保存
func Save(writer http.ResponseWriter, request *http.Request) {

conf := &config.Config{}
// 初始化以前的配置
conf.InitConfigFromFile()
conf, _ := config.GetConfigCache()

idNew := request.FormValue("DnsID")
secretNew := request.FormValue("DnsSecret")

idHide, secretHide := getHideIDSecret(conf)
idHide, secretHide := getHideIDSecret(&conf)

if idNew != idHide {
conf.DNS.ID = idNew
Expand All @@ -42,14 +35,11 @@ func Save(writer http.ResponseWriter, request *http.Request) {
conf.Ipv6.URL = request.FormValue("Ipv6Url")
conf.Ipv6.Domains = strings.Split(request.FormValue("Ipv6Domains"), "\r\n")

// 保存到用户目录
util.GetConfigFilePath()
byt, err := yaml.Marshal(conf)
if err != nil {
log.Println(err)
}
conf.Username = request.FormValue("Username")
conf.Password = request.FormValue("Password")

ioutil.WriteFile(util.GetConfigFilePath(), byt, 0600)
// 保存到用户目录
conf.SaveConfig()

// 只运行一次
go dns.RunOnce()
Expand Down
9 changes: 4 additions & 5 deletions web/writing.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@ func Writing(writer http.ResponseWriter, request *http.Request) {
return
}

conf := &config.Config{}
err = conf.InitConfigFromFile()
conf, err := config.GetConfigCache()
if err == nil {
// 隐藏真实的ID、Secret
idHide, secretHide := getHideIDSecret(conf)
// 已存在配置文件,隐藏真实的ID、Secret
idHide, secretHide := getHideIDSecret(&conf)
conf.DNS.ID = idHide
conf.DNS.Secret = secretHide
tmpl.Execute(writer, conf)
tmpl.Execute(writer, &conf)
return
}

Expand Down

0 comments on commit 54105d9

Please sign in to comment.