ZF2 How to get unloaded config file in controller? - zend-framework2

The cenario
My application is divided by many agencies, each one with it's own database and database configuration file.
Before logging in, the user needs to send me an agency-id. In that request ZF2 load a non-agency db configutarion file (with SQLite database info) to validate if agency-id really exists.
The next requests are made to agency-specific-url so ZF2 load that agency's specific db configutarion file.
The problem
In the first request (to validate agency-id) after I validate it, I need to load the agency's specific database to fetch some info and return it.
I was thinking of loading that "unloaded agency database config file" in my controller, to instantiate a model with a DbAdapter containing the agency's database info for that, but I can't find a way to do it.
How can I do this or is there another way? Perhaps I should load every agency config file before ZF2's init but I don't know if that's the best solution.

To solve this I created an action that will return the agency's info.
Inside the agency-id validate action, create a request for the above action and get it's response:
// Create request to get agency's info
$client = new Client();
$request = new Request();
$request->setMethod(Request::METHOD_GET);
$explicitUrl = 'http://example.com/any/action';
$request->setUri($explicitUrl);
$response = $client->send($request);
// The any/action route points to an action that return JSON data
$json = JsonDecoder::decode($response->getBody());
// Now I can do whatenever I want
$json->variable1...
$json->variable2...
$json->variable3...

Related

Pass id to new create form (but not through URL) - rails

I used the following advice to set up new_invoice_path in my app:
https://stackoverflow.com/a/14570788
How can I (using the outlined scenario in the question/answer I linked to above) make it so that when a user clicks a link to create a new invoice for a specific account the account_id passes to the form but does not show up in the URL?
I view the current solution (pass account_id to form via URL) as problematic because...
Someone could easily modify the URL and start creating invoices in different accounts.
It looks sloppy (especially if you start trying to pass things other than just account_id)

How to make a rails server wide object?

I am using the RedditKit gem and in order to access certain elements, I need to send a request to reddit api to create a "client" object. Below is my current logic:
## application_controller
before_action :redditkit_login
private
def redditkit_login
#client = RedditKit::Client.new ENV["reddit_username"], ENV["reddit_password"]
end
As you can see in my logic here, before EVERY REQUEST, I am subsequently making a new client object and then using that everywhere.
My question is, how do I only make one client object which can be used to serve ALL requests from anywhere?
My motive behind this is speed. For every request to server, I am making a new request to reddit and then responding to the original request. I want to have the client object readily available at all times.
You have a lot of options. A simple one would be to create a config/initializers/reddit_client.rb file and put in there:
RedditClient = RedditKit::Client.new ENV.fetch("reddit_username"), ENV("reddit_password")
(note I switched to ENV.fetch because it will error if the key is not found, which can be helpful).
You could also rename the file as app/models/reddit_client.rb. Although it's not really a model, that folder is also autoloaded so it should work as well.

Prevent an URL from being discovered

Recently I've created a controller, which will do some insert into my database whenever I access the url.
My route config for it :
routes.MapRoute(
"SCRoute",
"SC/{pdate}",
new
{
controller = "SC",
action = "Index",
pdate = DateTime.Today.Date.ToString("yyyyMMdd")
});
My question is if I don't expose this url, will it be detected? Of course since there is no credential log-in, anyone with the link can access the page, but if I can keep it for my self, will it be safe?
There will be no internal links to this controller also. It won't be mentioned anywhere except in my mind and the route config!
but if I can keep it for my self
Its not safe, no matter how you hide it. You can accidently execute this URL or other developer can do that while understanding the code. Lots of things can take place to get it run.
If you want to insert something in DB, why don't you create a script and execute it. It would be a controlled change in any environment.
UPDATE - After comment from user
You can work out a solution on following lines:
Define an action filter.
Check for a unique value in the URL e.g. IP Address (Example) or write an algorithm to generate a hash.
When you want to run the action from anywhere, generate the hash and supply in the URL. The defined filter will verify the hash validity. A request with valid hash will only be served.
Hope this help.

Adding User-Agent & IP to a stored Session -RecordNotSaved -Rails

I'm currently building an in-house analytics system which tracks where a visitor clicks throughout each session, whether they are logged into a User account or are a visitor without an account.
I am currently saving my sessions to the database thanks to changes made through sessions_store.rb, however in addition to the session_id, I am trying to figure out how to add both UserAgent details and a visitor's IP to the sessions table.
I've tried a couple solutions but all have failed - my current solution appears to be the closest, however I keep encountering an ActiveRecord::RecordNotSaved error after updating the Session's attributes.
I am currently using a before filter in application controller:
before_filter :set_useragent_and_ip_in_session
def set_useragent_and_ip_in_session
if session
sess = request.session_options[:id]
#session = Session.where(session_id: sess).first
#session.update_attributes(:ip=>request.remote_ip, :user_agent=>request.user_agent)
#session.save!
else
end
end
I've inserted a debugging statement in my views and have played around the code in pry - the #session is valid and displays the #session.user_agent properly .... however when saving to the DB it justs rollsback.
When I use save!, I receive a Completed 422 Unprocessable Entity in the logs in addition to the following (pasted to gist to conserve space):
https://gist.github.com/anonymous/8019c2426334f395a5fd
Thanks! Any help would be very appreciated.
I would recommend rethinking your schema. A session can last many requests and you want a record per request. Also notice how your moving data off the request object and trying to store them into a session table. Instead make your very own request table and make a before filter that moves all the data you want from the request object to the request table. Now a session will have many requests.
I'm not sure why your record isn't saving however I would wager naming a model Session is conflicting with rails. By that same token when you make your request table you should give it a unique name like maybe SessionMeta and RequestMeta. Then SessionMeta could have many RequestMeta.

accessing user credentials/permissions

Is there an easy way to get a credential/permission for a particular user?
I've seen the hasCredential() method, but I'd like to dynamically check any user, not just the current user.
I know I can use sfContext::getInstance()->getUser(); to get the current user object, but is there a way to load in any user and get his/her credentials?
Thanks
It kind of depends on the "store" you're using. In Symfony the current user (the one provided with sfContext::getInstance()->getUser()) is more an abstraction of the session.
So the most used plugin for authentication, sfDoctrineGuard, has controllers (sfGuardAuth) which handle things like a a signin form, and once succesful, it will populate the sfUser accordingly.
So, if you want to check for the permissions of a user, you will have to check the underlying store. If you're using sfDoctrineGuard, you can retrieve a User model through sfGuardUserTable::getInstance()->find(...). On the sfGuardUser, you can call the hasPermission($name) function to check.
If you are using sfGuardPlugin or sfDoctrineGuardPlugin you can get all user permissions by calling getAllPermissions() inside actions with:
$this->getUser()->getGuardUser()->getAllPermissions();
or inside models with:
sfContext::getInstance()->getUser()->getGuardUser()->getAllPermissions();
either way you have to call getGuardUser.
if you are using the sfGuardPlugin, you have the sf_guard_user, sf_guard_permission and sf_guard_group tables in your databse. So you can query that tables to obtain the permission of an specific user doing something like:
$c = new Criteria();
$c->add('username',$specificName);
$userPeer = new sfGuardUserPeer();
$user = $userPeer->doSelect($c);
$credentials = $user->getPermissions();
that way in $credentials you'll have an array of all the permissions (permissions are the credentials in sfGuardPlugin) of the selected user.
Good luck

Resources