added whitelist frontend

This commit is contained in:
2025-12-06 10:21:43 +00:00
parent 99c005e4d2
commit 7644f83e52
6 changed files with 193 additions and 1 deletions

View File

@@ -37,6 +37,7 @@ type Config struct {
URLFileList string `json:"url_file_list"`
BlocklistFile string `json:"blocklist_file"`
RemoveFile string `json:"remove_file"`
WhitelistFile string `json:"whitelist_file"`
MergedListTmp string `json:"merged_list_tmp"`
// Default blocklist URLs
@@ -67,6 +68,7 @@ func getDefaultConfig() Config {
URLFileList: "/sdcard1/urllist.csv",
BlocklistFile: "/run/utm/domain_list/domainlist_0.list",
RemoveFile: "/run/utm/domain_list/domainlist_1.list",
WhitelistFile: "custom_whitelist.txt",
MergedListTmp: "/tmp/mergedlist.txt",
DefaultURLs: []URLListItem{
{Name: "AdGuard DNS filter", Enabled: true, Group: "Default", URL: "https://adguardteam.github.io/HostlistsRegistry/assets/filter_27.txt"},

View File

@@ -320,6 +320,57 @@ func domainsHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, r, "domains.html", pageData)
}
func whitelistHandler(w http.ResponseWriter, r *http.Request) {
pageData := map[string]interface{}{
"Domains": []string{},
"Query": "",
"Notification": "",
"NotificationType": "",
}
if r.Method == http.MethodPost {
action := r.FormValue("action")
if action == "add_domain" {
domain := strings.TrimSpace(r.FormValue("domain"))
if domain == "" {
pageData["Notification"] = "Domain cannot be empty."
pageData["NotificationType"] = "error"
} else {
configMu.RLock()
whitelistFile := config.WhitelistFile
configMu.RUnlock()
// Read current whitelist
lines, err := readLines(whitelistFile)
if err != nil {
lines = []string{}
}
// Check if already exists
exists := false
for _, d := range lines {
if strings.EqualFold(d, domain) {
exists = true
break
}
}
if exists {
pageData["Notification"] = "Domain already in whitelist."
pageData["NotificationType"] = "error"
} else {
lines = append(lines, domain)
writeLines(whitelistFile, lines)
pageData["Notification"] = "Domain added to whitelist."
pageData["NotificationType"] = "success"
}
}
}
}
renderTemplate(w, r, "whitelist.html", pageData)
}
func searchDomainsHandler(w http.ResponseWriter, r *http.Request) {
configMu.RLock()
blocklistFile := config.BlocklistFile
@@ -370,6 +421,87 @@ func searchDomainsHandler(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]interface{}{"domains": filtered})
}
func searchWhitelistHandler(w http.ResponseWriter, r *http.Request) {
configMu.RLock()
removeFile := config.RemoveFile
whitelistFile := config.WhitelistFile
configMu.RUnlock()
query := strings.TrimSpace(r.FormValue("query"))
if query == "" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"results": []map[string]string{}})
return
}
// Read both files
domains1, err1 := readLines(removeFile)
domains2, err2 := readLines(whitelistFile)
if err1 != nil && err2 != nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"results": []map[string]string{}})
return
}
// Create maps for quick lookup
removeMap := make(map[string]bool)
for _, d := range domains1 {
removeMap[strings.ToLower(d)] = true
}
whitelistMap := make(map[string]bool)
for _, d := range domains2 {
whitelistMap[strings.ToLower(d)] = true
}
// Combine unique domains
domainMap := make(map[string]bool)
for d := range removeMap {
domainMap[d] = true
}
for d := range whitelistMap {
domainMap[d] = true
}
var filtered []map[string]string
for d := range domainMap {
var source string
inRemove := removeMap[d]
inWhitelist := whitelistMap[d]
if inRemove && inWhitelist {
source = "Both"
} else if inRemove {
source = "Unifi"
} else {
source = "Custom"
}
match := false
if strings.Contains(query, "*") {
// Wildcard search
pattern := strings.ReplaceAll(regexp.QuoteMeta(query), "\\*", ".*")
re, err := regexp.Compile("(?i)^" + pattern + "$")
if err == nil && re.MatchString(d) {
match = true
}
} else {
// Exact match, case insensitive
if strings.EqualFold(d, query) {
match = true
}
}
if match {
filtered = append(filtered, map[string]string{"domain": d, "source": source})
if len(filtered) >= 100 {
break
}
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{"results": filtered})
}
func applyHandler(w http.ResponseWriter, r *http.Request) {
userInitiatedMu.Lock()
userInitiated = true

View File

@@ -66,9 +66,11 @@ func main() {
r.HandleFunc("/profile", authMiddleware(profileHandler)).Methods("GET", "POST")
r.HandleFunc("/api/mfa-setup", authMiddleware(mfaSetupHandler)).Methods("POST")
r.HandleFunc("/api/search-domains", authMiddleware(searchDomainsHandler)).Methods("POST")
r.HandleFunc("/api/search-whitelist", authMiddleware(searchWhitelistHandler)).Methods("POST")
r.HandleFunc("/", authMiddleware(dashboardHandler))
r.HandleFunc("/urllists", authMiddleware(urlListsHandler)).Methods("GET", "POST")
r.HandleFunc("/domains", authMiddleware(domainsHandler)).Methods("GET", "POST")
r.HandleFunc("/whitelist", authMiddleware(whitelistHandler)).Methods("GET", "POST")
r.HandleFunc("/apply", authMiddleware(applyHandler)).Methods("POST")
r.HandleFunc("/logs", authMiddleware(logsHandler))

File diff suppressed because one or more lines are too long

View File

@@ -15,6 +15,7 @@
<ul class="flex space-x-4">
<li><a href="/urllists">URL Lists</a></li>
<li><a href="/domains">Blocked Domains</a></li>
<li><a href="/whitelist">Whitelisted Domains</a></li>
<li><a href="/logs">Logs</a></li>
<li><a href="/profile">Profile</a></li>
<li><a href="/logout">Logout</a></li>

55
templates/whitelist.html Normal file
View File

@@ -0,0 +1,55 @@
{{ define "content" }}
<div class="max-w-4xl mx-auto">
<h1 class="text-3xl font-bold mb-6">Whitelisted Domains</h1>
<div class="mb-6 bg-gray-800 p-4 rounded">
<div class="flex gap-2 mb-4">
<input type="text" id="query" placeholder="Search domains exact match (use * as wildcard)" onkeydown="if(event.key === 'Enter') searchWhitelist()" class="flex-1 p-2 bg-gray-700 rounded text-white placeholder-gray-400">
<button type="button" onclick="searchWhitelist()" class="bg-blue-600 hover:bg-blue-700 text-white font-bold px-4 py-2 rounded transition">Search</button>
</div>
<form method="POST" action="/whitelist" class="flex gap-2">
<input type="hidden" name="action" value="add_domain">
<input type="hidden" name="csrf_token" value="{{ .CSRFToken }}">
<input type="text" name="domain" placeholder="Enter domain to add" class="flex-1 p-2 bg-gray-700 rounded text-white placeholder-gray-400">
<button type="submit" class="bg-green-600 hover:bg-green-700 text-white font-bold px-4 py-2 rounded transition">Add</button>
</form>
</div>
<div id="results"></div>
</div>
<script>
function searchWhitelist() {
const query = document.getElementById('query').value.trim();
if (!query) {
document.getElementById('results').innerHTML = '<p class="text-gray-300">Please enter a search query.</p>';
return;
}
document.getElementById('results').innerHTML = '<p class="text-gray-300">Searching...</p>';
fetch('/api/search-whitelist', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRF-Token': '{{ .CSRFToken }}'
},
body: 'query=' + encodeURIComponent(query)
})
.then(response => response.json())
.then(data => {
let html = '';
if (data.results && data.results.length > 0) {
html = '<h2 class="text-xl font-bold mb-4">Results (' + data.results.length + ' found)</h2>';
html += '<ul class="space-y-2 max-h-96 overflow-y-auto">';
data.results.forEach(r => {
html += '<li class="bg-gray-800 p-3 rounded flex justify-between"><span class="text-sm text-gray-300 break-all">' + r.domain + '</span><span class="text-sm text-blue-400 select-none">' + r.source + '</span></li>';
});
html += '</ul>';
} else {
html = '<p class="text-gray-300">No results found for \'' + query + '\'</p>';
}
document.getElementById('results').innerHTML = html;
})
.catch(error => {
document.getElementById('results').innerHTML = '<p class="text-red-400">Error searching domains.</p>';
});
}
</script>
{{ end }}</content>
<parameter name="filePath">/home/nahaku/Downloads/unifi_mama_bcp/script/goapp/templates/whitelist.html