This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
mobile_app.go
318 lines (266 loc) · 8.1 KB
/
mobile_app.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright 2020 the Exposure Notifications Verification Server authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"fmt"
"strings"
"time"
"github.com/google/exposure-notifications-verification-server/internal/project"
"github.com/google/exposure-notifications-verification-server/pkg/pagination"
"github.com/jinzhu/gorm"
)
type OSType int
// Display prints the name of the OSType. Note this CANNOT be named String()
// because, if it is, Go's text/template package will automatically call
// String() and cause you to lose hours upon hours of your life debuggin when
// forms are suddenly broken.
func (o OSType) Display() string {
switch o {
case OSTypeUnknown:
return "Unknown"
case OSTypeIOS:
return "iOS"
case OSTypeAndroid:
return "Android"
default:
return "Unknown"
}
}
func (o OSType) Len() int {
return 3
}
func (o OSType) IsAndroid() bool {
return o == OSTypeAndroid
}
func (o OSType) IsIOS() bool {
return o == OSTypeIOS
}
const (
OSTypeUnknown OSType = iota
OSTypeIOS
OSTypeAndroid
)
var _ Auditable = (*MobileApp)(nil)
type MobileApp struct {
gorm.Model
Errorable
// Name is the name of the app.
Name string `gorm:"column:name; type:citext;"`
// RealmID is the id of the mobile app.
RealmID uint `gorm:"column:realm_id;"`
Realm *Realm
// URL is the link to the app in it's appstore.
URL string `gorm:"-"`
URLPtr *string `gorm:"column:url; type:text"`
// DisableRedirect disables URL redirection in the redirector service for this
// app.
DisableRedirect bool `gorm:"column:disable_redirect; type:bool; default:false; not null"`
// OS is the type of the application we're using (eg, iOS, Android).
OS OSType `gorm:"column:os; type:int;"`
// Headless indicates that this an and android EN Express headless app.
// This is only settable through the app sync service.
Headless bool `gorm:"column:headless; type:bool; default:false; not null"`
// AppID is a unique string representing the app.
//
// For iOS this should include the team ID or app ID prefix followed by
// the bundle ID. eg. ABCD1234.com.google.test.application
AppID string `gorm:"column:app_id; type:varchar(512);"`
// SHA is a unique hash of the app.
// It is only present for Android devices, and should be of the form:
// AA:BB:CC:DD...
SHA string `gorm:"column:sha; type:text;"`
}
func (a *MobileApp) BeforeSave(tx *gorm.DB) error {
a.Name = project.TrimSpace(a.Name)
if a.Name == "" {
a.AddError("name", "cannot be blank")
}
if a.RealmID == 0 && a.Realm == nil {
a.AddError("realm_id", "is required")
}
a.AppID = project.TrimSpace(a.AppID)
if a.AppID == "" {
a.AddError("app_id", "cannot be blank")
}
a.URL = project.TrimSpace(a.URL)
a.URLPtr = stringPtr(a.URL)
// Ensure OS is valid
if a.OS < OSTypeIOS || a.OS > OSTypeAndroid {
a.AddError("os", "is invalid")
}
// SHA is required for Android
a.SHA = project.TrimSpace(a.SHA)
if a.OS == OSTypeAndroid {
if a.SHA == "" {
a.AddError("sha", "cannot be blank for Android apps")
}
}
// Process and clean SHAs
var shas []string
for _, line := range strings.Split(a.SHA, "\n") {
for _, entry := range strings.Split(line, ",") {
entry = strings.ToUpper(project.TrimSpace(entry))
if entry == "" {
continue
}
if got, want := len(entry), 95; got != want {
a.AddError("sha", fmt.Sprintf("must be %d characters (got %d)", want, got))
continue
}
if entry != "" {
shas = append(shas, entry)
}
}
}
a.SHA = strings.Join(shas, "\n")
return a.ErrorOrNil()
}
func (a *MobileApp) AfterFind(tx *gorm.DB) error {
a.URL = stringValue(a.URLPtr)
return nil
}
func (db *Database) FindMobileApp(id interface{}) (*MobileApp, error) {
var app MobileApp
if err := db.db.
Where("id = ?", id).
First(&app).
Error; err != nil {
return nil, err
}
return &app, nil
}
// ListActiveAppsWithRealm finds all active mobile apps with their associated
// realm preloaded. Refine the search with scopes.
func (db *Database) ListActiveAppsWithRealm(p *pagination.PageParams, scopes ...Scope) ([]*MobileApp, *pagination.Paginator, error) {
var apps []*MobileApp
query := db.db.
Model(&MobileApp{}).
Joins("JOIN realms ON realms.id = mobile_apps.realm_id").
Scopes(scopes...).
Order("realms.id ASC, LOWER(mobile_apps.name) ASC")
if p == nil {
p = new(pagination.PageParams)
}
paginator, err := Paginate(query, &apps, p.Page, p.Limit)
if err != nil {
if IsNotFound(err) {
return apps, nil, nil
}
return nil, nil, err
}
return apps, paginator, nil
}
// ListActiveApps finds mobile apps by their realm.
func (db *Database) ListActiveApps(realmID uint, scopes ...Scope) ([]*MobileApp, error) {
// Find the apps.
var apps []*MobileApp
if err := db.db.
Model(&MobileApp{}).
Scopes(scopes...).
Where("realm_id = ?", realmID).
Find(&apps).
Error; err != nil {
if IsNotFound(err) {
return apps, nil
}
return nil, err
}
return apps, nil
}
// SaveMobileApp saves the mobile app.
func (db *Database) SaveMobileApp(a *MobileApp, actor Auditable) error {
if a == nil {
return fmt.Errorf("provided mobile app is nil")
}
if actor == nil {
return ErrMissingActor
}
return db.db.Transaction(func(tx *gorm.DB) error {
var audits []*AuditEntry
var existing MobileApp
if err := tx.
Unscoped().
Model(&MobileApp{}).
Where("id = ?", a.ID).
First(&existing).
Error; err != nil && !IsNotFound(err) {
return fmt.Errorf("failed to get existing mobile app: %w", err)
}
// Save the app
if err := tx.Unscoped().Save(a).Error; err != nil {
if IsUniqueViolation(err, "uix_name_realm_id_os") {
a.AddError("name", "must be unique")
return ErrValidationFailed
}
return err
}
// Brand new app?
if existing.ID == 0 {
audit := BuildAuditEntry(actor, "created mobile app", a, a.RealmID)
audits = append(audits, audit)
} else {
if existing.Name != a.Name {
audit := BuildAuditEntry(actor, "updated mobile app name", a, a.RealmID)
audit.Diff = stringDiff(existing.Name, a.Name)
audits = append(audits, audit)
}
if existing.OS != a.OS {
audit := BuildAuditEntry(actor, "updated mobile app os", a, a.RealmID)
audit.Diff = stringDiff(existing.OS.Display(), a.OS.Display())
audits = append(audits, audit)
}
if existing.AppID != a.AppID {
audit := BuildAuditEntry(actor, "updated mobile app appID", a, a.RealmID)
audit.Diff = stringDiff(existing.AppID, a.AppID)
audits = append(audits, audit)
}
if existing.SHA != a.SHA {
audit := BuildAuditEntry(actor, "updated mobile app sha", a, a.RealmID)
audit.Diff = stringDiff(existing.SHA, a.SHA)
audits = append(audits, audit)
}
if existing.DeletedAt != a.DeletedAt {
audit := BuildAuditEntry(actor, "updated mobile app enabled", a, a.RealmID)
audit.Diff = boolDiff(existing.DeletedAt == nil, a.DeletedAt == nil)
audits = append(audits, audit)
}
}
// Save all audits
for _, audit := range audits {
if err := tx.Save(audit).Error; err != nil {
return fmt.Errorf("failed to save audits: %w", err)
}
}
return nil
})
}
func (a *MobileApp) AuditID() string {
return fmt.Sprintf("mobile_apps:%d", a.ID)
}
func (a *MobileApp) AuditDisplay() string {
return fmt.Sprintf("%s (%s)", a.Name, a.OS.Display())
}
// PurgeMobileApps will delete mobile apps that have been deleted for more than
// the specified time.
func (db *Database) PurgeMobileApps(maxAge time.Duration) (int64, error) {
if maxAge > 0 {
maxAge = -1 * maxAge
}
deleteBefore := time.Now().UTC().Add(maxAge)
result := db.db.
Unscoped().
Where("deleted_at IS NOT NULL AND deleted_at < ?", deleteBefore).
Delete(&MobileApp{})
return result.RowsAffected, result.Error
}