audience-kit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/docs/sign-in.md ADDED
@@ -0,0 +1,197 @@
1
+ # Signing people in with Ruby
2
+
3
+ A website signs a person in with a provider (Facebook, Google or Apple), hands what the provider returned to
4
+ AudienceKit, and keeps the AudienceKit session it gets back. From then on every call the SDK makes acts as that person,
5
+ under the audience's rules: they see what members see, and their RSVPs, chat messages and cover passes are their own.
6
+
7
+ A site that only shows what the audience lists doesn't sign anyone in; see [Building a website](websites.md) for API
8
+ keys and service tokens.
9
+
10
+ ## Set up the session
11
+
12
+ Make one `Audience::Kit::Session` per request, with a `SessionCredentialStore` so the credential lives in the
13
+ framework's session rather than anywhere the browser can read it. In Rails:
14
+
15
+ ```ruby
16
+ class ApplicationController < ActionController::Base
17
+ private
18
+
19
+ def audience_kit
20
+ @audience_kit ||= Audience::Kit::Session.new(
21
+ configuration: Audience::Kit::Configuration.new(
22
+ host: "hotmess.social", # the host that names your audience
23
+ facebook_app_id: "123456789" # the Facebook app your login dialog uses
24
+ ),
25
+ store: Audience::Kit::SessionCredentialStore.new(session)
26
+ )
27
+ end
28
+
29
+ def audience_kit_device
30
+ session[:audiencekit_device] ||= SecureRandom.hex(16)
31
+ Audience::Kit::DeviceDescription.new(identifier: session[:audiencekit_device])
32
+ end
33
+ end
34
+ ```
35
+
36
+ Rails' default cookie store encrypts the session, so the token is never readable in the browser. With another store,
37
+ use a server-side one (Active Record, Redis) or an encrypted cookie. In Sinatra or plain Rack, pass `session` or
38
+ `env["rack.session"]` the same way, with `enable :sessions` and a strong `session_secret`.
39
+
40
+ `audience_kit.signed_in?` says whether there is a session; `audience_kit.me` reads the person's profile. Every sign-in
41
+ takes a `DeviceDescription`: a stable identifier for the browser or server and the platform, `web` by default.
42
+
43
+ When a sign-in succeeds, start a fresh session so an ID planted before sign-in can't ride along. In Rails, keep the
44
+ credential across `reset_session`:
45
+
46
+ ```ruby
47
+ def start_session!(credential)
48
+ device = session[:audiencekit_device]
49
+ reset_session
50
+ session[:audiencekit_device] = device
51
+ Audience::Kit::SessionCredentialStore.new(session).save(credential)
52
+ end
53
+ ```
54
+
55
+ ## Facebook
56
+
57
+ Open Facebook's login dialog (for Facebook Login for Business, with the configuration ID the audience's branding gives
58
+ as `facebook_login_config_id`), and when Facebook redirects back with a `code`, trade it. The redirect URI must be
59
+ exactly the one the dialog was opened with:
60
+
61
+ ```ruby
62
+ class FacebookSessionsController < ApplicationController
63
+ CALLBACK = "https://example.com/auth/facebook"
64
+
65
+ # GET /auth/facebook/start
66
+ def new
67
+ session[:oauth_state] = SecureRandom.hex(16)
68
+ branding = audience_kit.branding # public: the audience, its theme and its login configuration
69
+ query = { client_id: "123456789", redirect_uri: CALLBACK, state: session[:oauth_state],
70
+ config_id: branding["facebook_login_config_id"], response_type: "code" }.compact
71
+ redirect_to "https://www.facebook.com/v21.0/dialog/oauth?#{query.to_query}", allow_other_host: true
72
+ end
73
+
74
+ # GET /auth/facebook
75
+ def create
76
+ expected = session.delete(:oauth_state).to_s
77
+ return head(:bad_request) unless ActiveSupport::SecurityUtils.secure_compare(expected, params[:state].to_s)
78
+
79
+ credential = audience_kit.sign_in_with_facebook_code(params[:code], redirect_uri: CALLBACK,
80
+ device: audience_kit_device)
81
+ start_session!(credential)
82
+ redirect_to root_path
83
+ rescue Audience::Kit::Error => e
84
+ redirect_to sign_in_path, alert: e.message
85
+ end
86
+ end
87
+ ```
88
+
89
+ The API trades the code with the app secret, so the secret never reaches your server. When the dialog belongs to
90
+ another Facebook app than the configured one, pass `facebook_app_id:`. A Facebook user access token the browser got
91
+ from the JavaScript SDK works too: `sign_in_with_facebook_token(access_token, device:)`.
92
+
93
+ ## Google
94
+
95
+ Google Identity Services posts an ID token (its `credential`) to your login endpoint. Check its CSRF cookie, then
96
+ trade it:
97
+
98
+ ```ruby
99
+ def google
100
+ token = params[:g_csrf_token].to_s
101
+ return head(:bad_request) if token.empty? || !ActiveSupport::SecurityUtils.secure_compare(token, cookies[:g_csrf_token].to_s)
102
+
103
+ start_session!(audience_kit.sign_in_with_google(params[:credential], device: audience_kit_device))
104
+ redirect_to root_path
105
+ end
106
+ ```
107
+
108
+ The ID token carries only the account's primary email. To let the API match an existing account by the Google
109
+ account's other verified emails, also ask for the `https://www.googleapis.com/auth/user.emails.read` scope and pass
110
+ the access token: `sign_in_with_google(id_token, device:, access_token:)`. A person already signed in can add Google to
111
+ their account with `connect_google(id_token, device:)`, and Facebook with `connect_facebook(code, redirect_uri:,
112
+ device:)`.
113
+
114
+ ## Sign in with Apple
115
+
116
+ Sign in with Apple JS returns an identity token, an authorization code and, the first time only, the person's name.
117
+ Pass them with the redirect URI and the nonce you gave Apple:
118
+
119
+ ```ruby
120
+ apple = JSON.parse(params[:apple_response])
121
+ credential = audience_kit.sign_in_with_apple(
122
+ apple.dig("authorization", "id_token"),
123
+ device: audience_kit_device,
124
+ authorization_code: apple.dig("authorization", "code"),
125
+ redirect_uri: "https://example.com/auth/apple",
126
+ nonce: session.delete(:apple_nonce),
127
+ first_name: apple.dig("user", "name", "firstName"),
128
+ last_name: apple.dig("user", "name", "lastName")
129
+ )
130
+ ```
131
+
132
+ ## App Review codes
133
+
134
+ While an audience is in App Review, its console issues a code a reviewer types instead of signing in with a provider:
135
+
136
+ ```ruby
137
+ audience_kit.sign_in_with_review_code(params[:code], device: audience_kit_device)
138
+ ```
139
+
140
+ A wrong or expired code raises `Audience::Kit::Error` with `SIGN_IN_REJECTED`.
141
+
142
+ ## When sessions end
143
+
144
+ A session ends when the person signs out, when an admin ends it, or when it expires. When the API refuses it, the call
145
+ raises `Audience::Kit::Error` with `UNAUTHENTICATED` and the SDK forgets the credential, so `signed_in?` turns false:
146
+ send the person back to sign in. In Rails, one `rescue_from` covers every controller:
147
+
148
+ ```ruby
149
+ class ApplicationController < ActionController::Base
150
+ rescue_from Audience::Kit::Error do |error|
151
+ raise error unless error.unauthenticated? || error.code == Audience::Kit::Error::NOT_SIGNED_IN
152
+
153
+ redirect_to sign_in_path, alert: error.message
154
+ end
155
+ end
156
+ ```
157
+
158
+ `refresh_session` re-issues the token for the same session (after the API rotates its signing key, say). `sign_out`
159
+ forgets the credential and revokes the token everywhere:
160
+
161
+ ```ruby
162
+ def destroy
163
+ audience_kit.sign_out
164
+ reset_session
165
+ redirect_to root_path
166
+ end
167
+ ```
168
+
169
+ ## Deleting an account
170
+
171
+ App stores and privacy law expect people to be able to delete their account from wherever they signed up. After the
172
+ person confirms:
173
+
174
+ ```ruby
175
+ if audience_kit.delete_account
176
+ reset_session
177
+ redirect_to root_path, notice: "Your account is deleted."
178
+ end
179
+ ```
180
+
181
+ It erases their data in the audience and signs them out everywhere, and can't be undone.
182
+
183
+ ## Keeping the credential somewhere else
184
+
185
+ `SessionCredentialStore` keeps the credential in any Hash-like session under `audiencekit.credential` (pass `key:` for
186
+ another). For a database row or a secrets manager, write an object with three methods:
187
+
188
+ ```ruby
189
+ class AccountCredentialStore
190
+ def initialize(account) = @account = account
191
+ def load = @account.audiencekit_credential && Audience::Kit::Credential.from_h(@account.audiencekit_credential)
192
+ def save(credential) = @account.update!(audiencekit_credential: credential.to_h)
193
+ def delete = @account.update!(audiencekit_credential: nil)
194
+ end
195
+ ```
196
+
197
+ Encrypt the column (Rails' `encrypts :audiencekit_credential`): the token is as good as a password. Never log it.
data/docs/websites.md ADDED
@@ -0,0 +1,167 @@
1
+ # Building a website with Ruby
2
+
3
+ A venue's site, a city guide, a Discord bot or a newsletter job can be built from what an audience lists, with the
4
+ same calls the apps make. This page covers reading as the audience (no one signed in), the public listings, Soapbox
5
+ news, and what a signed-in visitor can do on a site.
6
+
7
+ ## Read as the audience: API keys and service tokens
8
+
9
+ An admin makes tokens in the audience's console. Keep them in the environment or Rails credentials, never in the
10
+ repository:
11
+
12
+ ```sh
13
+ AUDIENCEKIT_TOKEN=...
14
+ AUDIENCEKIT_HOST=hotmess.social
15
+ ```
16
+
17
+ ```ruby
18
+ session = Audience::Kit::Session.from_env
19
+ ```
20
+
21
+ `from_env` also reads `AUDIENCEKIT_BASE_URL`, `AUDIENCEKIT_AUDIENCE_ID` and `AUDIENCEKIT_ENVIRONMENT` (`staging` for a
22
+ staging build), and takes `http:`, a Faraday connection of your own (for timeouts, instrumentation or a proxy). With a
23
+ token from somewhere else:
24
+
25
+ ```ruby
26
+ session = Audience::Kit::Session.new(configuration: Audience::Kit::Configuration.new(host: "hotmess.social"))
27
+ session.use_bearer_token(Rails.application.credentials.audiencekit_api_key)
28
+ ```
29
+
30
+ Which token to use:
31
+
32
+ - **An application API key** reads everything below the public listings: `community`, `events`, `venues`, news and
33
+ the rest. Anything in `AUDIENCEKIT_TOKEN` that doesn't start `akst_` is sent as is, or pass it to
34
+ `use_bearer_token`.
35
+ - **A service token** (`akst_<prefix>_<secret>`) with the `public:read` scope reads the public listings. The session
36
+ trades it at `POST /v1/token/service` for an hour-long session, trades it again a minute before that runs out, and
37
+ once more if the API refuses the session (after a key rotation, say). A token an admin revoked raises
38
+ `Audience::Kit::Error` with `UNAUTHENTICATED`. The GraphQL reads refuse a service session for now, so a site that
39
+ renders from them uses an application API key.
40
+
41
+ Keep both on the server.
42
+
43
+ ## The public listings
44
+
45
+ What the audience shows anyone, as its own websites show it: up to 500 venues, then events, then posts, a page at a
46
+ time. Plain text, ready for a template:
47
+
48
+ ```ruby
49
+ listings = session.public_listings.select(&:public?) # "community" listings show in full only to members
50
+
51
+ listings.group_by(&:kind).each do |kind, items|
52
+ puts "## #{kind.capitalize}s"
53
+ items.each do |listing|
54
+ case listing.kind
55
+ when "venue" then puts "#{listing.title}, #{listing.address}"
56
+ when "event" then puts "#{listing.start_at&.strftime("%b %-d")}: #{listing.title} at #{listing.venue_name}"
57
+ when "post" then puts "#{listing.title}: #{listing.description}"
58
+ end
59
+ end
60
+ end
61
+ ```
62
+
63
+ `public_listings_page(page)` reads one page (with `next_page` for the next), `public_listing(:venue, id)` one listing
64
+ (nil when it's gone), and `public_tonight(venue_id)` what a screen facing the room shows: tonight's event, who's on and
65
+ what's next. [`examples/listings_page.rb`](../examples/listings_page.rb) writes a static page of listings.
66
+
67
+ ## The community in one call
68
+
69
+ For a site that renders from the richer GraphQL models (venues with their locales, points and tags; events with their
70
+ venues, hosts and tickets), `community` reads the audience, its locales, venues, people, upcoming events and event
71
+ series together. A part whose module the audience doesn't have comes back empty.
72
+
73
+ ```ruby
74
+ community = session.community
75
+
76
+ community.venues.each do |venue|
77
+ point = venue.coordinate # Audience::Kit::Coordinate, for a map
78
+ tags = venue.tags.map(&:name)
79
+ end
80
+
81
+ accent = community.audience&.color("accent") # Audience::Kit::Color from the audience's theme
82
+ accent&.to_css # "rgba(255, 51, 102, 1)"
83
+ ```
84
+
85
+ The individual calls are there too: `venues`, `people`, `locales`, `events(window:, locale_id:, venue_id:)`,
86
+ `event_series`, `event(id)`, `venue_detail(id)` and `closest_locale(coordinate)`.
87
+ [`examples/community_export.rb`](../examples/community_export.rb) writes the whole community as JSON for a static site
88
+ generator (Jekyll's `_data/`, Bridgetown, Middleman).
89
+
90
+ Event times are `Time` in UTC; show them in the locale's zone with `event.start_at.in_time_zone("America/Phoenix")`
91
+ in Rails, or `getlocal` elsewhere. `event.ended?` says whether it is over, and `event.effective_hosts` who runs the
92
+ night: its hosts or, when nobody else is linked to it, its KJ, DJ or VJ.
93
+
94
+ ## News
95
+
96
+ Audiences with Soapbox carry local news and op-eds from publications they trust:
97
+
98
+ ```ruby
99
+ # The latest, pinned first, for a locale (or one publication).
100
+ session.articles(locale_id: locale.id, first: 10).each do |article|
101
+ puts "#{article.title} (#{article.publication&.name})"
102
+ end
103
+
104
+ # "Show more": page through with the cursor.
105
+ page = session.articles_page(locale_id: locale.id, after: params[:after])
106
+ link_to "Show more", news_path(after: page.end_cursor) if page.next_page?
107
+
108
+ # One article, with its Markdown body and what it is about.
109
+ article = session.article(id)
110
+ ```
111
+
112
+ Also `national_articles`, `articles_about(:venue | :event | :person | :locale, id)` for "In the news" on a listing's
113
+ page, `publications`, `local_publications(locale_id)` and `publication(id)`. Show `article.disclosure` when there is
114
+ one, and link `article.canonical_url` when `article.teaser?`: the rest of the article is on the publication's site. A
115
+ signed-in reader can send a publication that accepts them (`publication.accepts_op_eds?`) an op-ed with
116
+ `submit_op_ed`, and follow it with `my_op_eds`. [`examples/news_digest.rb`](../examples/news_digest.rb) writes a
117
+ Markdown digest for a newsletter.
118
+
119
+ Every Soapbox call returns nothing, rather than failing, for an audience without Soapbox.
120
+
121
+ ## Things a signed-in visitor can do
122
+
123
+ Once someone has [signed in](sign-in.md), a site can do what the apps do
124
+ ([`examples/member_actions.rb`](../examples/member_actions.rb) walks through them):
125
+
126
+ - RSVP: `rsvp_event(event_id, "ATTENDING")`, `cancel_rsvp(event_id)` and `event_rsvp(event_id)` for who's going.
127
+ - Calendar: `create_calendar_feed` returns links (`feed.url`, `webcal_url`, `google_url`) that add every event they're
128
+ going to to their own calendar, and `follow_venue_in_calendar(venue_id)` adds every event at a venue.
129
+ - Cover: `venue_cover(venue_id)` says tonight's charge; `buy_cover(venue_id)` (with `amount_cents:` on a sliding
130
+ scale) or `buy_coat_check(venue_id, quantity:)` starts paying with the venue's provider. For Stripe, confirm
131
+ `payment_intent_client_secret` with Stripe.js and call `confirm_cover`; for Square, tokenize with the Web Payments
132
+ SDK and call `pay_cover`. `admission.pass_code` is the code to show at the door as a QR code; it changes every 30
133
+ seconds, so render it in the page and refresh it, rather than caching it.
134
+ - Chat: `send_chat_message(text, venue_id:)`, `remove_chat_message`, and `report_content`, `block_user` and
135
+ `unblock_user` so people can report what they see. Offer `Audience::Kit::ReportTarget::REASONS` as the reasons.
136
+ - Tribes and notifications: `tribes`, `identify_with_tribe`, `leave_tribe` and `register_device`.
137
+
138
+ ## Caching
139
+
140
+ Listings change a few times a day, so cache what the page renders, not the session. Cache the JSON and rebuild models
141
+ when reading:
142
+
143
+ ```ruby
144
+ events = Rails.cache.fetch("audiencekit/events", expires_in: 5.minutes) do
145
+ session.events.map(&:to_h)
146
+ end.map { |json| Audience::Kit::Event.new(json) }
147
+ ```
148
+
149
+ Don't cache anything read as a signed-in person in a cache other people's pages read from.
150
+
151
+ ## Your own queries
152
+
153
+ The calls above cover what the apps show. For anything else, run a document of your own and build models from the
154
+ result:
155
+
156
+ ```ruby
157
+ data = session.graphql(<<~GRAPHQL, { "first" => 5 })
158
+ query Featured($first: Int) {
159
+ events { list(first: $first) { nodes { #{Audience::Kit::Queries.event_fields(Audience::Kit::SchemaShape.everything)} } } }
160
+ }
161
+ GRAPHQL
162
+ Audience::Kit::Event.list(data.dig("events", "list"))
163
+ ```
164
+
165
+ The schema is on the [GraphQL reference](https://developer.audiencekit.com/reference/graphql/). A field a module adds
166
+ fails the whole operation in an audience without that module; `shaped_graphql` builds the document from what the
167
+ audience has, as the SDK's own calls do.
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Audience
4
+ module Kit
5
+ # A color from the API's hex strings (a theme token, a tag's chip color), with components from 0 to 1, for pages
6
+ # that draw with the audience's branding.
7
+ Color = Data.define(:red, :green, :blue, :alpha) do
8
+ def initialize(red:, green:, blue:, alpha: 1.0)
9
+ super
10
+ end
11
+
12
+ # Parses +#rgb+, +#rrggbb+ or +#rrggbbaa+ (the +#+ is optional); nil when it is none of those.
13
+ # @param hex [String]
14
+ # @return [Color, nil]
15
+ def self.from_hex(hex)
16
+ digits = hex.to_s.strip.delete_prefix("#")
17
+ digits = digits.chars.map { |digit| digit * 2 }.join if digits.length == 3
18
+ return nil unless digits.match?(/\A(\h{6}|\h{8})\z/)
19
+
20
+ digits += "ff" if digits.length == 6
21
+ red, green, blue, alpha = digits.scan(/../).map { |pair| pair.to_i(16) / 255.0 }
22
+ new(red: red, green: green, blue: blue, alpha: alpha)
23
+ end
24
+
25
+ # A branding theme token's color, preferring its dark override in dark mode. +theme+ is branding's or the
26
+ # audience's +theme+: +light+ and +dark+ either as +{ token => hex }+ maps (REST branding) or as lists of
27
+ # +{ name, value }+ (GraphQL).
28
+ # @param theme [Hash, nil]
29
+ # @param token [String] e.g. +"accent"+
30
+ # @param dark [Boolean]
31
+ # @return [Color, nil]
32
+ def self.from_theme(theme, token, dark: false)
33
+ return nil unless theme.is_a?(Hash)
34
+
35
+ hex = (token_value(theme["dark"], token) if dark) || token_value(theme["light"], token)
36
+ hex && from_hex(hex)
37
+ end
38
+
39
+ def self.token_value(tokens, token)
40
+ case tokens
41
+ when Hash then tokens[token].is_a?(String) ? tokens[token] : nil
42
+ when Array
43
+ entry = tokens.find { |e| e.is_a?(Hash) && e["name"] == token && e["value"].is_a?(String) }
44
+ entry && entry["value"]
45
+ end
46
+ end
47
+ private_class_method :token_value
48
+
49
+ # The color as CSS +rgba(r, g, b, a)+.
50
+ # @return [String]
51
+ def to_css
52
+ alpha_text = format("%.3f", alpha.clamp(0.0, 1.0)).sub(/0+\z/, "").sub(/\.\z/, "")
53
+ "rgba(#{channel(red)}, #{channel(green)}, #{channel(blue)}, #{alpha_text})"
54
+ end
55
+
56
+ # The color as +#rrggbb+, or +#rrggbbaa+ when it isn't opaque.
57
+ # @return [String]
58
+ def to_hex
59
+ hex = format("#%<r>02x%<g>02x%<b>02x", r: channel(red), g: channel(green), b: channel(blue))
60
+ alpha >= 1.0 ? hex : hex + format("%02x", channel(alpha))
61
+ end
62
+
63
+ private
64
+
65
+ def channel(value) = (value.clamp(0.0, 1.0) * 255).round
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Audience
4
+ module Kit
5
+ # Where a {Session} talks to and which audience it speaks for.
6
+ #
7
+ # @!attribute [r] base_url
8
+ # @return [String] the API's base URL, e.g. +https://api.audiencekit.com+ or +http://localhost:3000+
9
+ # @!attribute [r] host
10
+ # @return [String, nil] a host that names the audience, e.g. +hotmess.social+. Sent with sign-in so the session
11
+ # is bound to the audience, and used to look up branding (and the audience ID when none is set).
12
+ # @!attribute [r] audience_id
13
+ # @return [String, nil] the audience's ID (a UUID). When nil the session works it out from the stored
14
+ # credential, or from branding for {#host}.
15
+ # @!attribute [r] facebook_app_id
16
+ # @return [String, nil] the Facebook app the site signs people in with
17
+ # @!attribute [r] environment
18
+ # @return [String] {Environment::PRODUCTION} or {Environment::STAGING}
19
+ # @!attribute [r] trusted_credential_origins
20
+ # @return [Array<String>] other API instances whose sign-ins {#base_url} also takes: a credential one of them
21
+ # issued is sent to {#base_url} rather than its own instance
22
+ Configuration = Data.define(:base_url, :host, :audience_id, :facebook_app_id, :environment,
23
+ :trusted_credential_origins) do
24
+ def initialize(base_url: PRODUCTION_BASE_URL, host: nil, audience_id: nil, facebook_app_id: nil,
25
+ environment: Environment::PRODUCTION, trusted_credential_origins: [])
26
+ super
27
+ end
28
+
29
+ # The API instance to send +credential+ to: the one that issued it (its endpoint's origin), unless {#base_url}
30
+ # takes that instance's sign-ins ({#trusted_credential_origins}); {#base_url} with no credential.
31
+ # @param credential [Credential, nil]
32
+ # @return [String]
33
+ def api_base(credential)
34
+ origin = credential&.origin
35
+ return base_url if origin.nil?
36
+ return base_url if trusted_credential_origins.any? { |trusted| Configuration.same_origin?(trusted, origin) }
37
+
38
+ origin
39
+ end
40
+
41
+ # Whether two URLs name the same scheme, host and port.
42
+ # @return [Boolean]
43
+ def self.same_origin?(lhs, rhs)
44
+ a = URI.parse(lhs)
45
+ b = URI.parse(rhs)
46
+ [a.scheme, a.host, a.port].map { |part| part.to_s.downcase } == [b.scheme, b.host, b.port].map do |part|
47
+ part.to_s.downcase
48
+ end
49
+ rescue URI::InvalidURIError
50
+ false
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Audience
4
+ module Kit
5
+ # A latitude and longitude, with an optional iBeacon's major and minor values.
6
+ #
7
+ # @!attribute [r] latitude
8
+ # @return [Float] degrees north, -90 to 90
9
+ # @!attribute [r] longitude
10
+ # @return [Float] degrees east, -180 to 180
11
+ # @!attribute [r] beacon_major
12
+ # @return [Integer, nil] an iBeacon's major value, which names a locale; nil or 0 for none
13
+ # @!attribute [r] beacon_minor
14
+ # @return [Integer, nil] an iBeacon's minor value; nil or 0 for none
15
+ Coordinate = Data.define(:latitude, :longitude, :beacon_major, :beacon_minor) do
16
+ def initialize(latitude:, longitude:, beacon_major: nil, beacon_minor: nil)
17
+ super(latitude: Float(latitude), longitude: Float(longitude), beacon_major: beacon_major,
18
+ beacon_minor: beacon_minor)
19
+ end
20
+
21
+ # Parses a WKT point, +POINT (<longitude> <latitude>)+, optionally with an SRID prefix
22
+ # (+SRID=4326;POINT (...)+). Nil when it isn't a point, or isn't a place on Earth (often the two numbers
23
+ # swapped).
24
+ # @param wkt [String]
25
+ # @return [Coordinate, nil]
26
+ def self.from_wkt(wkt)
27
+ match = /POINT\s*\(\s*(-?[\d.]+(?:e-?\d+)?)\s+(-?[\d.]+(?:e-?\d+)?)/i.match(wkt.to_s)
28
+ return nil unless match
29
+
30
+ longitude = Float(match[1])
31
+ latitude = Float(match[2])
32
+ return nil unless latitude.between?(-90, 90) && longitude.between?(-180, 180)
33
+
34
+ new(latitude: latitude, longitude: longitude)
35
+ rescue ArgumentError
36
+ nil
37
+ end
38
+
39
+ # The value to pass as a +CoordinatesInput+ variable. Zero beacon values mean no beacon.
40
+ # @return [Hash{String => Numeric}]
41
+ def to_input
42
+ input = { "latitude" => latitude, "longitude" => longitude }
43
+ input["beaconMajor"] = beacon_major unless beacon_major.to_i.zero?
44
+ input["beaconMinor"] = beacon_minor unless beacon_minor.to_i.zero?
45
+ input
46
+ end
47
+
48
+ # The point as WKT, +POINT (<longitude> <latitude>)+.
49
+ # @return [String]
50
+ def to_wkt
51
+ "POINT (#{number(longitude)} #{number(latitude)})"
52
+ end
53
+
54
+ # The great-circle distance to +other+, in meters.
55
+ # @param other [Coordinate]
56
+ # @return [Float]
57
+ def distance_to(other)
58
+ lat1 = radians(latitude)
59
+ lat2 = radians(other.latitude)
60
+ d_lat = lat2 - lat1
61
+ d_lon = radians(other.longitude - longitude)
62
+ a = (Math.sin(d_lat / 2)**2) + (Math.cos(lat1) * Math.cos(lat2) * (Math.sin(d_lon / 2)**2))
63
+ 2 * 6_371_000.0 * Math.asin([1.0, Math.sqrt(a)].min)
64
+ end
65
+
66
+ private
67
+
68
+ def radians(degrees) = degrees * Math::PI / 180
69
+
70
+ def number(value)
71
+ text = format("%.7f", value).sub(/0+\z/, "").sub(/\.\z/, "")
72
+ text == "-0" ? "0" : text
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Audience
4
+ module Kit
5
+ # The QR code on a cover pass, made from the admission's +passSecret+ every {WINDOW_SECONDS} so it works with no
6
+ # signal and a screenshot stops scanning within a minute:
7
+ #
8
+ # HMC1.<admission id>.<window>.<signature>
9
+ #
10
+ # where window is the Unix time divided by the window length and signature is the first 16 characters of the
11
+ # unpadded URL-safe Base64 HMAC-SHA256 of +<admission id>.<window>+, keyed with the Base64-decoded secret. The
12
+ # door accepts a couple of windows either side, for clock drift. The same codes the apps and other SDKs make.
13
+ module CoverPass
14
+ # What every code starts with.
15
+ PREFIX = "HMC1"
16
+ # How long each code lasts.
17
+ WINDOW_SECONDS = 30
18
+
19
+ module_function
20
+
21
+ # The window +epoch_seconds+ falls in.
22
+ # @param epoch_seconds [Integer]
23
+ # @return [Integer]
24
+ def window(epoch_seconds) = epoch_seconds.floor.div(WINDOW_SECONDS)
25
+
26
+ # Seconds from +epoch_seconds+ until the code changes.
27
+ # @param epoch_seconds [Integer]
28
+ # @return [Integer]
29
+ def seconds_until_next_window(epoch_seconds) = WINDOW_SECONDS - epoch_seconds.floor.modulo(WINDOW_SECONDS)
30
+
31
+ # @return [String] the code's signature for one window
32
+ def signature(admission_id, pass_secret, window)
33
+ key = pass_secret.to_s.unpack1("m")
34
+ mac = OpenSSL::HMAC.digest("SHA256", key, "#{admission_id}.#{window}")
35
+ [mac].pack("m0").tr("+/", "-_").delete("=")[0, 16]
36
+ end
37
+
38
+ # The pass's code at +epoch_seconds+ (now by default).
39
+ # @param admission_id [String]
40
+ # @param pass_secret [String] the admission's +passSecret+ (Base64)
41
+ # @param epoch_seconds [Integer, nil]
42
+ # @return [String]
43
+ def code(admission_id, pass_secret, epoch_seconds = nil)
44
+ current = window(epoch_seconds || Time.now.to_i)
45
+ [PREFIX, admission_id, current.to_s, signature(admission_id, pass_secret, current)].join(".")
46
+ end
47
+
48
+ # Whether +code+ looks like a cover pass, before asking the API.
49
+ # @param code [String]
50
+ # @return [Boolean]
51
+ def code?(code)
52
+ parts = code.to_s.strip.split(".", -1)
53
+ parts.length == 4 && parts[0] == PREFIX && !parts[1].empty? && parts[2].match?(/\A\d+\z/) && !parts[3].empty?
54
+ end
55
+ end
56
+ end
57
+ end