How do I get access to rails session in the console? - ruby-on-rails

Say I have copied the string for a cookie from a browser request.
_some_session=RXF6SVF5RHdV...
I want to open the rails console and paste something like
> session[RXF6SVF5RHdV...]
To retrieve the decrypted data from the session. If this is possible, how do I do it?

Yes it is possible, here is more detailed way, open your rails console to try this:
content = 'BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTgwZGFiNzhiYWZmYTc3NjU1ZmVmMGUxM2EzYmEyMDhhBjsAVEkiFGdpdGh1Yl91c2VybmFtZQY7AEZJIhJuZWVyYWpkb3RuYW1lBjsARkkiEF9jc3JmX3Rva2VuBjsARkkiMU1KTCs2dXVnRFo2R2NTdG5Kb3E2dm5BclZYRGJGbjJ1TXZEU0swamxyWU09BjsARg%3D%3D--b5bcce534ceab56616d4a215246e9eb1fc9984a4'
assuming content is your session cookie,
When the content is written to cookie then it is escaped. So first we need to unescape it.
> unescaped_content = URI.unescape(content)
=> "BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTgwZGFiNzhiYWZmYTc3NjU1ZmVmMGUxM2EzYmEyMDhhBjsAVEkiFGdpdGh1Yl91c2VybmFtZQY7AEZJIhJuZWVyYWpkb3RuYW1lBjsARkkiEF9jc3JmX3Rva2VuBjsARkkiMU1KTCs2dXVnRFo2R2NTdG5Kb3E2dm5BclZYRGJGbjJ1TXZEU0swamxyWU09BjsARg==--b5bcce534ceab56616d4a215246e9eb1fc9984a4"
Notice that towards the end unescaped_content has -- . That is a separation marker. The value before -- is the real payload. The value after -- is digest of data.
> data, digest = unescaped_content.split('--')
=> ["BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTgwZGFiNzhiYWZmYTc3NjU1ZmVmMGUxM2EzYmEyMDhhBj VEkiFGdpdGh1Yl91c2VybmFtZQY7AEZJIhJuZWVyYWpkb3RuYW1lBjsARkkiEF9jc3JmX3Rva2VuBjsARkkiMU1KTCs2dXVnRFo2R
2NTdG5Kb3E2dm5BclZYRGJ
GbjJ1TXZEU0swamxyWU09BjsARg==", "b5bcce534ceab56616d4a215246e9eb1fc9984a4"]
The data is Base64 encoded. So let’s unecode it.
> Marshal.load(::Base64.decode64(data))
=> {"session_id"=>"80dab78baffa77655fef0e13a3ba208a",
"github_username"=>"manoj910",
"_csrf_token"=>"MJL+6uugDZ6GcStnJoq6vnArVXDbFn2uMvDSK0jlrYM="}
So we are able to get the data that is stored in cookie.

Here is an answer that works for non-cookie-based sessions too. I.e. normally all that you would save in the cookie is the session ID. Now given the session ID you can lookup the session data independently from the used session store (file, cache, ActiveRecord) like this:
def lookup_session_data(session_id)
session_store = Rails.application.config.session_store.new nil, {}
_id, data = session_store.find_session({}, Rack::Session::SessionId.new(session_id))
data if data.present?
end
session_id = "..."
lookup_session_data session_id

Related

Find the right URL(EndPoint) for creating a ServiceNow Change Request type = Emergency

I do not know the difference between these two end points:
a) /api/sn_chg_rest/v1/change/emergency
b) /api/now/table/change_request?sys_id=-1&sysparm_query=type=emergency
b) once submitted changes to "normal" response type
Issue: Unable to submit a request of type Emergency, Standard, OR Expedited.
Things I have Tried: url = 'https://xxxx.service-now.com/api/now/table/change_request?sys_id=-1&sysparm_query=type=expedited <<changes to normal, the site only allows edits into emergency or normal once submitted with this link>>
url = 'https://xxxx.service-now.com/api/sn_chg_rest/v1/change/emergency <<This one seems to be working only for emergency & normal, also the user is locked into emergency and normal even when logged in to edit type manually once submitted via script >>
Outcome of the current code below in conjuction with the "Things I have Tried" There is a CHG#XXX created but no matter what the Key:xxxxxx "sys-pram_query=type=xxxxxx" changes to (i.e. "Normal", "Expedited", "Emergency", "Standard") looks like this ---> ("sys-pram_query=type= Emergency","sys-pram_query=type= Expedited","sys-pram_query=type= Standard") the type on the ServiceNow-site defaults to "Normal" once the code below runs creating the request using the POST Method.
#Need to install requests package for python
#easy_install requests
import requests
# Set the request parameters
url = 'https://xxxx.service-now.com/api/now/table/change_request?sysparm_fields=type'
# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'
# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Do the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers ,data="{\"type\":\"Emergency\"}")
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)
Alternative Options for url THAT MAY NOT WORK = 'https://xxxx.service-now.com/api/now/table/"optionsA" OR "B" OR "C" is as follows:
A) POST /sn_chg_rest/change/standard/{standard_change_template_id}
B) POST api/sn_chg_rest/change/normal
C) POST Versioned URL /api/sn_chg_rest/{version}/change/emergency
link for A, B , C above : https://developer.servicenow.com/dev.do#!/reference/api/orlando/rest/change-management-api#changemgmt-POST-emerg-create-chng-req
Resources:
https://docs.servicenow.com/bundle/paris-it-service-management/page/product/change-management/task/t_AddNewChangeType.html
https://developer.servicenow.com/dev.do#!/reference/api/orlando/rest/change-management-api
API_URL="/api/sn_chg_rest/v1/change/emergency"
this Might have worked, going to confirm.
Yup this works ! unable to submit Standard OR Expedited. But that might be a setting that needs to be enabled (Not sure). Looking into it further. Some progress.

How to store encrypted data?

I'm new to ruby on rails, and I'm developing an application that will have very sensitive data (api keys from other websites) and I need to store it encrypted in a db but without knowing them at any time.
Let me explain myself:
The form asks the user for his api keys
Encrypt them
Store it in the db
The main question is, how do I encrypt them in such a way that I can use them later (still without knowing them)?
Sorry if the question is silly, but I can't find a way to do it, and thanks.
I've used attr_encrypted for this. Works great.
class User
attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'
end
You then work with ssn as if it were a plain field
user = User.find(1)
puts user.ssn
but it's encrypted at rest (in the database) and can't be retrieved without the key.
def encrypt text
text = text.to_s unless text.is_a? String
len = ActiveSupport::MessageEncryptor.key_len
salt = SecureRandom.hex len
key = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base).generate_key salt, len
crypt = ActiveSupport::MessageEncryptor.new key
encrypted_data = crypt.encrypt_and_sign text
"#{salt}$$#{encrypted_data}"
end
def decrypt text
salt, data = text.split "$$"
len = ActiveSupport::MessageEncryptor.key_len
key = ActiveSupport::KeyGenerator.new(Rails.application.secrets.secret_key_base).generate_key salt, len
crypt = ActiveSupport::MessageEncryptor.new key
crypt.decrypt_and_verify data
end
Pass the key to encrypt method and store the returned encrypted value in DB.
Then to decrypt pass the encrypted key to the decrypt method.
This is assuming your Secret Key Base is in Rails.application.secrets.secret_key_base
The original source for the answer is here

Rails - cookies value doesnt persist across actions

I am trying to save a data on cookies that can be used later.
def hello
name = SecureRandom.hex
cookies[:cookies_name] = name
.....
end
def process_file
logger.debug "The number of lines in specific is updr #{cookies[:cookies_name] }"
...
end
In action process_file, the value I stored in cookies is spaces (nil). Moreover, using developer tool when I am trying to see the cookies (Chrome -> developer tool -> resources), i cant see any cookies.
How do I set cookies?
Try setting expiry date for your cookie
cookies[:cookies_name] = {value: name, expires: 1.year.from_now}

How to store more than one values, in same cookie - Rails

So i want to store a comment_id:value pair and a comment_user:value pair
So far i do this
cookies.signed[:comment_author] = { value: #comment.id, expires: 2.hour.from_now }
Basically i am trying to figure out how to store more than one value to same cookie so to avoid creating multiple cookies for same user. Is that possible?
Question 2: how can i dynamically append to that cookie if any values exist?
The only way to do it using one cookie is to serialize the data into some textual format like YAML or JSON.
Example:
cookies.signed[:comment_data] = { value: {comment_id: 1, comment_user:2}.to_yaml, expires: 2.hour.from_now }
And to read it back just process the cookie value through: YAML.load
But you should remember that an individual cookies size is limited to 4K bytes (and actually even less, as signing the cookie increases the cookies value size), so you can't just put there as much data as you want. Thus, if all you need to store is some numbers you may store them in a more compact format e.g. [1, 2].to_json.
And on the second point: you can't really append anything to the cookie, but you can read whatever is stored in the cookie and merge it with the data you were going to append and then set the cookie again.
You can do something like this:
if cookies[:comment_data]
existing_data_string = cookies[:comment_data]
existing_data = YAML.load(existing_data_string)
else
existing_data = {...}
end
existing_data.update(comment_number: 1234)
cookies.signed[:comment_data] = { value: existing_data.to_yaml, expires: 2.hour.from_now }

Store cookie from HTTP header

How do you store a cookie with basic info.
i.e. link is http://www.domain.com/index.html?ref=123
How would I store a cookie with name of "ref" and the value of "123"?
see http://api.rubyonrails.org/classes/ActionController/Cookies.html
use following code in your controller:
cookies[:ref] = 123
or
cookies[:ref] = params[:ref]

Resources