Cherrypy configuration for cherrypy.quickstart - python-2.7

This is configuration for /projects endpoint. What modification do i have to add for adding an endpoint "/projects/all" at the same port.
conf = {
'global':{
'server.socket_host': "127.0.0.1",
'server.socket_port': config.SERVER_PORT
},
'/projects': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'application/json')],
}
}
webapp = ApiApp()
webapp.projects = ProjectsApi()
cherrypy.quickstart(webapp, '/', conf)

Related

Adonis: How to connect with SSL (with a certificate.crt file) to MySQL?

I just created a Managed Database on Digital Ocean that requires an SSL connection. How can I do that with Adonis?
This code works for me:
/**************************************************************************
* IMPORTS
***************************************************************************/
// NPM
const fs = require('fs')
// Providers
const Env = use('Env')
/**************************************************************************
* CONFIG > DATABASE
***************************************************************************/
const config = {
connection: Env.get('DB_CONNECTION', 'mysql'),
mysql: {
client: 'mysql',
connection: {
host: Env.get('DB_HOST', 'localhost'),
port: Env.get('DB_PORT', ''),
user: Env.get('DB_USER', 'root'),
password: Env.get('DB_PASSWORD', ''),
database: Env.get('DB_DATABASE', 'adonis'),
},
debug: Env.get('DB_DEBUG', false),
},
}
// Add certificate for production environment
if (Env.get('NODE_ENV') === 'production') {
config.mysql.connection.ssl = {
ca: fs.readFileSync(__dirname + '/certs/ca-database.crt'),
}
}
module.exports = config

How to remove .html extension using AWS Lambda & Cloudfront

I've my website's source code stored in AWS S3 and I'm using AWS Cloudfront to deliver my content.
I want to use AWS Lamda#Edge to remove .html extension from all the web links that's served through Cloudfront.
My required output should be www.example.com/foo instead of www.example.com/foo.html or example.com/foo1 instead of example.com/foo1.html.
Please help me to implement this as I can't find clear solution to use. I've referred the point 3 mentioned on this article: https://forums.aws.amazon.com/thread.jspa?messageID=796961&tstart=0. But it's not clear what I need to do.
PFB the lambda code, how can I modify it-
const config = {
suffix: '.html',
appendToDirs: 'index.html',
removeTrailingSlash: false,
};
const regexSuffixless = /\/[^/.]+$/; // e.g. "/some/page" but not "/", "/some/" or "/some.jpg"
const regexTrailingSlash = /.+\/$/; // e.g. "/some/" or "/some/page/" but not root "/"
exports.handler = function handler(event, context, callback) {
const { request } = event.Records[0].cf;
const { uri } = request;
const { suffix, appendToDirs, removeTrailingSlash } = config;
// Append ".html" to origin request
if (suffix && uri.match(regexSuffixless)) {
request.uri = uri + suffix;
callback(null, request);
return;
}
// Append "index.html" to origin request
if (appendToDirs && uri.match(regexTrailingSlash)) {
request.uri = uri + appendToDirs;
callback(null, request);
return;
}
// Redirect (301) non-root requests ending in "/" to URI without trailing slash
if (removeTrailingSlash && uri.match(/.+\/$/)) {
const response = {
// body: '',
// bodyEncoding: 'text',
headers: {
'location': [{
key: 'Location',
value: uri.slice(0, -1)
}]
},
status: '301',
statusDescription: 'Moved Permanently'
};
callback(null, response);
return;
}
// If nothing matches, return request unchanged
callback(null, request);
};
Please help me to remove .html extension from my website and what updated code do I need to paste in my AWS Lambda
Thanks in advance!!

How to dynamically change Apollo Web Socket Link URI?

Currently I've set up Apollo's web socket link like so:
const wsLink = new WebSocketLink({
uri: `ws://example.com/graphql?token=${getToken()}`,
options: {
reconnect: true,
connectionParams(): ConnectionParams {
return {
authToken: getToken(),
};
},
},
});
This works fine while the connection lasts, but fails when the connection needs to be re-established if the token in the query string has expired.
The way the infra I'm dealing with is set up requires this token to be set as a query param in the URI. How can I dynamically change the URI so that I may provide a new token when the connection needs to be re-established?
You can set property wsLink.subscriptionClient.url manually (or create a new subscriptionClient instance?) in function setContext https://www.apollographql.com/docs/link/links/context/.
For example:
import { setContext } from 'apollo-link-context'
...
const wsLink = your code...
const authLink = setContext(() => {
wsLink.subscriptionClient.url = `ws://example.com/graphql?token=${getToken()}`
})
...
const config = {
link: ApolloLink.from([
authLink,
wsLink
]),
...
}

Couldn't set authentication cookie lifetime - IdentityServer4

I am trying to set the IdentityServer4 authentication cookie lifetime.
This is my client configuration :
// OpenID Connect hybrid flow and client credentials client (MVC)
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
IdentityTokenLifetime = 120,
AccessTokenLifetime = 120,
AuthorizationCodeLifetime = 120,
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
RedirectUris = new List<string>
{
"http://localhost:5002/signin-oidc"
},
PostLogoutRedirectUris = new List<string>
{
"http://localhost:5002"
},
AllowedScopes = new List<string>
{
StandardScopes.OpenId.Name,
StandardScopes.Profile.Name,
StandardScopes.OfflineAccess.Name,
"api1"
}
}
and my Configure method in the mvc client is
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticChallenge = true,
ExpireTimeSpan = System.TimeSpan.FromSeconds(120),
SlidingExpiration = false
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = "http://localhost:5000",
RequireHttpsMetadata = false,
ClientId = "mvc",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = { "api1", "offline_access" },
GetClaimsFromUserInfoEndpoint = true,
SaveTokens = true
});
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
I'm using the below sample from IdentityServer4 samples to learn IdentityServer4.
IdentityServer4.Samples/Quickstarts/5_HybridFlowAuthenticationWithApiAccess
I have already set the cookie expire time, access token life time, identity token life time and authorization code life time. But still the cookie life time is showing as session in the browser. Please see the below image
Am I missed any setting to do?
Any help is greatly appreciated.

Rewrite cookie paths when using grunt-connect-proxy

During development I use grunt-connect-proxy to make some remote APIs locally available. This works just fine, except that the rewrite rules that I use are not applied to cookies:
proxies: [{
context: '/publicPath',
host: 'localhost',
port: 8080,
rewrite: {
'^/publicPath': '/privatePath'
}
}]
If the remote API sets a cookie with path /privatePath it must be rewritten to /publicPath.
E.g. When using Apache httpd I'd use the ProxyPassReverseCookiePath-Directive. How do I do it with grunt-connect-proxy?
Thanks to this answer in "Rewrite response headers with node-http-proxy" I managed to figure it out. I created the following middleware:
function rewriteSetCookie(req, res, next) {
var isProxyRequest = req.url.lastIndexOf('/publicPath', 0) === 0;
if (isProxyRequest) {
// we intercept the writeHead function, so that we can exchange headers just before they are written
var oldWriteHead = res.writeHead;
res.writeHead = function () {
var cookie = res.getHeader('Set-Cookie');
if (cookie) {
res.setHeader('Set-Cookie', cookie.map(function(item) {
// Replace paths in all cookies. The simple string/replace approach might be too naive in some cases, so check before you copy&paste before thinking
return item.replace(/\/privatePath/, '/publicPath');
}));
}
oldWriteHead.apply(res, arguments);
};
}
next();
}
Just for reference here is the full configuration so that you can see how to use the middleware:
connect: {
server: {
options: {
hostname: 'localhost',
base: 'myBaseDir',
open: true,
middleware: function (connect, options) {
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
// Setup the proxy
var middlewares = [rewriteSetCookie, proxySnippet];
// ^^^^^^^^^^^^^^^^- Here is is used!
// Serve static files.
options.base.forEach(function(base) {
middlewares.push(connect.static(base));
});
// Make directory browse-able.
var directory = options.directory || options.base[options.base.length - 1];
middlewares.push(connect.directory(directory));
return middlewares;
}
},
proxies: [{
context: '/publicPath',
host: 'localhost',
port: 8080,
rewrite: {
'^/publicPath': '/privatePath'
}
}]
}
}