Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: access bridge service #616

Merged
merged 143 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
143 commits
Select commit Hold shift + click to select a range
ef33f18
feat(project): access bridge initial structure
kiremitrov123 Jul 18, 2024
4358d94
feat(project): yarn
kiremitrov123 Jul 18, 2024
88c51b7
feat(project): add lint-staged
kiremitrov123 Jul 18, 2024
e7c582b
feat(project): error for unused imports
kiremitrov123 Jul 19, 2024
3fc50a4
feat(project): remove not needed ls-lint
kiremitrov123 Jul 19, 2024
d6d283b
feat(project): add access tests
kiremitrov123 Jul 20, 2024
d18fe2d
feat(project): rename error message
kiremitrov123 Jul 20, 2024
12cc7f5
feat(project): readme and docs
kiremitrov123 Jul 22, 2024
7399e70
Merge branch 'develop' of https://github.com/jwplayer/ott-web-app int…
kiremitrov123 Jul 22, 2024
ac75a09
chore: rename project in package
kiremitrov123 Jul 22, 2024
5a72ec6
feat(project): include SIMS authorization
kiremitrov123 Jul 22, 2024
aec8347
chore: replace jw/fet with standard prettier config
kiremitrov123 Jul 22, 2024
66e5af9
chore: access-bridge changes to not trigger e2e tests
kiremitrov123 Jul 22, 2024
dada55d
chore: revert web env
kiremitrov123 Jul 22, 2024
478cd3b
feat(project): add stripe products endpoint
kiremitrov123 Jul 23, 2024
7499b37
chore: yarn update
kiremitrov123 Jul 23, 2024
e2e5dc3
feat(project): move types in common package
kiremitrov123 Jul 23, 2024
a88e20b
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 23, 2024
c055114
feat(project): update allowed methods
kiremitrov123 Jul 23, 2024
aa8d39a
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 23, 2024
c44b17a
chore: rename stripe service fnc name
kiremitrov123 Jul 24, 2024
5f473d5
feat(project): make authorization optional
kiremitrov123 Jul 24, 2024
e1e13aa
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 24, 2024
7080e72
feat(project): redefine functions with obj params
kiremitrov123 Jul 24, 2024
81cf353
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 24, 2024
5f7c7cf
chore: consistent naming convention
kiremitrov123 Jul 24, 2024
4ad3716
chore: update namings
kiremitrov123 Jul 24, 2024
eabf817
feat(project): add test fixtures
kiremitrov123 Jul 24, 2024
4c2a1cf
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 24, 2024
afba6bb
feat(project): add tests for stripe
kiremitrov123 Jul 25, 2024
70b5d9b
feat(project): fine-tune error descriptions
kiremitrov123 Jul 25, 2024
cff8e03
feat(project): use err code enum instead of hardcoded
kiremitrov123 Jul 25, 2024
30cc325
feat(project): add stripe checkout
kiremitrov123 Jul 25, 2024
b5b96e5
chore: move types in common
kiremitrov123 Jul 25, 2024
ed29191
chore: move types in common
kiremitrov123 Jul 25, 2024
36daa91
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 25, 2024
2a1ee0e
feat(project): add types in common
kiremitrov123 Jul 25, 2024
54713ec
feat(project): add tests for stripe checkout
kiremitrov123 Jul 26, 2024
e918525
feat(project): add more tests for checkout
kiremitrov123 Jul 28, 2024
0557a39
chore: stripe checkout params
kiremitrov123 Jul 28, 2024
2ba1416
feat(project): add test mocks class
kiremitrov123 Jul 29, 2024
5c2ae2c
feat(project): add metadata in stripe checkout
kiremitrov123 Jul 29, 2024
b5b50c7
feat(project): add viewer from auth token, handle plan external provi…
kiremitrov123 Jul 30, 2024
1284fd6
feat(project): add viewer from auth token, handle plan external provi…
kiremitrov123 Jul 30, 2024
e889ebd
feat(project): update stripe products filter
kiremitrov123 Jul 30, 2024
c4231be
feat(project): use external providers
kiremitrov123 Jul 30, 2024
ce3d54e
chore: update readme
kiremitrov123 Jul 31, 2024
d146dba
Merge branch 'develop' of https://github.com/jwplayer/ott-web-app int…
kiremitrov123 Jul 31, 2024
bcd00ed
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 31, 2024
6b1dba3
feat(project): update docs
kiremitrov123 Jul 31, 2024
6724a9f
Merge branch 'IDM-169/stripe-products' of https://github.com/jwplayer…
kiremitrov123 Jul 31, 2024
f84494e
feat(project): add account service
kiremitrov123 Jul 31, 2024
93b7698
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 31, 2024
7489d07
feat(project): add accounts service usage
kiremitrov123 Jul 31, 2024
9955d55
chore: remove unused util fnc
kiremitrov123 Jul 31, 2024
2cb2c96
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Jul 31, 2024
75a4989
Merge branch 'IDM-169/stripe-products' of https://github.com/jwplayer…
kiremitrov123 Jul 31, 2024
e175c3b
feat(project): add sentry
kiremitrov123 Aug 1, 2024
0ac404a
feat(project): replace node with vite
kiremitrov123 Aug 20, 2024
3c38ca0
feat(project): refactor server to use express, refactor error handlin…
kiremitrov123 Aug 21, 2024
c7b5718
feat(project): add types for express
kiremitrov123 Aug 21, 2024
c88e831
chore: add .test in the test naimings
kiremitrov123 Aug 21, 2024
0a02f3e
fix: vite version mismatch
kiremitrov123 Aug 21, 2024
5fdfd3c
feat(project): update docs
kiremitrov123 Aug 22, 2024
61e01ea
Merge branch 'develop' of https://github.com/jwplayer/ott-web-app int…
kiremitrov123 Aug 22, 2024
b164ad4
chore: add dummy env variables in the test-unit-snapshot workflow
kiremitrov123 Aug 22, 2024
d7715ce
feat(project): address changes of vite, express and vitest
kiremitrov123 Aug 22, 2024
e9cd076
feat(project): refactor services, decouple plans method
kiremitrov123 Aug 22, 2024
67d8b42
feat(project): update products controller and tests to match the refa…
kiremitrov123 Aug 22, 2024
73d7945
feat(project): refactor app to use vite, express and vitest for testing
kiremitrov123 Aug 22, 2024
24ef0fe
feat(project): load sentry after build
kiremitrov123 Aug 25, 2024
5e13a20
feat(project): add sentry source mapping
kiremitrov123 Aug 25, 2024
08f994b
feat(project): add sentry version and environment
kiremitrov123 Aug 26, 2024
ed41bf4
chore: remove debug sentry
kiremitrov123 Aug 26, 2024
0bb0bd6
feat(project): additional test build for not source mapping on test
kiremitrov123 Aug 26, 2024
239742e
feat(project): add stripe billing portal endpoint
kiremitrov123 Aug 26, 2024
889d299
chore: update readme
kiremitrov123 Aug 26, 2024
c73487f
chore: add stripe dummy secret on test-unit workflow
kiremitrov123 Aug 26, 2024
264a1f6
Merge branch 'IDM-169/stripe-products' of https://github.com/jwplayer…
kiremitrov123 Aug 26, 2024
2797ec3
chore: update checkout params
kiremitrov123 Aug 26, 2024
7fb5808
Merge branch 'IDM-209/stripe-checkout' of https://github.com/jwplayer…
kiremitrov123 Aug 26, 2024
a4e7209
Merge branch 'IDM-220/error-logging' of https://github.com/jwplayer/o…
kiremitrov123 Aug 26, 2024
987e5fa
feat(project): add cors middleware
kiremitrov123 Aug 26, 2024
132e8a2
Merge branch 'IDM-161/IAM-Middleware' of https://github.com/jwplayer/…
kiremitrov123 Aug 26, 2024
6120337
feat(project): add cors middleware
kiremitrov123 Aug 26, 2024
27f115b
feat(project): add site_id in the route
kiremitrov123 Aug 26, 2024
e022515
Merge branch 'IDM-209/stripe-checkout' of https://github.com/jwplayer…
kiremitrov123 Aug 26, 2024
8204e15
feat(project): add site_id in the route
kiremitrov123 Aug 26, 2024
8ef6a24
feat(project): update port it can match google cloud run reqs
kiremitrov123 Aug 29, 2024
8ed3c59
feat(project): use newer version of node to make happy sentry
kiremitrov123 Aug 29, 2024
2a4da7b
feat(project): move error handling to the middleware
kiremitrov123 Sep 3, 2024
7dabd37
feat(project): add refresh passport
kiremitrov123 Sep 3, 2024
07bb8df
chore: update branch
kiremitrov123 Sep 3, 2024
6551e2d
chore: update branch
kiremitrov123 Sep 3, 2024
5ea2d83
feat(project): remove error handling from services
kiremitrov123 Sep 3, 2024
115a218
feat(project): simplify jw error usage
kiremitrov123 Sep 3, 2024
3bd7d10
feat(project): handle stripe errros simplified
kiremitrov123 Sep 3, 2024
f36f1ca
feat(project): remove service level error handling
kiremitrov123 Sep 3, 2024
29fa3f3
feat(project): move error handling to the middleware
kiremitrov123 Sep 3, 2024
3c2bddc
feat(project): remove error handling from service level
kiremitrov123 Sep 3, 2024
54a5477
feat(project): refactor routes and middlewares
kiremitrov123 Sep 11, 2024
d7eacd2
feat(project): refactor structure and namings
kiremitrov123 Sep 11, 2024
7699732
feat(project): add missing case for refresh passport test
kiremitrov123 Sep 11, 2024
69b32de
feat(project): load envs at runtime
kiremitrov123 Sep 12, 2024
514e999
fix(search): override search query cache (#594)
langemike Sep 4, 2024
9d78554
feat(project): app metadata insertion
royschut Sep 4, 2024
a0a7fc4
feat(project): add injectable wrapper to common components (#598)
royschut Sep 4, 2024
2a0e3ca
refactor(project): update services members visibility and explicit in…
ChristiaanScheermeijer Sep 4, 2024
0c3a6ba
feat(project): remove free and productIds from content-types.json (#605)
CarinaDraganJW Sep 5, 2024
5e59035
fix(e2e): fix tests after cleeng api update (#606)
AntonLantukh Sep 6, 2024
cb0df4f
chore(release): v6.6.0
invalid-email-address Sep 6, 2024
0039674
feat(project): refactor routes and middlewares
kiremitrov123 Sep 11, 2024
def9b1c
feat(project): rebase and stuff
kiremitrov123 Sep 12, 2024
72a186a
Merge branch 'develop' of https://github.com/jwplayer/ott-web-app int…
kiremitrov123 Sep 12, 2024
8cb18a7
feat(project): simplify using routes and middlewares
kiremitrov123 Sep 12, 2024
a2e6541
feat(project): add generic payment service that other services will i…
kiremitrov123 Sep 12, 2024
1979ae0
feat(project): update products to use our own types
kiremitrov123 Sep 13, 2024
2272643
chore: add site_id in .env.example
kiremitrov123 Sep 13, 2024
b267b61
feat(project): add stripe error handler in middleware
kiremitrov123 Sep 13, 2024
cd9adc2
feat(project): simplify checkout controller to use shared service iml…
kiremitrov123 Sep 13, 2024
dfa24f0
chore: update readme
kiremitrov123 Sep 13, 2024
29199eb
chore: update comments on stripe payment service
kiremitrov123 Sep 13, 2024
a57359b
chore: remove unused type
kiremitrov123 Sep 13, 2024
5ce22c1
feat(project): adapt new structure and move logger
kiremitrov123 Sep 13, 2024
584cb59
feat(project): update sentry and logger
kiremitrov123 Sep 13, 2024
6173558
chore: node-version
kiremitrov123 Sep 13, 2024
c4b2751
chore: revert node version
kiremitrov123 Sep 13, 2024
53ab754
feat(project): update billing portal url to use the new structure
kiremitrov123 Sep 13, 2024
1f4f826
chore: update comment on checkout controller
kiremitrov123 Sep 13, 2024
cfd5826
chore: revert node version
kiremitrov123 Sep 13, 2024
fb10424
chore: revert env to default
kiremitrov123 Sep 16, 2024
93f78d4
feat(project): modify types for products and prices
kiremitrov123 Sep 16, 2024
3c4220f
feat(project): update test fixtures
kiremitrov123 Sep 16, 2024
f8822f6
Merge branch 'IDM-209/stripe-checkout' of https://github.com/jwplayer…
kiremitrov123 Sep 16, 2024
0504c5b
feat(project): update typings and product fixtures
kiremitrov123 Sep 16, 2024
5968134
feat(project): add deployment file and docs
kiremitrov123 Sep 17, 2024
d5cff56
chore: update readme paths
kiremitrov123 Sep 17, 2024
6aad880
feat(project): remove mode from checkout params
kiremitrov123 Sep 19, 2024
e9cde38
feat(project): remove stripe type
kiremitrov123 Sep 19, 2024
3c81aca
feat(project): merge with develop
kiremitrov123 Sep 19, 2024
83332e7
chore: remove vite build file
kiremitrov123 Sep 19, 2024
df86b96
Merge branch 'develop' of https://github.com/jwplayer/ott-web-app int…
kiremitrov123 Sep 19, 2024
4202042
Merge branch 'develop' into feat/access-bridge-service
kiremitrov123 Sep 19, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/test-unit-snapshot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ jobs:
env:
CI: true
# Dummy environment variables for testing the access-bridge service
APP_SITE_ID: test1234
APP_API_SECRET: dummy_secret
APP_STRIPE_SECRET: dummy_stripe_secret
APP_BIND_ADDR: localhost
APP_BIND_PORT: 3000
APP_BIND_PORT: 8080
APP_ACCESS_CONTROL_API_HOST: https://test-cdn.jwplayer.com
APP_SIMS_API_HOST: https://test-sims.jwplayer.com
40 changes: 40 additions & 0 deletions packages/common/types/payment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
type Recurring = {
// The frequency at which a subscription is billed. One of `month` or `year`.
interval: 'month' | 'year';
// Default number of trial days when subscribing a customer.
trial_period_days: number | null;
};

export type Price = {
// Unique identifier for the object.
id: string;
// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
currency: string;
// The ID of the product this price is associated with.
product: string;
// The recurring components of a price such as `interval` and `trial`.
recurring: Recurring | null;
// The unit amount in cents (or local equivalent) to be charged, represented as a whole integer if possible.
unit_amount: number | null;
};

export type Product = {
// Unique identifier for the object.
id: string;
// The product's name, meant to be displayable to the customer.
name: string;
// The product's description, meant to be displayable to the customer.
// Use this field to optionally store a long form explanation of the product being sold for your own rendering purposes.
description: string;
// The ID of the default price this product is associated with.
default_price: string;
// Array of price objects as defined above
prices: Price[];
};

// General checkout parameters type. Can be extended by specific payment providers, e.g. Stripe
export type CheckoutParams = {
price_id: string;
success_url: string;
cancel_url: string;
};
12 changes: 4 additions & 8 deletions packages/common/types/stripe.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
export type StripeCheckoutParams = {
price_id: string;
mode: 'payment' | 'setup' | 'subscription';
success_url: string;
cancel_url: string;
};
import type { CheckoutParams } from './payment';

export type StripeCheckoutResponse = {
url: string;
// Extend the CheckoutParams type with Stripe-specific fields
export type StripeCheckoutParams = CheckoutParams & {
mode: 'payment' | 'subscription';
};
2 changes: 2 additions & 0 deletions platforms/access-bridge/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ APP_VERSION=$npm_package_version
# Make sure the secrets are V1 and that they refer to the desired property.
# For production env, use this reference on how to store them: https://cloud.google.com/run/docs/configuring/services/secrets
APP_API_SECRET=customer_v1_secret
# site_id or property_id represents the key that corresponds to the APP_API_SECRET defined earlier.
APP_SITE_ID=customer_site_id
# Stripe secret responsible for authenticating Stripe API calls
APP_STRIPE_SECRET=stripe_secret

Expand Down
2 changes: 1 addition & 1 deletion platforms/access-bridge/.gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
node_modules
build
*.local

.env
# Sentry Config File
.env.sentry-build-plugin
23 changes: 22 additions & 1 deletion platforms/access-bridge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ You can also copy and paste the contents of `.env.example` into `.env.local` and
- **Method:** GET
- **Authorization:** None
- **Summary:** Lists all the corresponding stripe products with prices that are connected to the SIMS plans.
- **Response:** Stripe.Product type
- **Response:** [Product payment type](../../../ott-web-app/packages/common/types/payment.ts)
```json
[
{
Expand All @@ -89,6 +89,27 @@ You can also copy and paste the contents of `.env.example` into `.env.local` and
]
```

#### URL: `/v2/sites/{site_id}/checkout`

- **Method:** POST
- **Authorization:** Valid SIMS token
- **Summary:** Creates Payment Checkout Session URL where the viewer will be redirected to complete the payment.
- **Request:**
```json
{
"price_id": "string", // id of the price that is about to be paid
"mode": "string", // subscription (recurring) | payment (one time purchases)
"success_url": "string", // redirect after successful payment
"cancel_url": "string" // redirect after cancel / invalid payment
}
```
- **Response:**
```json
{
"url": "string" // url where the viewer will be redirected to complete the payment.
}
```

## Developer guidelines

- Read the workspace guidelines here [../../docs/developer-guidelines.md](../../docs/developer-guidelines.md).
Expand Down
9 changes: 7 additions & 2 deletions platforms/access-bridge/docs/developer-guidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,21 @@
/src - Source code for the application
/controllers - Controller modules containing the core logic for handling requests and responses
/services - Services which connect external data sources to the application
/app-config.ts - Configuration settings for the application
/endpoints.ts - Definitions for the exposed endpoints
/pipeline - Middleware and routing logic
/middleware.ts - Middleware functions and error handling
/routes.ts - Route definitions and route registration
/errors.ts - Custom error classes and error handling logic
/http.ts - HTTP utility functions and setup
/app-config.ts - Configuration settings for the application
/main.ts - Main entry point of the application
/server.ts - Server initialization and configuration
/test - Data and scripts for testing
/.env<.mode> - Environment variables for different modes (e.g., development, production)
/package.json - Yarn file for dependencies and scripts




* = Generated directories, not in source control

Note: Some system and util files are not shown above for brevity.
Expand Down
18 changes: 0 additions & 18 deletions platforms/access-bridge/instrument.mjs

This file was deleted.

4 changes: 3 additions & 1 deletion platforms/access-bridge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"scripts": {
"build": "vite build --mode ${MODE:=prod}",
"build-test": "vite build --mode test",
"start": "node --import ./build/instrument.js build/main.js",
"start": "node build/main.js",
"prestart": "yarn build",
"pretest": "yarn build-test",
"test": "TZ=UTC LC_ALL=en_US.UTF-8 vitest run",
Expand All @@ -25,6 +25,7 @@
"eslint-config-jwp": "*",
"typescript": "^5.5.3",
"vite": "^5.3.1",
"vite-plugin-node": "^3.1.0",
"vitest": "^1.6.0"
},
"dependencies": {
Expand All @@ -33,6 +34,7 @@
"@sentry/profiling-node": "^8.26.0",
"@sentry/vite-plugin": "^2.22.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"stripe": "^16.8.0"
Expand Down
15 changes: 14 additions & 1 deletion platforms/access-bridge/src/app-config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import dotenv from 'dotenv';
// Inject environment variables at runtime
dotenv.config();

// Function to assert an environment variable is defined
function requireEnvVar(env: string | undefined, name: string): string {
if (!env) {
Expand All @@ -10,13 +14,22 @@ function requireEnvVar(env: string | undefined, name: string): string {
export const API_SECRET = requireEnvVar(process.env.APP_API_SECRET, 'APP_API_SECRET');
export const STRIPE_SECRET = requireEnvVar(process.env.APP_STRIPE_SECRET, 'APP_STRIPE_SECRET');

// SITE_ID specifies the property that the customer is using
export const SITE_ID = requireEnvVar(process.env.APP_SITE_ID, 'APP_SITE_ID');

// BIND_ADDR specifies the network address or IP address on which the server listens for incoming connections.
// This could be an IP address (e.g., '127.0.0.1' for localhost) or a hostname.
export const BIND_ADDR = requireEnvVar(process.env.APP_BIND_ADDR, 'APP_BIND_ADDR');

// BIND_PORT specifies the port number on which the server listens for incoming connections.
// Ensure this port is available and not in use by another application.
export const BIND_PORT = parseInt(requireEnvVar(process.env.APP_BIND_PORT, 'APP_BIND_PORT'), 10);
export const BIND_PORT = (() => {
const port = parseInt(requireEnvVar(process.env.APP_BIND_PORT, 'APP_BIND_PORT'), 10);
if (isNaN(port)) {
throw new Error(`Environment variable "APP_BIND_PORT" must be a valid number.`);
}
return port;
})();

// Client host URLs
export const ACCESS_CONTROL_API_HOST = requireEnvVar(
Expand Down
101 changes: 28 additions & 73 deletions platforms/access-bridge/src/controllers/access-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@ import { Request, Response, NextFunction } from 'express';
import { ErrorDefinitions, sendErrors } from '../errors.js';
import { PassportService } from '../services/passport-service.js';
import { PlansService } from '../services/plans-service.js';
import { isValidSiteId } from '../utils.js';
import { IdentityService, Viewer } from '../services/identity-service.js';
import logger from '../logger.js';

/**
* Controller class responsible for handling access-related services.
* The controller interacts with services for identity management, plans management, and passport generation.
*/
export class AccessController {
private identityService: IdentityService;
private passportService: PassportService;
private plansService: PlansService;
private readonly identityService: IdentityService;
private readonly passportService: PassportService;
private readonly plansService: PlansService;

constructor() {
this.identityService = new IdentityService();
Expand All @@ -23,86 +21,43 @@ export class AccessController {
}

/**
* Service handler for generating passport access tokens based on the provided site ID
* and authorization token. Validates the site ID, checks user authorization, retrieves
* access control plans, and generates access tokens. Sends appropriate error responses
* for invalid requests.
*
* @param req - Express request object
* @param res - Express response object
* @param next - Express next middleware function
* Service handler for generating passport access tokens based on the provided authorization token.
* Retrieves access control plans and generates access tokens.
*/
async generatePassport(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const siteId = req.params.site_id;
if (!isValidSiteId(siteId)) {
sendErrors(res, ErrorDefinitions.ParameterInvalidError.create({ parameterName: 'site_id' }));
// Anonymous is default for not authenticated viewers.
// These viewers only have access to free plans.
let viewer: Viewer = { id: 'anonymous', email: '' };

const authorization = req.headers['authorization'];
if (authorization) {
viewer = await this.identityService.getAccount({ authorization });
if (!viewer.id || !viewer.email) {
sendErrors(res, ErrorDefinitions.UnauthorizedError.create());
return;
}
}

// anonymous is default for not authenticated viewers
// they only have access to free plans
let viewer: Viewer = { id: 'anonymous', email: '' };

const authorization = req.headers['authorization'];
if (authorization) {
viewer = await this.identityService.getAccount({ authorization });
if (!viewer.id || !viewer.email) {
sendErrors(res, ErrorDefinitions.UnauthorizedError.create());
return;
}
}

const viewerEntitledPlans = await this.plansService.getEntitledPlans({ siteId, authorization });
const plans = viewerEntitledPlans
.map((plan) => ({
id: plan.access_plan?.id,
exp: plan.access_plan?.exp,
}))
.filter((plan) => plan.id !== undefined && plan.exp !== undefined);
const viewerEntitledPlans = await this.plansService.getEntitledPlans({ authorization });
const plans = viewerEntitledPlans
.map((plan) => ({
id: plan.access_plan?.id,
exp: plan.access_plan?.exp,
}))
.filter((plan) => plan.id !== undefined && plan.exp !== undefined);

// Generate passport tokens for the given site, viewer and plans.
const passport = await this.passportService.generatePassport({
siteId,
viewerId: viewer.id,
plans,
});
const passport = await this.passportService.generatePassport({ viewerId: viewer.id, plans });

res.json(passport);
} catch (error) {
logger.error('AccessController: generatePassport: failed to generate passport:', error);
next(error);
}
res.json(passport);
}

/**
* Service handler for refreshing access tokens based on the provided site ID
* and refresh token. Sends appropriate error responses for invalid requests.
*
* @param req - Express request object
* @param res - Express response object
* @param next - Express next middleware function
* Service handler for refreshing access tokens based on the provided refresh token.
*/
async refreshPassport(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const siteId = req.params.site_id;
if (!isValidSiteId(siteId)) {
sendErrors(res, ErrorDefinitions.ParameterInvalidError.create({ parameterName: 'site_id' }));
return;
}

const { refresh_token: refreshToken } = req.body;
if (!refreshToken) {
sendErrors(res, ErrorDefinitions.ParameterMissingError.create({ parameterName: 'refresh_token' }));
return;
}

const passport = await this.passportService.refreshPassport({ siteId, refreshToken });
const { refresh_token: refreshToken } = req.body;
const passport = await this.passportService.refreshPassport({ refreshToken });

res.json(passport);
} catch (error) {
logger.error('AccessController: refreshPassport: failed to refresh passport:', error);
next(error);
}
res.json(passport);
}
}
Loading