How to set application_name with sinatra/sequel - ruby

I'm setting application_name in my connection string like so:
DB = Sequel.connect(:adapter=>'postgres', :host=> 'localhost',
:database=>'blah', :user=>'gator',
:application_name => 'blahwebapp')
However, when I view the pg_stat_activity or any other metric to filter down by application_name I'm not seeing it assigned properly.
My Pg gem is "pg (0.17.0)" and I believe that since 0.16 it's been able to handle the application name. sequel_pg is (1.6.8) and Sequel is (4.2.0).
An application name is set, but it is path/webserver related rather than what is set in the config:
/Users/gator/.rvm/gems/rub...47#blahwebapp/bin/shotgun
Even when I use a URL-type connection string it still doesn't register the application_name:
DB = Sequel.connect('postgres://gator#localhost/blah?application_name=blahwebapp')
That is the same URL I use in psql to connect and it shows up fine.
In the documentation for Sequel I don't see much about application_name as an option which has me worried:
Any thoughts/ideas on how to get it to respect the application_name?

Sequel's PostgreSQL adapter doesn't pass the URL directly to PostgreSQL. It can't really do so and keep backwards compatibility.
It looks like you can just set the application_name at runtime. The best way to do this with Sequel is via after_connect:
DB = Sequel.connect('postgres://gator#localhost/blah', :after_connect=>proc{|c| c.execute("SET application_name TO 'blahwebapp'")})
It is possible to integrate this feature into Sequel so that using it inside the 'postgres://' URL would work correctly. I'm open to that if other people think it would be useful.

Related

How to do a basic GraphQL query to Shopify with Ruby

I'm trying to do a basic GraphQL query to a Shopify store with Sinatra. Could someone help me figure out what I'm doing wrong? I looked at their API to do this:
require 'shopify_api'
require 'sinatra'
class App < Sinatra::Base
get '/' do
shop = 'xxxx.myshopify.com'
token = 'shpat_xxxxxxxxxxxxxxxxxxxxxx'
session = ShopifyAPI::Session.new(domain: shop, token: token, api_version: "2021-04")
ShopifyAPI::Base.activate_session(session)
ShopifyAPI::GraphQL.initialize_clients
client = ShopifyAPI::GraphQL.client
SHOP_NAME_QUERY = client.parse <<-'GRAPHQL'
{
shop {
name
}
}
GRAPHQL
result = client.query(SHOP_NAME_QUERY)
result.data.shop.name
end
end
Which gives this error but I don't want to use Rake or Rails. Is it possible to do a GraphQL query to Shopify with Ruby?
ShopifyAPI::GraphQL::InvalidClient at /
Client for API version 2021-04 does not exist because no schema file exists at `shopify_graphql_schemas/2021-04.json`. To dump the schema file, use the `rake shopify_api:graphql:dump` task
As the error states, you need to first dump the schema (see this link: https://github.com/Shopify/shopify_api/blob/v9/docs/graphql.md#dump-the-schema).
Then you create a shopify_graphql_schemas directory in the same root as your ruby script, and put the generated JSON there.
Like stated in the comments, this requires a Rake task, so you need to be using Rails.
If your project doesn't use Rails, you need to do a quick workaround.
You create a temporary barebones Rails project, then generate the dump using that project (you can delete the project when you're done with this).
It's a bit hacky, but it's the only thing I can see that would work.
New link to schema dump
https://github.com/Shopify/shopify_api/blob/v9/docs/graphql.md#dump-the-schema
You need to use something like this
rake shopify_api:graphql:dump SHOP_DOMAIN="SHOP_NAME.myshopify.com" ACCESS_TOKEN="SHOP_TOKEN" API_VERSION=2022-04
Old one doesn't work anymore

Change phoenix endpoint url host at runtime

Does anyone know of a way of changing the :host of the Phoenix application endpoint dynamically on every request?
Specifically to support multiple domains on a single phoenix app, i want to change the host in the endpoint based on the host in the connection object.
Am trying something on the lines of
conn = Map.get_and_update(conn.private.phoenix_endpoint[:url], :host, fn (_) -> "ll.com" end)
or
Keyword.put(conn.private.phoenix_endpoint.config(:url), :host, conn.host)
But am not quite correct.
Wouldn't it just be a value you assign the :to keyword in the redirect?
def index(conn, params) do
redirect conn, to: params[:location] # or whatever
end
The master_proxy package offers some useful tools to support multiple sites.

Sinatra Session Caching

I'm having a little trouble understanding how to get Sinatra to cache sessions. This problem manifests itself when I fire up more than one application instance (ala Puma or multiple Thins).
I'm asking Sinatra (1.4) to use sessions like this:
enable :sessions
set :session_secret, 'secret sauce'
set :protection, except: :session_hijacking
$connections = []
set connections: $connections
I've left the $connections in there to demonstrate that this App is using server sent events, in case that has any relevance.
I am them using Persona (Mozilla) to support logins/authentication and am ultimately storing the logged in email in Sinatra's session with:
session[:auth_email] = data["email"]
Where data is given to me by Persona.
What I can't work out is how I ask Sinatra to store session data in a persistent store (ideally Redis) so the app can be recycled without losing session state (I've done this with Ramaze before with Ramaze::Cache.options.session = Ramaze::Cache::Redis.using())
Check out Moneta.
The project's Github page gives examples of how to set this up and is extremely easy to integrate with Sinatra.

Grails Spring Security & LDAP Auth Failure

ISSUE: Grails ADMIN logs in via LDAP but no other account does.
System = Win 7, grails 2.2.1, Active Dir lightweight
I have created a simple grails default application, installed the latest grails spring security and ldap plugins. I then followed the following tutorial to configure the spring security setup. Tutorial located at http://blog.springsource.com/2010/08/11/simplified-spring-security-with-grails/
Anyway got spring security working fairly fast, next step was setting up LDAP to use the anonymousAuthenticationProvider so my grails app would log in without checking its own DB for passwords, only LDAP. I am using windows Active Directory. Anyway, followed this configuration setup http://grails-plugins.github.io/grails-spring-security-ldap/docs/manual/guide/2.%20Usage.html . All seems to start fine, except the only user that seems to log in correctly is admin, no other user works. I get a can not find user with that username / password error. I have added error, warn and info log output for spring security but does not seem to give much info at all except for the admin account which actually works. I verified it works as I gave the spring security db password a different password to the ldap password, and once the ldap was configured the only password that worked for the admin was the ldap one. Unfortunately no other users worked though.
Here is my grails config:
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'org.example.SecUser'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'org.example.SecUserSecRole'
grails.plugins.springsecurity.authority.className = 'org.example.SecRole'
grails.plugins.springsecurity.ldap.context.managerDn = 'CN=admin,OU=people,OU=imApp,DC=example,DC=org'
grails.plugins.springsecurity.ldap.context.managerPassword = 'password'
grails.plugins.springsecurity.ldap.context.server = 'ldap://localhost:55000/'
grails.plugins.springsecurity.ldap.authorities.ignorePartialResultException = true
grails.plugins.springsecurity.ldap.search.base = 'OU=people,OU=imApp,DC=example,DC=org'
grails.plugins.springsecurity.ldap.search.filter='uid={0}' //ad use sAMAccountName instead of uid
grails.plugins.springsecurity.ldap.search.searchSubtree =true
grails.plugins.springsecurity.ldap.auth.hideUserNotFoundExceptions= false
grails.plugins.springsecurity.ldap.search.derefLink = true
// specify this when you want to skip attempting to load from db and only use LDAP
grails.plugins.springsecurity.providerNames = ['ldapAuthProvider', 'anonymousAuthenticationProvider']
grails.plugins.springsecurity.conf.ldap.authorities.retrieveGroupRoles = false
grails.plugins.springsecurity.conf.ldap.authorities.retrieveDatabaseRoles = false
//grails.plugins.springsecurity.ldap.authorities.groupSearchBase = 'ou=groups,ou=imApp,dc=mcommunity,dc=org'
//role specific ldap config
grails.plugins.springsecurity.ldap.useRememberMe = false
I have tried a few variations of this config, for example it says Active Dir requires sAMAccountName as the search.filter but when I use this no accounts work, if i comment it out completely it works as already memntioned, admin logs in but no other account does. If I remove the springsecurity.providerNames the app starts but uses DB as password auth provider. I came across some blogs mentioned removing password for model class and db, or making it null-able which I tried but had no effect on outcome.
My Active Dir structure is as follows:
DC=example,dc=org
OU=imApp
OU=groups
OU=people
CN=admin user CN=admin,OU=people,OU=imApp,DC=example,DC=org
CN=user1 user CN=user1,OU=people,OU=imApp,DC=example,DC=org
CN=LostAndFound
CN= NTDS Quotas
CN=Roles
I have given each account a LDAP password, and added a parameter uid matching that of their username (CN). I have not used a Custom UserDetailsContextMapper, just default. However, I did try a Custom UserDetailsContextMapper and just came across the same issue, so reverted back to using just standard. Also I noticed Active Dir has a lower case dc for org so I tried using same lower case dc in Grails config but has same result.
Has anyone come across this issue or know where I may be going worng? Any help appreciated.
Best,
Marklw16
Try these settings:
grails.plugins.springsecurity.ldap.authorities.groupSearchBase ='DC=example,dc=org'
grails.plugins.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'

How do I set/get session vars in a Rack app?

use Rack::Session::Pool
...
session[:msg]="Hello Rack"
EDIT: The word session doesn't seem to resolve. I included the Session pool middleware in my config.ru, and try to set a variable in an ERB file (I'm using Ruby Serve) and it complains "undefined local variable or method `session'"
Thanks!
session is a method that is part of some web frameworks, for example Sinatra and Rails both have session methods. Plain rack applications don’t have a session method, unless you add one yourself.
The session hash is stored in the rack env hash under the key rack.session, so you can access it like this (assuming you’ve named the rack environment to your app env):
env['rack.session'][:msg]="Hello Rack"
Alternatively, you could use Rack’s built in request object, like this:
request = Rack::Request.new(env)
request.session[:msg]="Hello Rack"
You need to load rack::session module next probably cookie like here
http://rack.rubyforge.org/doc/classes/Rack/Session/Cookie.html
This like explains it with example.

Resources