-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
72 lines (59 loc) · 2.09 KB
/
api.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
package api
import (
"context"
"net/http"
"github.com/ONSdigital/dp-authorisation/auth"
"github.com/ONSdigital/dp-net/request"
"github.com/ONSdigital/dp-observation-api/config"
"github.com/ONSdigital/log.go/log"
"github.com/gorilla/mux"
)
//API provides a struct to wrap the api around
type API struct {
cfg *config.Config
Router *mux.Router
graphDB IGraph
datasetClient IDatasetClient
cantabularClient CantabularClient
permissions IAuthHandler
}
// Setup creates the API struct and its endpoints with corresponding handlers
func Setup(ctx context.Context, r *mux.Router, cfg *config.Config, graphDB IGraph, datasetClient IDatasetClient, cantabularClient CantabularClient, permissions IAuthHandler) *API {
api := &API{
cfg: cfg,
Router: r,
graphDB: graphDB,
datasetClient: datasetClient,
cantabularClient: cantabularClient,
permissions: permissions,
}
if api.cfg.EnablePrivateEndpoints {
read := auth.Permissions{Read: true}
r.HandleFunc("/datasets/{dataset_id}/editions/{edition}/versions/{version}/observations", permissions.Require(read, api.getObservations)).Methods(http.MethodGet)
} else {
r.HandleFunc("/datasets/{dataset_id}/editions/{edition}/versions/{version}/observations", api.getObservations).Methods(http.MethodGet)
}
return api
}
func (api *API) checkIfAuthorised(r *http.Request, logData log.Data) (authorised bool) {
callerIdentity := request.Caller(r.Context())
if callerIdentity != "" {
logData["caller_identity"] = callerIdentity
authorised = true
}
userIdentity := request.User(r.Context())
if userIdentity != "" {
logData["user_identity"] = userIdentity
authorised = true
}
logData["authenticated"] = authorised
return authorised
}
func setJSONContentType(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
}
// Close is called during graceful shutdown to give the API an opportunity to perform any required disposal task
func (*API) Close(ctx context.Context) error {
log.Event(ctx, "graceful shutdown of api complete", log.INFO)
return nil
}