Newer
Older
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
package routes
import (
"database/sql"
"net/http"
"strings"
"owo.codes/whats-this/api/lib/apierrors"
"owo.codes/whats-this/api/lib/db"
"owo.codes/whats-this/api/lib/middleware"
"github.com/go-chi/render"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
// objectsResponse is the response format for Object.
type objectResponse struct {
Success bool `json:"success"`
Data db.Object `json:"data"`
}
// Object returns metadata about any object (even objects a user isn't
// associated with).
func Object(w http.ResponseWriter, r *http.Request) {
// Only authorized users can use this route
user := middleware.GetAuthorizedUser(r)
if user.ID == "" || user.IsBlocked {
panic(apierrors.Unauthorized)
}
// Get the key
key := r.URL.Path
if strings.HasPrefix(key, "/objects/") {
key = key[9:]
}
// Get the object
object, err := db.GetObject(viper.GetString("database.objectBucket"), key)
switch {
case errors.Cause(err) == sql.ErrNoRows:
panic(apierrors.NoObjectFound)
case err != nil:
log.Error().Err(err).Msg("failed to get object")
panic(apierrors.InternalServerError)
}
associatedWithCurrentUser := false
if object.AssociatedUser != nil && *object.AssociatedUser == user.ID {
associatedWithCurrentUser = true
}
object.AssociatedWithCurrentUser = &associatedWithCurrentUser
// Return response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
render.JSON(w, r, objectResponse{true, object})
}