URL redirect from one domain to another using cloudflare - url

I haaave been trying to set up a cloudflare worker to redirecet an URL to another (SOURCE.ie/... -> DESTINATION.com/...).
The destination URL is set up within cloudflare the source-URL however is purchased via Onlydomains.
I have been using the code given in the documentation:
const base = "https://DESTINATION.com"
const statusCode = 301
async function handleRequest(request) {
const url = new URL(request.url)
const { pathname, search } = url
const destinationURL = base + pathname + search
return Response.redirect(destinationURL, statusCode)
}
addEventListener("fetch", async event => {
event.respondWith(handleRequest(event.request))
})
What I think have to do now is to aadd a route but is does not want to do that:
Although I added the nameservers to the Onlydomains URL.
Am I missing something? I just want a simple redirect that replaces SOURCE with DESTINATION :|

Related

keycloak-js appending session data to url in vue3

keycloak-js appears to be appending session data when I refresh my vue3 application: https://my.domain/#/&state={state}&session={session} etc
I wouldn't have a problem with this except it's breaking my site when I refresh due to the incorrect url format.
I can't find where this appears to be trying to append the data in the url from.
Here is a workaround to configure in router configuration. Credits from this thread.
const removeKeycloakStateQuery = (to, from) => {
const cleanPath = to.path
.replace(/[&\?]code=[^&\$]*/, "")
.replace(/[&\?]state=[^&\$]*/, "")
.replace(/[&\?]session_state=[^&\$]*/, "");
return { path: cleanPath, query: {}, hash: to.hash };
};
// ...
{
path: "/:catchAll(.*)*",
component: () => import("src/pages/component.vue"),
beforeEnter: [removeKeycloakStateQuery],
}
It ended up being that keycloak-js appears to conflict with createWebHashHistory in vue-router. I've updated it to just use createWebHistory and now my site is working.
There is logic in keycloak-js that tries to determine if you're in a query string and I found the problem by stepping through that code in parseCallbackUrl.
Example: As stated, I ended up using createWebHistory instead of createWebHashHistory. I made the change in my router/index.js file in the createRouter method passing the history option:
import { createRouter, createWebHistory } from 'vue-router'
/* Other router code here */
const router = createRouter({
history: createWebHistory(), // was createWebHashHistory() with matching import substitution
routes
})
export default router

OAuth implicit grant - Can't get the URL fragment, which contains the access token

I'm trying to implement the implicit grant OAuth flow using AWS Cognito. In particular, after having already logged in to my website, I'm trying to make a GET request to Cognito's AUTHORIZATION endpoint; the response from this request should redirect me to a URL of my choosing - let's call this the callback URL - and provide the desired access token in the fragment.
If I make this request by entering into the browser's address bar the appropriate URL for the AUTHORIZATION endpoint, everything happens as expected: The browser gets redirected to the callback URL, and the access token appears in the fragment of this URL.
However, if I make this same request asynchronously from a script in my website using XMLHttpRequest, I am unable to access the fragment returned in the callback URL (and Chrome's network tab shows that the token-containing fragment is in fact returned, just like in the address bar scenario described above). How can I access this fragment?
My code is as follows:
let xhr = new XMLHttpRequest();
let method = options.method.toUpperCase();
let extractFrom = ['url', 'code'];
xhr.open(options.method, options.url, true);
xhr.withCredentials = true;
for (const key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
xhr.onreadystatechange = function () {
const status = this.status;
const respUrl = this.responseURL;
const respHeaders = this.getAllResponseHeaders();
const respBody = this.response;
if (this.readyState === XMLHttpRequest.DONE) {
if (status === 200) {
let val = extractParameter(extractFrom[0], respUrl, extractFrom[1]);
resolve(val);
} else {
console.error('Other Response Text: ' + this.statusText);
reject(this.statusText);
}
}
};
xhr.onerror = function () {
console.error('Error: ' + xhr.statusText);
reject(this.statusText);
};
xhr.send(null);
The fragment is client site stuff, only stays in browser. You will need use javascript to pull it explicitly, see https://openid.net/specs/openid-connect-core-1_0.html#FragmentNotes. You could avoid fragment by using response_mode=form_post if OpenID Connect server supports it, see https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html.

get absolute url on handle ressource request on blackberry

I use this method the get the urls of ressources contain on web page
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception
{
final String url = request.getURL();
return super.handleResourceRequest(request);
}
But, I made request.getURL(); it returns relative url and not the absolute url.
How can I change it to get the absolute URL?
When I run your code, it does return me absolute URLs, even when my web page contained relative links. That said, it wouldn't surprise me if sometimes, it doesn't. I haven't fully tested this code, but I would think you could try something like this.
Basically, you check to see if the URL is absolute, and if not, you assemble an absolute URL by using the parent BrowserField document URL:
ProtocolController controller = new ProtocolController(_browserField) {
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
String absoluteUrl = null;
URI uri = URI.create(request.getURL());
if (uri.isAbsolute()) {
absoluteUrl = request.getURL();
} else {
String docUrl = _browserField.getDocumentUrl();
String url = request.getURL();
if (url.startsWith("/")) {
// the URL is relative to the server root
URI docUri = URI.create(docUrl);
absoluteUrl = docUri.getScheme() + "://" + docUri.getHost() + url;
} else {
// the URL is relative to the document URL
absoluteUrl = docUrl + url;
}
}
System.out.println(" requesting: " + absoluteUrl);
return super.handleResourceRequest(request);
}
}
Again, for me, I was getting absolute URLs, so I couldn't easily test the code in the branch where the URL is relative. So, it's possible that I'm dropping a "/" somewhere, or not handling file:/// URLs properly.
But, this is a starting point, to workaround your problem.

Extjs 4 - How can I get the complete url with params from a currently loaded grid's store?

I have a grid loaded, I want to get the current stores URL which loaded the json data to it , and pass an extra param to it, and load this URL as a pdf, or xls. But how can I get the url?
Get the proxy and ExtraParams:
var url = grid.getStore().getProxy().url;
var params = grid.getStore().getProxy().extraParams;
Then, build the url:
var newUrl = url + '?' + Ext.Object.toQueryString (params);
And the newUrl will be something like this:
your_url_data.json?param1=value1&param2=value2
I don't think that exists a proxy method that do this but you can extend an existing proxy, as follows:
Ext.define ('MyProxy', {
extend: 'Ext.data.proxy.Ajax' ,
buildInternalUrl: function () {
return this.url + '?' + Ext.Object.toQueryString (this.extraParams);
}
});
And then:
var newUrl = grid.getStore().getProxy().buildInternalUrl ();
Result is the same ;)
Here's you can find the doc of proxies: Ajax Proxy
you can get the stores url by yourGrid.getStore().getProxy().url

How to add campaign tracking data to any url automatically?

I get a bunch of different URL from my sources and what I would like is to redirect to the same URL, but with campaign data added to URL (to track the referred clicks).
For example I have these URLs:
www.example.com/category/product/name.html
www.example.com/id_product=5
I want to add at the end the following: utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
And the URLs to become
www.example.com/category/product/name.html?utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
www.example.com/id_product=5&utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
How to I correctly check and cover all the cases if a URL string has parameters, and add mine?
I want to do it in node.js
Thank you
Elaborating on #snkashis, a similar but arguably more elegant solution, again using node's url module, is:
var addQueryParams = function (cleanUrl) {
var obj = url.parse(cleanUrl, true, false);
obj.query['utm_source'] = 'SOURCE';
obj.query['utm_medium'] = 'MEDIUM';
obj.query['utm_campaign'] = 'CAMPAIGN';
delete obj.search; // this makes format compose the search string out of the query object
var trackedUrl = url.format(obj);
return trackedUrl;
};
This works, because url.format first looks for search and, if it can't find it, it composes the query string from the query object
(taken from node url module documentation http://nodejs.org/api/url.html#url_url_format_urlobj )
search will be used in place of query
query (object; see querystring) will only be used if search is absent.
Here is a example showing different scenarios using Node's URL module.
var url = require('url');
var exurls = ["www.example.com/category/product/name.html","www.example.com/id_product=5?hasparam=yes"]
var to_append = "utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN";
for (i=0;i<exurls.length;i++) {
var parsedobj = url.parse(exurls[i],true,false);
//Below checks if param obj is empty.
if (Object.keys(parsedobj.query).length!==0) {
var newpath = parsedobj.href+"&"+to_append;
}
else {
var newpath = parsedobj.href+"?"+to_append;
}
console.log(newpath);
}
Connect will help you:
var connect = require('connect');
var app = connect();
app.use(connect.query());
app.use(function (req, res, next) {
console.log(req.query);
res.end(JSON.stringify(req.query));
});
app.listen(3000);

Resources