-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
220 lines (207 loc) · 6.84 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package wildlifenl
import (
"database/sql"
"fmt"
"log"
"math/rand/v2"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/UtrechtUniversity/wildlifenl/models"
"github.com/UtrechtUniversity/wildlifenl/stores"
"github.com/UtrechtUniversity/wildlifenl/timeseries"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/google/uuid"
"github.com/patrickmn/go-cache"
)
var (
relationalDB *sql.DB
timeseriesDB *timeseries.Timeseries
mailer *Mailer
sessions *cache.Cache
authRequests *cache.Cache
)
func Start(config *Configuration) error {
if err := initializeRelationalDB(config); err != nil {
return fmt.Errorf("could not initialize Relational database: %w", err)
}
if err := initializeTimeseriesDB(config); err != nil {
return fmt.Errorf("could not initiliaze Timeseries database: %w", err)
}
if err := initializeMailer(config); err != nil {
return fmt.Errorf("could not initialize Mailer service: %w", err)
}
if err := timeseriesDB.CreateBucketIfNotExists("animals"); err != nil {
return fmt.Errorf("could not create Timeseries bucket: %w", err)
}
if err := timeseriesDB.CreateBucketIfNotExists("humans"); err != nil {
return fmt.Errorf("could not create Timeseries bucket: %w", err)
}
sessions = cache.New(time.Duration(config.CacheSessionDurationMinutes)*time.Minute, 12*time.Hour)
authRequests = cache.New(time.Duration(config.CacheAuthRequestDurationMinutes)*time.Minute, 12*time.Hour)
apiConfig := huma.DefaultConfig(appName, config.Version)
apiConfig.Info.Description = appDescription
apiConfig.Security = []map[string][]string{{"auth": {}}}
apiConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{"auth": {Type: "http", Scheme: "bearer"}}
apiConfig.DocsPath = "/"
router := NewServeMux()
api := humago.New(router, apiConfig)
api.UseMiddleware(NewMiddleware(api))
huma.AutoRegister(api, newAlarmOperations())
huma.AutoRegister(api, newAnimalOperations())
huma.AutoRegister(api, newAnswerOperations())
huma.AutoRegister(api, newAuthOperations())
huma.AutoRegister(api, newBorneSensorDeploymentOperations())
huma.AutoRegister(api, newBorneSensorReadingOperations())
huma.AutoRegister(api, newConveyanceOperations())
huma.AutoRegister(api, newDetectionOperations())
huma.AutoRegister(api, newExperimentOperations())
huma.AutoRegister(api, newInteractionOperations())
huma.AutoRegister(api, newInteractionTypeOperations())
huma.AutoRegister(api, newLivingLabOperations())
huma.AutoRegister(api, newMessageOperations())
huma.AutoRegister(api, newProfileOperations())
huma.AutoRegister(api, newQuestionOperations())
huma.AutoRegister(api, newQuestionnaireOperations())
huma.AutoRegister(api, newResponseOperations())
huma.AutoRegister(api, newRoleOperations())
huma.AutoRegister(api, newSpeciesOperations())
huma.AutoRegister(api, newTrackingReadingOperations())
huma.AutoRegister(api, newTriggerTypeOperations())
huma.AutoRegister(api, newUserOperations())
huma.AutoRegister(api, newZoneOperations())
return http.ListenAndServe(config.Host+":"+strconv.Itoa(config.Port), router)
}
func initializeRelationalDB(config *Configuration) error {
connStr := "postgres://" + config.RelationalDatabaseUser + ":" + config.RelationalDatabasePass + "@" + config.RelationalDatabaseHost
if config.RelationalDatabasePort > 0 {
connStr += ":" + strconv.Itoa(config.RelationalDatabasePort)
}
connStr += "/" + config.RelationalDatabaseName + "?sslmode=" + config.RelationalDatabaseSSLmode
db, err := sql.Open("postgres", connStr)
if err != nil {
return err
}
db.SetConnMaxLifetime(1 * time.Hour)
relationalDB = db
return relationalDB.Ping()
}
func initializeTimeseriesDB(config *Configuration) error {
timeseriesDB = timeseries.NewTimeseries(config.TimeseriesDatabaseURL, config.TimeseriesDatabaseOrganization, config.TimeseriesDatabaseToken)
return timeseriesDB.Ping()
}
func initializeMailer(config *Configuration) error {
mailer = newMailer(config)
return mailer.Ping()
}
func NewMiddleware(api huma.API) func(ctx huma.Context, next func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
var anyOfNeededScopes []string
isAuthorizationRequired := false
for _, opScheme := range ctx.Operation().Security {
var ok bool
if anyOfNeededScopes, ok = opScheme["auth"]; ok {
isAuthorizationRequired = true
break
}
}
if !isAuthorizationRequired {
next(ctx)
return
}
token := strings.TrimPrefix(ctx.Header("Authorization"), "Bearer ")
if len(token) == 0 {
huma.WriteErr(api, ctx, http.StatusUnauthorized, "Missing bearer token.")
return
}
credential := getCredential(token)
if credential == nil {
huma.WriteErr(api, ctx, http.StatusUnauthorized, "Invalid bearer token.")
return
}
if len(anyOfNeededScopes) == 0 {
next(ctx)
return
}
for _, scope := range credential.Scopes {
if slices.Contains(anyOfNeededScopes, scope) {
next(ctx)
return
}
}
huma.WriteErr(api, ctx, http.StatusForbidden, "Bearer token is not authorized for any of the scopes: "+strings.Join(anyOfNeededScopes, ", "))
}
}
func authenticate(displayNameApp, email string) error {
code := ""
for i := 0; i < 6; i++ {
code += strconv.Itoa(rand.IntN(10))
}
userName := email[:strings.Index(email, "@")]
name, err := stores.NewUserStore(relationalDB).GetNameFromEmail(email)
if err != nil {
return err
}
if name != "" {
userName = name
}
if err := mailer.SendCode(displayNameApp, userName, email, code); err != nil {
return err
}
authenticationRequest := AuthenticationRequest{
appName: displayNameApp,
userName: userName,
email: email,
code: code,
}
authRequests.SetDefault(email, authenticationRequest)
return nil
}
func authorize(email, code string) (*models.Credential, error) {
c, ok := authRequests.Get(email)
if !ok {
return nil, nil
}
authenticationRequest := c.(AuthenticationRequest)
if authenticationRequest.code != code {
return nil, nil
}
account, err := stores.NewCredentialStore(relationalDB).Create(authenticationRequest.appName, authenticationRequest.userName, authenticationRequest.email)
if err != nil {
return nil, err
}
sessions.SetDefault(account.Token, account)
return account, nil
}
func getCredential(token string) *models.Credential {
if credential, ok := sessions.Get(token); ok {
return credential.(*models.Credential)
}
if _, err := uuid.Parse(token); err != nil {
return nil
}
credential, err := stores.NewCredentialStore(relationalDB).Get(token)
if err != nil {
log.Println("ERROR getting credential from store:", err)
}
if credential == nil {
return nil
}
sessions.SetDefault(token, credential)
return credential
}
func flushSession(userID string) {
selectedKey := ""
for key, item := range sessions.Items() {
if item.Object.(*models.Credential).UserID == userID {
selectedKey = key
break
}
}
if selectedKey != "" {
sessions.Delete(selectedKey)
}
}