-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
134 lines (113 loc) · 3.15 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"crypto/md5"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/golang-jwt/jwt/v5"
)
type FileInfo struct {
Name string
Path string
Size int64
FormattedSize string
Type string
Content string
TimeUploaded string
}
type TemplateData struct {
Files []FileInfo
URL string
}
func CheckAuth(r *http.Request, key string) bool {
receivedKey := r.Header.Get("X-Auth")
if receivedKey == key {
return true
} else if err := validateToken(receivedKey, key); err == nil {
return true
}
return false
}
func validateToken(tokenString, key string) error {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(key), nil
})
if err != nil {
return err
}
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return nil
} else {
return fmt.Errorf("invalid token")
}
}
func FormatFileSize(size int64) string {
if size < 1024 {
return fmt.Sprintf("%d B", size)
} else if size < 1024*1024 {
return fmt.Sprintf("%.2f KB", float64(size)/1024)
} else if size < 1024*1024*1024 {
return fmt.Sprintf("%.2f MB", float64(size)/(1024*1024))
}
return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024))
}
func HashFile(file io.Reader, extension string, full bool) (string, error) {
hasher := md5.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", err
}
sha1Hash := strings.ToUpper(hex.EncodeToString(hasher.Sum(nil)))
filename := fmt.Sprintf("%s%s", sha1Hash, extension)
if full {
return filename, nil
} else {
return fmt.Sprintf("%s%s", sha1Hash[:5], extension), nil
}
}
func SaveFile(name string, file io.Reader) error {
dst, err := os.Create(name)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
return err
}
return nil
}
func BasicAuth(next http.HandlerFunc, app *Application) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok {
// hash password received
usernameHash := sha256.Sum256([]byte(username))
passwordHash := sha256.Sum256([]byte(password))
// hash our password
expectedUsernameHash := sha256.Sum256([]byte(app.auth.username))
expectedPasswordHash := sha256.Sum256([]byte(app.auth.password))
// compare hashes
usernameMatch := (subtle.ConstantTimeCompare(usernameHash[:], expectedUsernameHash[:]) == 1)
passwordMatch := (subtle.ConstantTimeCompare(passwordHash[:], expectedPasswordHash[:]) == 1)
if usernameMatch && passwordMatch {
next.ServeHTTP(w, r)
return
}
}
w.Header().Set("WWW-Authenticate", `Basic realm="restricted", charset="UTF-8`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
})
}
func ResponseURLHandler(w http.ResponseWriter, url, filename string) {
pasteURL := fmt.Sprintf("http://%s/%s\n", url, filename)
w.Header().Set("Location", pasteURL)
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "%s", pasteURL)
}