How to expose a static html page from ionic - node.js

I have a static html page which intercept authorization message, I'd like to expose this on the domain. It looks like so:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>JwtAuthDemo - Facebook Auth</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="assets/util.js"></script>
</head>
<body>
<script>
// if we don't receive an access token then login failed and/or the user has not connected properly
var accessToken = getParameterByName("access_token");
var message = {};
if (accessToken) {
message.status = true;
message.accessToken = accessToken;
}
else
{
message.status = false;
message.error = getParameterByName("error");
message.errorDescription = getParameterByName("error_description");
}
window.opener.postMessage(JSON.stringify(message), "http://localhost:5000");
</script>
</body>
</html>
If I place this page next to the index.html page it is not exposed, however when I place it inside the assets folder it can be access. I'm guessing I have to explicitly expose the page in one of the json config files however I'm not to sure how to do so?
I'd prefer not to have my redirect url be www.mydomain.com/assets/oauth-response-parser.html. I'd like to keep this in my application seeing as it's part of the application.
How can I expose a static html page from Ionic as a sibling to the index.html page ?

You can automatically get files to your assets directory by specifying that you want to run a custom script during your ionic builds.
In your package.json you'd have a 'config' section where you can specify this script:
...
"config": {
"ionic_copy": "./config/customCopy.config.js"
},
...
and then your customCopy.config.js would contain an entry to copy over your html into assets:
module.exports = {
copyAssets: {
src: ['{{SRC}}/assets/**/*'],
dest: '{{WWW}}/assets'
}
}
More info on this process at the ionic app scripts page
I hope this steers you in the right direction.

Related

routing a webpage error, nodejs and expressjs

I am trying to route directly to the html file using express.js, getting an unknown error, being new to express.js, I couldn't get how to resolve this one:-
here is the js code :-
const express = require('express');
const path = require();
const app = express();
const port=process.env.PORT || 8000;
// public static path
const static_path = path.join(__dirname,"../public");
app.use(express.static(static_path));
app.get("",(req,res)=>{
res.send("welcome to this main page");
})
app.get("/about",(req,res)=>{
res.send("welcome to this about page");
})
app.get("/weather",(req,res)=>{
res.send("welcome to this weather page");
})
app.get("*",(req,res)=>{
res.send("404 Error page oops");
})
app.listen(port,()=>{
console.log(`listening to the port ${port}`);
})
static web page:-
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Welcome to the static web</h1>
</body>
</html>
getting this error:-
internal/validators.js:124
throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "id" argument must be of type string. Received undefined
ok, I was using "type nul > filename" command for creating new files in attached folders. When I used directly the VSCode feature of creating files, it's working fine now,... don't know why, but I think that old command might have expired, tell me if I am wrong, but I just solved my issue...

Service to Service authentication with Managed Identity in Azure

From my Azure Function I'm trying to access an API endpoint of another custom service that has been registered as an app in azure. I have Managed Identity enabled for my azure function. I use the following code to obtain a token:
var tokenIssuerAddress = #"uriOfServiceThatImTryingToConsume";
var tokenProvider = new AzureServiceTokenProvider("RunAs=App");
var accessToken = await tokenProvider.GetAccessTokenAsync(tokenIssuerAddress);
This seems to be fine since I'm getting a bearer token. But when I then try to call the service itself with the token:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{accessToken}");
var response = await client.GetAsync($"{uriOfServiceThatImTryingToConsume}{path}");
}
I get a 200 OK but the response is a HTML page that starts with the following:
<!-- Copyright (C) Microsoft Corporation. All rights reserved. -->
<!DOCTYPE html>
<html dir="ltr" class="" lang="en">
<head>
<title>Sign in to your account</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<link rel="preconnect" href="https://aadcdn.msftauth.net" crossorigin>
<meta http-equiv="x-dns-prefetch-control" content="on">
<link rel="dns-prefetch" href="//aadcdn.msftauth.net">
<link rel="dns-prefetch" href="//aadcdn.msauth.net">
Why do I get a HTML login page as the response when I'm using the bearer token that I got? Am I missing a step?
You have done the right thing by registering the api as an app in Azure. You also have to add the Authentication middleware like
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
AuthenticationSettings settings = Configuration.GetSection("Authentication").Get<AuthenticationSettings>();
o.Authority = settings.Authority;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = new[]
{
settings.ClientId,
settings.ApplicationIdUri
}
};
});
Then add "UseAuthentication" in the pipleline. See if this helps.
Assuming that the bearer token you are getting is valid and what you expect (you can always decode it to see a look at its claims), then you need to provide more details about the specific service you are calling. It's possible that the service requires 2FA or has other authentication strength policy that your bearer token does not meet and is thereby redirecting to continue authentication.

How to change the line "var domToPdf = require('dom-to-pdf');"

I want to use a NodeJs Module on the browser. I read, that I can do this with http://browserify.org/.
Concret I want to use this NodeJs Module: https://github.com/ovvn/dom-to-pdf
So I create a bundle.js form this like explained here: http://browserify.org/
You can see my bundle in my github repo: https://github.com/astridx/dom-to-pdf/blob/javascriptexport_browserify/bundle.js
But now I do not know how to go on. I created an example: https://github.com/astridx/dom-to-pdf/blob/javascriptexport_browserify/example/index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./../bundle.js"></script>
</head>
<body>
<div id="test">TODO write content</div>
<script>
var domToPdf = require('dom-to-pdf');
var element = document.getElementById('test');
var options = {
filename: 'test.pdf'
};
domToPdf(element, options, function () {
console.log('done');
});
</script>
</body>
</html>
But I do not know how to change the line var domToPdf = require('dom-to-pdf');
Can someone give me a hint?
Try using import instead, but you might need babel for that to work properly.
e.g import domToPdf from 'dom-to-pdf';

How to re-translate image from other website (hiding source URL)

I have a link to the image like
this or that.
I'm trying to re-translate this image from other source URL to some link, f.e http(s)://examplewebsite.com/john.
So, it doesn't need to be a redirect, but rather "showing" image on a different link. I've tried using express.static but it doesn't work.
Thanks in advance
If I understand it right, you have your express server and you want to include foreign images in response while hiding source url
In the simplest form, every time someone requests your page, you would fetch the image you want, encode it in base64 and include this base64 as src for the img
const express = require('express')
const fetch = require('node-fetch')
const app = express()
const port = 3000
app.get('/', (req, res) => {
fetch('https://www.gravatar.com/avatar/fdb4d2674d818861be4a4139469ebe59?s=48&d=identicon&r=PG&f=1')
.then(res => res.buffer())
.then(buffer => {
res.send(`
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>hello</p>
<img src="data:image\png;base64, ${buffer.toString('base64')}" alt="image">
</body>
</html>
`)
})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
ideally you would create a separate endpoint for these images and also cache them (in memory or on hard drive) to not re-download them every time you need them

html-webpack-plugin - How to insert webpack bundle.js without executing the EJS template

I am trying to insert bundle.js dynamically without executing the EJS template but I get the below error. Is there a way to insert just the JS without executing the EJS template?
ERROR in Template execution failed: ReferenceError: description is not defined
ERROR in ReferenceError: description is not defined
I am actually rendering the template using node and I just want the bundle file to be dynamically inserted in the template.ejs
res.status(200).render('template',
{
description: description,
title:title
});
webpack config:
output: {
path: path.join(__dirname, 'dist'),
filename: "output.[hash].bundle.js",
publicPath: '/'
},
new HtmlWebpackPlugin({
inject: 'body',
template: 'views/template.ejs'
}),
template.ejs
<!DOCTYPE html>
<html lang="en" class="ddhub-site">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="format-detection" content="telephone=no">
<meta description=<%=description%>/>
<title> <%= title %> </title>
</head>
<body></body>
</html>
I ended up using a simple custom plugin with the information posted on one of the github issue.
var fs = require("fs");
const path = require('path')
function UpdateBundleJsPlugin(options) {
// Setup the plugin instance with options...
}
UpdateBundleJsPlugin.prototype.apply = function(compiler) {
compiler.plugin("done", function(statsData) {
const stats = statsData.toJson();
if (!stats.errors.length) {
const htmlFileName = "search.ejs";
const html = fs.readFileSync(path.join('./views',htmlFileName), "utf8");
// need to read the final js bundle file to replace in the distributed index.html file
const asset = stats.assets[0];
let htmlOutput = html.replace(/static\/.*bundle\.js/, 'static/'+asset.name);
fs.writeFileSync(
path.join('./views', htmlFileName),
htmlOutput);
}
});
};
module.exports = UpdateBundleJsPlugin;
Why not use:
plugins: [
new HtmlWebpackPlugin({
hash: true,
template: 'ejs-render!./dev/index.ejs',
inject: 'body'
})
]
With the ejs-render-loader:
https://github.com/tracker1/ejs-render-loader

Resources