/
middleware.go
87 lines (76 loc) · 2.28 KB
/
middleware.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
package main
import (
"errors"
"github.com/PandoCloud/pando-cloud/pkg/models"
"github.com/PandoCloud/pando-cloud/pkg/server"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"net/http"
"strconv"
"strings"
)
func checkAppDomain(domain string, identifier string) error {
domainPieces := strings.Split(domain, "/")
identifierPieces := strings.Split(identifier, "-")
if len(domainPieces) == 0 {
return errors.New("wrong app domain format.")
}
if len(identifierPieces) != 3 {
return errors.New("wrong identifier format.")
}
devvendorid, err := strconv.ParseUint(identifierPieces[0], 16, 64)
if err != nil {
return errors.New("wrong vendor format.")
}
devproductid, err := strconv.ParseUint(identifierPieces[1], 16, 64)
if err != nil {
return errors.New("wrong product format.")
}
if len(domainPieces) == 1 {
if domainPieces[0] != "*" {
return errors.New("wrong app domain " + domainPieces[0])
}
return nil
}
if len(domainPieces) == 2 {
id, err := strconv.ParseUint(domainPieces[1], 10, 64)
if err != nil {
return errors.New("wrong app domain format..")
}
if domainPieces[0] == "vendor" {
if id != devvendorid {
return errors.New("app has no access right on device.")
}
} else if domainPieces[0] == "product" {
if id != devproductid {
return errors.New("app has no access right on device.")
}
} else {
return errors.New("wrong app domain" + domain)
}
}
if len(domainPieces) > 2 {
return errors.New("wrong app domain" + domainPieces[0])
}
return nil
}
// check if app has access right on device of given identifier( in url params )
func ApplicationAuthOnDeviceIdentifer(context martini.Context, params martini.Params, req *http.Request, r render.Render) {
identifier := params["identifier"]
key := req.Header.Get("App-Key")
if identifier == "" || key == "" {
r.JSON(http.StatusOK, renderError(ErrDeviceNotFound, errors.New("missing device identifier or app key.")))
return
}
app := &models.Application{}
err := server.RPCCallByName("registry", "Registry.ValidateApplication", key, app)
if err != nil {
r.JSON(http.StatusOK, renderError(ErrAccessDenied, err))
return
}
err = checkAppDomain(app.AppDomain, identifier)
if err != nil {
r.JSON(http.StatusOK, renderError(ErrAccessDenied, err))
return
}
}