Skip to content

Commit

Permalink
added authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
glblduh committed Aug 18, 2024
1 parent 411f7a1 commit fe42a04
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 16 deletions.
61 changes: 61 additions & 0 deletions auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"net/http"
"net/url"
"os"

"github.com/gorilla/mux"
)

// Check if authentication is enabled
func checkAuthEnabled(isEnabled bool) {
authEnabled = isEnabled
// If authentication is disabled
if !isEnabled {
Warn.Println("Authentication is disabled")
return
}

// Gets the key from env variable
key, isValid := os.LookupEnv("TORRENTTPKEY")

// Check if key is empty or unset
if key == "" || !isValid {
Error.Fatalln("Auth flag is enabled but TORRENTTPKEY env variable is empty or unset")
}

// Set the API key to the value of TORRENTTPKEY
apiKey = key

Info.Println("Authentication is enabled")
}

// Check for API key on the HTTP parameter
func checkAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Check if authencation is enabled
if !authEnabled {
next(w, r)
}

// Get API key from HTTP parameter
vars := mux.Vars(r)
key := vars["key"]

// Unescape the API key
unescapedKey, unescapeErr := url.QueryUnescape(key)
if unescapeErr != nil {
errorRes(w, "Error unescaping the API key", http.StatusInternalServerError)
return
}

// Check if API key is valid
if unescapedKey != apiKey {
errorRes(w, "Key is not valid", http.StatusForbidden)
return
}

next(w, r)
}
}
8 changes: 7 additions & 1 deletion functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,14 @@ func createFileLink(infohash string, filename string, isFile bool) string {
if isFile {
verb = "file"
}
return "/api/" + verb + "/" + infohash + "/" + url.QueryEscape(filename)

link := "/api/" + verb + "/" + infohash + "/" + url.QueryEscape(filename)

if authEnabled {
link = link + "?key=" + url.QueryEscape(apiKey)
}

return link
}

// Get the file handle inside the torrent
Expand Down
4 changes: 4 additions & 0 deletions globals.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ var (
/* BitTorrent client */
btEngine btEng

/* Authentication */
authEnabled bool
apiKey string

/* Loggers */
// For information
Info = log.New(os.Stderr, "["+time.Now().Format("2006/01/02 15:04:05")+"] [INFO] ", log.Lmsgprefix)
Expand Down
28 changes: 13 additions & 15 deletions torrenttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ func main() {
dirFlag := flag.String("dir", "torrenttpdl", "Download directory path")
portFlag := flag.String("port", ":1010", "HTTP server listening port")
noupFlag := flag.Bool("noup", false, "Disables BT client upload")
pwFlag := flag.String("pw", "changeme", "Set the password for the API")
authFlag := flag.Bool("auth", false, "Enable API key authentication from the env varible TORRENTTPKEY")
flag.Parse()

// Check if authentication is enabled
checkAuthEnabled(*authFlag)

// Creates the BitTorrent client with user args
btEngine.initialize(newBtCliConfs(*dirFlag, *noupFlag))

Expand All @@ -32,19 +35,19 @@ func main() {
/* Handlers for endpoints */

/* POST */
r.HandleFunc("/api/addtorrent", apiAddTorrent).Methods("POST")
r.HandleFunc("/api/selectfile", apiTorrentSelectFile).Methods("POST")
r.HandleFunc("/api/setpriority", apiTorrentPriorityFile).Methods("POST")
r.HandleFunc("/api/addtorrentfile", apiAddTorrentFile).Methods("POST")
r.HandleFunc("/api/addtorrent", checkAuth(apiAddTorrent)).Methods("POST")
r.HandleFunc("/api/selectfile", checkAuth(apiTorrentSelectFile)).Methods("POST")
r.HandleFunc("/api/setpriority", checkAuth(apiTorrentPriorityFile)).Methods("POST")
r.HandleFunc("/api/addtorrentfile", checkAuth(apiAddTorrentFile)).Methods("POST")

/* DELETE */
r.HandleFunc("/api/removetorrent", apiRemoveTorrent).Methods("DELETE")
r.HandleFunc("/api/removetorrent", checkAuth(apiRemoveTorrent)).Methods("DELETE")

/* GET */
r.HandleFunc("/api/stream/{infohash}/{file:.*}", apiStreamTorrentFile).Methods("GET")
r.HandleFunc("/api/file/{infohash}/{file:.*}", apiDownloadFile).Methods("GET")
r.HandleFunc("/api/torrents", apiTorrentStats).Methods("GET")
r.HandleFunc("/api/torrents/{infohash}", apiTorrentStats).Methods("GET")
r.HandleFunc("/api/stream/{infohash}/{file:.*}", checkAuth(apiStreamTorrentFile)).Methods("GET")
r.HandleFunc("/api/file/{infohash}/{file:.*}", checkAuth(apiDownloadFile)).Methods("GET")
r.HandleFunc("/api/torrents", checkAuth(apiTorrentStats)).Methods("GET")
r.HandleFunc("/api/torrents/{infohash}", checkAuth(apiTorrentStats)).Methods("GET")

/* CORS middleware */
c := cors.New(cors.Options{
Expand All @@ -53,11 +56,6 @@ func main() {
AllowCredentials: true,
}).Handler(r)

/* Warn if password is unchanged */
if *pwFlag == "changeme" {
Warn.Printf("Please change the password")
}

Info.Printf("Starting HTTP server on port: %s", *portFlag)
Error.Fatalln(http.ListenAndServe(*portFlag, c))
}

0 comments on commit fe42a04

Please sign in to comment.