/
model.go
366 lines (307 loc) · 9.99 KB
/
model.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/* ****************************************************************************
* Copyright 2020 51 Degrees Mobile Experts Limited (51degrees.com)
*
* 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 publisher
import (
"bytes"
"encoding/base64"
"fmt"
"html/template"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
"github.com/SWAN-community/owid-go"
"github.com/SWAN-community/swan-demo-go/common"
"github.com/SWAN-community/swan-demo-go/swanopenrtb"
"github.com/SWAN-community/swan-go"
)
// Model used with HTML templates.
type Model struct {
common.PageModel
swanData []*swan.Pair // The SWAN data for display
}
// Version is a code for cache busting.
func (m *Model) Version() string {
return time.Now().UTC().Format("01-02-2006 15")
}
// CMPURL returns the URL for the CMP dialog.
func (m Model) CMPURL() string {
return getCMPURL(m.Domain, m.Request, m.swanData)
}
// SWANURL returns the URL for the SWAN operation. Used when the SWAN
// transaction is completed in a pop up window, iFrame or is a JavaScript
// include.
func (m Model) SWANURL() string {
u, _ := getSWANURL(m.Domain, m.Request, m.swanData)
return u
}
// HomeNode returns the internet domain name of the home node.
func (m Model) HomeNode() string {
h, _ := getHomeNode(m.Domain, m.Request)
return h
}
// IsNew returns true if the SWID is newly created, otherwise false.
func (m Model) IsNew() bool {
if m.swid() != nil {
o, _ := m.swid().AsOWID()
if o != nil {
return o.Age() <= 1
}
}
return false
}
// Personalized returns a boolean to indicate if personalized marketing is enabled.
func (m Model) Personalized() bool { return m.PrefAsString() == "on" }
// SWIDAsString Secure Web IDentifier
func (m Model) SWIDAsString() string { return common.AsStringFromUUID(m.swid()) }
// SIDAsString Signed in IDentifier
func (m Model) SIDAsString() string { return common.AsPrintable(m.sid()) }
// PrefAsString true if personalized marketing allowed, otherwise false
func (m Model) PrefAsString() string { return common.AsString(m.pref()) }
// SWIDDomain returns the domain that created the SWID OWID
func (m Model) SWIDDomain() string { return common.OWIDDomain(m.swid()) }
// SIDDomain returns the domain that created the SID OWID
func (m Model) SIDDomain() string { return common.OWIDDomain(m.sid()) }
// PrefDomain returns the domain that created the Allow OWID
func (m Model) PrefDomain() string { return common.OWIDDomain(m.pref()) }
// SWIDDate returns the date SWID OWID was created
func (m Model) SWIDDate() string { return common.OWIDDate(m.swid()) }
// SIDDate returns the date SID OWID was created
func (m Model) SIDDate() string { return common.OWIDDate(m.sid()) }
// PrefDate returns the date Allow OWID was created
func (m Model) PrefDate() string { return common.OWIDDate(m.pref()) }
// Stopped returns a list of the domains that have been stopped for advertising.
func (m Model) Stopped() []string {
return strings.Split(common.AsString(m.stop()), "\r\n")
}
func (m Model) NewSWANIDAsString() string {
var err error
r, err := m.newSWANIDOWID()
if err != nil {
return ""
}
return r.AsString()
}
// DomainsByCategory returns all the domains that match the category.
func (m Model) DomainsByCategory(category string) []*common.Domain {
var domains []*common.Domain
for _, domain := range m.Domain.Config.Domains {
if domain.Category == category {
domains = append(domains, domain)
}
}
return domains
}
// NewAdvertHTML provides the HTML for the advert that will be displayed on the
// web page at the placement provided.
func (m Model) NewAdvertHTML(placement string) (template.HTML, error) {
// Check that the preference information has a value and is not empty.
if m.PrefAsString() == "" {
return template.HTML("<p>Preferences not set</p>"), nil
}
// Seed the random number generator to get a random advert in the demo.
rand.Seed(time.Now().UTC().UnixNano())
// Use the SWAN network to generate the swan.ID.
r, err := m.newSWANIDNode()
if err != nil {
return "", err
}
// Add the publishers signature and then process the supply chain.
_, err = swanopenrtb.SendToSuppliers(m.Domain, r)
if err != nil {
return template.HTML("<p>" + err.Error() + "</p>"), nil
}
// Get the OWID tree as a base 64 string.
e, err := r.AsJSON()
if err != nil {
return template.HTML("<p>" + err.Error() + "</p>"), nil
}
// Get the winning bid node.
w, err := swan.WinningNode(r)
if err != nil {
return template.HTML("<p>" + err.Error() + "</p>"), nil
}
// Get the winning bid.
b, err := swan.WinningBid(r)
if err != nil {
return template.HTML("<p>" + err.Error() + "</p>"), nil
}
// Get the return URL.
t, err := common.GetReturnURL(m.Request)
if err != nil {
return template.HTML("<p>" + err.Error() + "</p>"), nil
}
// Get the URL for the info icon.
var i url.URL
i.Scheme = m.Config().Scheme
i.Host = m.Domain.CMP
i.Path = "/info"
q := i.Query()
n := w
for n != nil {
q.Add("github.com/SWAN-community/owid-go", n.GetOWIDAsString())
n = n.GetParent()
}
q.Set("returnUrl", t.String())
// Set the access node so that the CMP knows which node to use to encrypt
// the results of a stop operation.
q.Set("accessNode", m.Domain.SWANAccessNode)
i.RawQuery = q.Encode()
// Return a FORM HTML element with a button for the advert. The OWID tree
// is a base 64 string added as a hidden field to the form.
var html bytes.Buffer
html.WriteString(fmt.Sprintf("<form method=\"POST\" action=\"//%s\">"+
"<div class=\"form-group\">"+
"<input type=\"hidden\" id=\"transaction\" name=\"transaction\" value=\"%s\">"+
"<button type=\"submit\" id=\"view\" name=\"view\" class=\"advert-button\">"+
"<img src=\"//%s\">"+
"</button>"+
"<a href=\"%s\" class=\"advert-stop\" title=\"Info about this advert\">"+
"<img src=\"%s\">"+
"</a>"+
"</div>"+
"</form>",
b.AdvertiserURL,
base64.StdEncoding.EncodeToString(e),
b.MediaURL,
i.String(),
"noun_Info_1582932.svg"))
return template.HTML(html.String()), nil
}
// SWID Secure Web IDentifier
func (m Model) swid() *swan.Pair { return m.findResult("swid") }
// SID Signed in IDentifier
func (m Model) sid() *swan.Pair { return m.findResult("sid") }
// Allow true if personalized marketing allowed, otherwise false
func (m Model) pref() *swan.Pair { return m.findResult("pref") }
// Stop the list of domains that should not have adverts displayed form.
func (m Model) stop() *swan.Pair { return m.findResult("stop") }
func (m Model) findResult(k string) *swan.Pair {
for _, n := range m.swanData {
if strings.EqualFold(k, n.Key) {
return n
}
}
return nil
}
// newSWANIDNode returns a new SWAN OWID Node from the form parameters of the
// request. If values are missing or are invalid then an error is returned.
func (m *Model) newSWANIDNode() (*owid.Node, error) {
o, err := m.newSWANIDOWID()
if err != nil {
return nil, err
}
b, err := o.AsByteArray()
if err != nil {
return nil, err
}
return &owid.Node{OWID: b}, nil
}
// newSWANIDOWID returns a new SWAN OWID from the form parameters of the
// request. If values are missing or are invalid then an error is returned.
func (m *Model) newSWANIDOWID() (*owid.OWID, error) {
of, err := m.newSWANID()
if err != nil {
return nil, err
}
b, err := of.AsByteArray()
if err != nil {
return nil, err
}
oc, err := m.Domain.GetOWIDCreator()
if err != nil {
return nil, err
}
o, err := oc.CreateOWIDandSign(b)
if err != nil {
return nil, err
}
return o, nil
}
// Returns a new unsigned swan.ID ready to be used the byte array payload in
// an OWID that the caller is generating a a Root Party for the commencement of
// an advertising request.
func (m *Model) newSWANID() (*swan.ID, error) {
// Create the new SWAN ID with random UUID.
o, err := swan.NewID()
if err != nil {
return nil, err
}
// Set the publisher domain from the request.
o.PubDomain = m.Request.Host
// Get the SWID as an OWID.
o.SWID, err = getOWID(m.Config(), m.Request, m.swid())
if err != nil {
return nil, err
}
// Get the Signed in Identifier (SID) as an OWID.
o.SID, err = getOWID(m.Config(), m.Request, m.sid())
if err != nil {
return nil, err
}
// Get the preferences as an OWID.
o.Preferences, err = getOWID(m.Config(), m.Request, m.pref())
if err != nil {
return nil, err
}
// Get the stopped adverts string.
o.Stopped = getStopped(m.Request, m.stop())
return o, nil
}
// Returns an array of stopped advert IDs. As the parameter is optional no error
// is returned.
func getStopped(r *http.Request, p *swan.Pair) []string {
var s []string
// Get stopped adverts from swan pair.
if p != nil {
s = append(s, strings.Split(p.Value, " ")...)
}
// Get stopped adverts from the form.
s = append(s, strings.Split(r.FormValue("stop"), " ")...)
return s
}
// Returns the value as a string associated with the form parameter k. If the
// value is missing then an error is returned.
func getValue(r *http.Request, k string) (string, error) {
v := r.FormValue(k)
if v == "" {
return "", fmt.Errorf("missing '%s' parameter", k)
}
return v, nil
}
// Returns a verified OWID associated with the form parameter k. Returns and
// error if the value is missing or is not a verified OWID.
func getOWID(
c *common.Configuration,
r *http.Request,
p *swan.Pair) (*owid.OWID, error) {
if p != nil {
o, err := owid.FromBase64(p.Value)
if err != nil {
return nil, err
}
e, err := o.Verify(c.Scheme)
if err != nil {
return nil, err
}
if e == false {
return nil, fmt.Errorf("'%s' not a valid OWID", p.Key)
}
return o, nil
}
return nil, nil
}