/
server.go
109 lines (93 loc) · 2.67 KB
/
server.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
package atm
import (
"log"
"net/http"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
)
const (
HOST = "https://o3.omrf.org"
DURATION = 5 * time.Minute
)
type Server struct {
Ds *Datastore
Object_host string
Default_duration int64
Nonces NonceChecker
}
func (a *Server) Run() {
e := echo.New()
// Middleware
e.Use(mw.Logger())
e.Use(mw.Recover())
auth_opts := NewHmacOpts(a.Ds.ApiKeySecret, a.Nonces)
e.Use(HMACAuth(auth_opts))
v1 := e.Group("/v1")
v1.Post("/urls", a.createUrl)
v1.Put("/keys/:name", a.setKey)
v1.Delete("/keys/:name", a.removeKey)
e.Run(":8080")
}
type keyRequest struct {
Key string `json:key`
}
func (s *Server) removeKey(c *echo.Context) error {
a, err := s.Ds.Account(c.Param("name"))
if nil != err || a.Id == "" {
return c.JSON(http.StatusGone, ErrMsg(http.StatusText(http.StatusNotFound)))
}
if c.Get(API_KEY) != a.Id {
return c.JSON(http.StatusForbidden, ErrMsg("Not authorized for this account"))
}
s.Ds.RemoveSigningKeyForAccount(a.Id)
return c.JSON(http.StatusNoContent, a)
}
func (s *Server) setKey(c *echo.Context) error {
k := &keyRequest{}
if err := c.Bind(k); nil != err {
return c.JSON(http.StatusBadRequest, ErrMsg(err.Error()))
}
a, err := s.Ds.Account(c.Param("name"))
if nil != err || a.Id == "" {
return c.JSON(http.StatusGone, ErrMsg(http.StatusText(http.StatusNotFound)))
}
if c.Get(API_KEY) != a.Id {
return c.JSON(http.StatusForbidden, ErrMsg("Not authorized for this account"))
}
s.Ds.AddSigningKeyForAccount(k.Key, a.Id)
return c.JSON(http.StatusOK, a)
}
func (s *Server) createUrl(c *echo.Context) error {
o := &UrlRequest{Host: s.Object_host, Duration: s.Default_duration}
if err := c.Bind(o); nil != err {
return c.JSON(http.StatusBadRequest, ErrMsg(err.Error()))
}
if !o.Valid() {
return c.JSON(http.StatusBadRequest, ErrMsg("Missing account, container, object, or method"))
}
duration := int64(0)
var err error
requestorId, ok := c.Get(API_KEY).(string)
if !ok {
return c.JSON(http.StatusInternalServerError, ErrMsg("Failed getting requesting id"))
}
o.Key, duration, err = s.Ds.KeyForRequest(o, requestorId)
if nil != err {
log.Printf("keyForRequest: %v, %s. Error: %s", o, "", err.Error())
return c.JSON(http.StatusInternalServerError, ErrMsg("Trouble checking authorization"))
}
if "" == o.Key {
return c.JSON(http.StatusForbidden, ErrMsg("Not authorized for this resource"))
}
if duration > 0 && duration > o.Duration {
o.Duration = duration
}
u := &Tmpurl{
Url: o.SignedUrl(),
Path: o.Path(),
}
c.Response().Header().Set("Location", u.Url)
return c.JSON(http.StatusCreated, u)
}