add endpoint to check if password exists

This commit is contained in:
1e99 2024-10-30 00:36:53 +01:00
parent c8bbe24d4d
commit b0baf85078
4 changed files with 36 additions and 1 deletions

View file

@ -26,6 +26,7 @@ func run() error {
mux.Handle("GET /", routes.ServeFiles(embedFS, "static")) mux.Handle("GET /", routes.ServeFiles(embedFS, "static"))
mux.Handle("POST /api/password", routes.CreatePassword(storage, 12*1024, base64.StdEncoding)) mux.Handle("POST /api/password", routes.CreatePassword(storage, 12*1024, base64.StdEncoding))
mux.Handle("GET /api/password/{id}", routes.GetPassword(storage, base64.StdEncoding)) mux.Handle("GET /api/password/{id}", routes.GetPassword(storage, base64.StdEncoding))
mux.Handle("HEAD /api/password/{id}", routes.HasPassword(storage))
address := os.Getenv("PASSED_ADDRESS") address := os.Getenv("PASSED_ADDRESS")
if address == "" { if address == "" {

24
routes/has_password.go Normal file
View file

@ -0,0 +1,24 @@
package routes
import (
"net/http"
"git.1e99.eu/1e99/passed/storage"
)
func HasPassword(store storage.Store) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
id := req.PathValue("id")
found, err := store.HasPassword(id)
if err != nil {
http.Error(res, "", http.StatusInternalServerError)
return
}
if found {
res.WriteHeader(http.StatusNoContent)
} else {
res.WriteHeader(http.StatusNotFound)
}
}
}

View file

@ -60,6 +60,14 @@ func (store *ram) GetPassword(id string) ([]byte, error) {
return password.password, nil return password.password, nil
} }
func (store *ram) HasPassword(id string) (bool, error) {
store.lock.Lock()
defer store.lock.Unlock()
_, found := store.passwords[id]
return found, nil
}
func (store *ram) Close() error { func (store *ram) Close() error {
store.close <- true store.close <- true
return nil return nil
@ -75,7 +83,6 @@ func (store *ram) clearExpired() error {
return nil return nil
case <-ticker.C: case <-ticker.C:
store.lock.Lock() store.lock.Lock()
defer store.lock.Unlock()
time := time.Now() time := time.Now()
for id, password := range store.passwords { for id, password := range store.passwords {
@ -83,6 +90,8 @@ func (store *ram) clearExpired() error {
delete(store.passwords, id) delete(store.passwords, id)
} }
} }
store.lock.Unlock()
} }
} }
} }

View file

@ -21,6 +21,7 @@ type entry struct {
type Store interface { type Store interface {
CreatePassword(password []byte, expiresAt time.Time) (string, error) CreatePassword(password []byte, expiresAt time.Time) (string, error)
GetPassword(id string) ([]byte, error) GetPassword(id string) ([]byte, error)
HasPassword(id string) (bool, error)
Close() error Close() error
} }