-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Schematic to Enable SSR in Existing ABP Angular Projects #23428
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
Closed
Closed
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
4b1e9b1
ssr migration schematics added
erdemcaygor 033a032
refactoring
erdemcaygor 51f25e7
refactoring
erdemcaygor 691648e
refactoring
erdemcaygor 04620ce
refactoring
erdemcaygor 8e3a1c2
refactoring
erdemcaygor 7ac6dcd
Merge branch 'feature/ssr-support' into feature/ssr-migration-schematic
erdemcaygor d1377af
refactoring
erdemcaygor 2b21d75
refactoring
erdemcaygor 59ffcfd
refactoring
erdemcaygor 03d2b4a
Merge branch 'dev' into feature/ssr-migration-schematic
erdemcaygor 79bc26f
refactoring
erdemcaygor bde7804
refactoring
erdemcaygor 5007f7c
refactoring
erdemcaygor 5106cee
Merge branch 'rel-10.0' into feature/ssr-migration-schematic
erdemcaygor 530ddcb
Merge branch 'dev' into feature/ssr-migration-schematic
erdemcaygor e1634bd
refactoring
erdemcaygor 9c0442e
new function added to tsconfig variable update
erdemcaygor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
192 changes: 192 additions & 0 deletions
192
...cks/packages/schematics/src/commands/ssr-add/files/application-builder/server.ts.template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| import { | ||
| AngularNodeAppEngine, | ||
| createNodeRequestHandler, | ||
| isMainModule, | ||
| writeResponseToNodeResponse, | ||
| } from '@angular/ssr/node'; | ||
| import express from 'express'; | ||
| import { dirname, resolve } from 'node:path'; | ||
| import { fileURLToPath } from 'node:url'; | ||
| import {environment} from './environments/environment'; | ||
| import { ServerCookieParser } from '@abp/ng.core'; | ||
|
|
||
| // ESM import | ||
| import * as oidc from 'openid-client'; | ||
|
|
||
| if (environment.production === false) { | ||
| process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = "0"; | ||
| } | ||
|
|
||
| const serverDistFolder = dirname(fileURLToPath(import.meta.url)); | ||
| const browserDistFolder = resolve(serverDistFolder, '../browser'); | ||
|
|
||
| const app = express(); | ||
| const angularApp = new AngularNodeAppEngine(); | ||
|
|
||
| const ISSUER = new URL(environment.oAuthConfig.issuer); | ||
| const CLIENT_ID = environment.oAuthConfig.clientId; | ||
| const REDIRECT_URI = environment.oAuthConfig.redirectUri; | ||
| const SCOPE = environment.oAuthConfig.scope; | ||
| // @ts-ignore | ||
| const CLIENT_SECRET = environment.oAuthConfig.clientSecret || undefined; | ||
|
|
||
| const config = await oidc.discovery(ISSUER, CLIENT_ID, CLIENT_SECRET); | ||
| const secureCookie = { httpOnly: true, sameSite: 'lax' as const, secure: environment.production, path: '/' }; | ||
| const tokenCookie = { ...secureCookie, httpOnly: false }; | ||
|
|
||
| app.use(ServerCookieParser.middleware()); | ||
|
|
||
| const sessions = new Map<string, { pkce?: string; state?: string; refresh?: string; at?: string, returnUrl?: string }>(); | ||
|
|
||
| app.get('/authorize', async (_req, res) => { | ||
| const code_verifier = oidc.randomPKCECodeVerifier(); | ||
| const code_challenge = await oidc.calculatePKCECodeChallenge(code_verifier); | ||
| const state = oidc.randomState(); | ||
|
|
||
| if (_req.query.returnUrl) { | ||
| const returnUrl = String(_req.query.returnUrl || null); | ||
| res.cookie('returnUrl', returnUrl, { ...secureCookie, maxAge: 5 * 60 * 1000 }); | ||
| } | ||
|
|
||
| const sid = crypto.randomUUID(); | ||
| sessions.set(sid, { pkce: code_verifier, state }); | ||
| res.cookie('sid', sid, secureCookie); | ||
|
|
||
| const url = oidc.buildAuthorizationUrl(config, { | ||
| redirect_uri: REDIRECT_URI, | ||
| scope: SCOPE, | ||
| code_challenge, | ||
| code_challenge_method: 'S256', | ||
| state, | ||
| }); | ||
| res.redirect(url.toString()); | ||
| }); | ||
|
|
||
| app.get('/logout', async (req, res) => { | ||
| try { | ||
| const sid = req.cookies.sid; | ||
|
|
||
| if (sid && sessions.has(sid)) { | ||
| sessions.delete(sid); | ||
| } | ||
|
|
||
| res.clearCookie('sid', secureCookie); | ||
| res.clearCookie('access_token', tokenCookie); | ||
| res.clearCookie('refresh_token', secureCookie); | ||
| res.clearCookie('expires_at', tokenCookie); | ||
| res.clearCookie('returnUrl', secureCookie); | ||
|
|
||
| const endSessionEndpoint = config.serverMetadata().end_session_endpoint; | ||
| if (endSessionEndpoint) { | ||
| const logoutUrl = new URL(endSessionEndpoint); | ||
| logoutUrl.searchParams.set('post_logout_redirect_uri', REDIRECT_URI); | ||
| logoutUrl.searchParams.set('client_id', CLIENT_ID); | ||
|
|
||
| return res.redirect(logoutUrl.toString()); | ||
| } | ||
| res.redirect('/'); | ||
|
|
||
| } catch (error) { | ||
| console.error('Logout error:', error); | ||
| res.status(500).send('Logout error'); | ||
| } | ||
| }); | ||
|
|
||
| app.get('/', async (req, res, next) => { | ||
| try { | ||
| const { code, state } = req.query as any; | ||
| if (!code || !state) return next(); | ||
|
|
||
| const sid = req.cookies.sid; | ||
| const sess = sid && sessions.get(sid); | ||
| if (!sess || state !== sess.state) return res.status(400).send('invalid state'); | ||
|
|
||
| const tokenEndpoint = config.serverMetadata().token_endpoint!; | ||
| const body = new URLSearchParams({ | ||
| grant_type: 'authorization_code', | ||
| code: String(code), | ||
| redirect_uri: environment.oAuthConfig.redirectUri, | ||
| code_verifier: sess.pkce!, | ||
| client_id: CLIENT_ID, | ||
| client_secret: CLIENT_SECRET || '' | ||
| }); | ||
|
|
||
| const resp = await fetch(tokenEndpoint, { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/x-www-form-urlencoded' }, | ||
| body, | ||
| }); | ||
|
|
||
| if (!resp.ok) { | ||
| const errTxt = await resp.text(); | ||
| console.error('token error:', resp.status, errTxt); | ||
| return res.status(500).send('token error'); | ||
| } | ||
|
|
||
| const tokens = await resp.json(); | ||
|
|
||
| const expiresInSec = | ||
| Number(tokens.expires_in ?? tokens.expiresIn ?? 3600); | ||
| const skewSec = 60; | ||
| const accessExpiresAt = new Date( | ||
| Date.now() + Math.max(0, expiresInSec - skewSec) * 1000 | ||
| ); | ||
|
|
||
| sessions.set(sid, { ...sess, at: tokens.access_token, refresh: tokens.refresh_token }); | ||
| res.cookie('access_token', tokens.access_token, {...tokenCookie, maxAge: accessExpiresAt.getTime()}); | ||
| res.cookie('refresh_token', tokens.refresh_token, secureCookie); | ||
| res.cookie('expires_at', String(accessExpiresAt.getTime()), tokenCookie); | ||
|
|
||
| const returnUrl = req.cookies?.returnUrl ?? '/'; | ||
| res.clearCookie('returnUrl', secureCookie); | ||
|
|
||
| return res.redirect(returnUrl); | ||
| } catch (e) { | ||
| console.error('OIDC error:', e); | ||
| return res.status(500).send('oidc error'); | ||
| } | ||
| }); | ||
|
|
||
| /** | ||
| * Serve static files from /browser | ||
| */ | ||
| app.use( | ||
| express.static(browserDistFolder, { | ||
| maxAge: '1y', | ||
| index: false, | ||
| redirect: false, | ||
| }), | ||
| ); | ||
|
|
||
| /** | ||
| * Handle all other requests by rendering the Angular application. | ||
| */ | ||
| app.use((req, res, next) => { | ||
| angularApp | ||
| .handle(req) | ||
| .then(response => { | ||
| if (response) { | ||
| res.cookie('ssr-init', 'true', {...secureCookie, httpOnly: false}); | ||
| return writeResponseToNodeResponse(response, res); | ||
| } else { | ||
| return next() | ||
| } | ||
| }) | ||
| .catch(next); | ||
| }); | ||
|
|
||
| /** | ||
| * Start the server if this module is the main entry point. | ||
| * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000. | ||
| */ | ||
| if (isMainModule(import.meta.url)) { | ||
| const port = process.env['PORT'] || 4200; | ||
| app.listen(port, () => { | ||
| console.log(`Node Express server listening on http://localhost:${port}`); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions. | ||
| */ | ||
| export const reqHandler = createNodeRequestHandler(app); | ||
74 changes: 74 additions & 0 deletions
74
...ng-packs/packages/schematics/src/commands/ssr-add/files/server-builder/server.ts.template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import 'zone.js/node'; | ||
|
|
||
| import { APP_BASE_HREF } from '@angular/common'; | ||
| import { CommonEngine } from '@angular/ssr/node'; | ||
| import express from 'express'; | ||
| import { existsSync } from 'node:fs'; | ||
| import { join } from 'node:path'; | ||
| import <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %> from './main.server'; | ||
|
|
||
| // The Express app is exported so that it can be used by serverless Functions. | ||
| export function app(): express.Express { | ||
| const server = express(); | ||
| const distFolder = join(process.cwd(), '<%= browserDistDirectory %>'); | ||
| const indexHtml = existsSync(join(distFolder, 'index.original.html')) | ||
| ? join(distFolder, 'index.original.html') | ||
| : join(distFolder, 'index.html'); | ||
|
|
||
| const commonEngine = new CommonEngine(); | ||
|
|
||
| server.set('view engine', 'html'); | ||
| server.set('views', distFolder); | ||
|
|
||
| // Example Express Rest API endpoints | ||
| // server.get('/api/{*splat}', (req, res) => { }); | ||
| // Serve static files from /browser | ||
| server.use(express.static(distFolder, { | ||
| maxAge: '1y', | ||
| index: false, | ||
| })); | ||
|
|
||
| // All regular routes use the Angular engine | ||
| server.use((req, res, next) => { | ||
| const { protocol, originalUrl, baseUrl, headers } = req; | ||
|
|
||
| commonEngine | ||
| .render({ | ||
| <% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>, | ||
| documentFilePath: indexHtml, | ||
| url: `${protocol}://${headers.host}${originalUrl}`, | ||
| publicPath: distFolder, | ||
| providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }, { provide: 'cookies', useValue: JSON.stringify(req.headers.cookie) }], | ||
| }) | ||
| .then((html) => res.send(html)) | ||
| .catch((err) => next(err)); | ||
| }); | ||
|
|
||
| return server; | ||
| } | ||
|
|
||
| function run(): void { | ||
| const port = process.env['PORT'] || 4000; | ||
|
|
||
| // Start up the Node server | ||
| const server = app(); | ||
| server.listen(port, (error) => { | ||
| if (error) { | ||
| throw error; | ||
| } | ||
|
|
||
| console.log(`Node Express server listening on http://localhost:${port}`); | ||
| }); | ||
| } | ||
|
|
||
| // Webpack will replace 'require' with '__webpack_require__' | ||
| // '__non_webpack_require__' is a proxy to Node 'require' | ||
| // The below code is to ensure that the server is run only when not requiring the bundle. | ||
| declare const __non_webpack_require__: NodeRequire; | ||
| const mainModule = __non_webpack_require__.main; | ||
| const moduleFilename = mainModule && mainModule.filename || ''; | ||
| if (moduleFilename === __filename || moduleFilename.includes('iisnode')) { | ||
| run(); | ||
| } | ||
|
|
||
| export default <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %>; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Disabling TLS certificate validation in non-production environments is a security risk. Consider using a more secure approach such as configuring trusted certificates or using a development proxy with proper certificates.