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}
Related
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 do I automatically sign out when the user closes the browser ? Is there any configuration changes in clearance gem that would enable this.
Create A Cookie - Create or set a cookie on user machine having cookie
name, cookie value and the time when cookie should get deleted
automatically (EXPIRES atribute, this is optional). If this is not
specified the cookie is called a session cookie and it expires (gets
deleted) when user's session ends, i.e. when the browser is closed
Source
In other words, if you don't set an expiration date on a cookie, it should "expire" when the browser is closed.
I've never used Clearance, but the ReadMe shows this configuration option in /config/initializers/clearance.rb:
Clearance.configure do |config|
config.allow_sign_up = true
config.cookie_domain = ".example.com"
config.cookie_expiration = lambda { |cookies| 1.year.from_now.utc }
config.cookie_name = "remember_token"
config.cookie_path = "/"
config.routes = true
config.httponly = false
config.mailer_sender = "reply#example.com"
config.password_strategy = Clearance::PasswordStrategies::BCrypt
config.redirect_url = "/"
config.rotate_csrf_on_sign_in = false
config.secure_cookie = false
config.sign_in_guards = []
config.user_model = User
end
If I were you, I'd attempt to set the cookie_expiration to nil. However, if it requires an expiration, you might want to fork the gem and see if the private API here can be altered to your needs.
If you don't want to do that, you can create a guard in Clearance. When a user signs in, set your own cookie with no expiry date. When the user closes the browser, that should delete your custom cookie. Then, in your guard, when the authentication occurs again, you should be able to check for your custom cookie and (upon not finding it) reject the auth and redirect to sign_in.
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
I'm building an app using Dailymotion API
https://developer.dailymotion.com/
with official python sdk
https://github.com/dailymotion/dailymotion-sdk-python
and writing video CRUD(Create, Read, Update, Delete) simply.
Create, Read, Delete were succeccfully completed, but encountering a weird response of the API about "Update".
Here is a simplified snippet of my code in my Django project,
def update(request, video_id):
user = request.user
video = get_object_or_404(Video, pk=video_id)
file_path = # define file_path from uploaded file object
input_title = # define input_title from post request
input_description = # define input_description from post request
d = get_dailymotion_d(user)
if d == 'revoked':
# do actions of logout and delete the user
try:
# get url for upload with the file_path on my server
url = d.upload(file_path)
# update
response = d.post('/video/' + video.dailymotion_video_id, {'url': url, 'title': input_title, 'description': input_description, 'published': 'true', 'channel': 'creation'})
# delete the video from my sever
video.file_field.delete()
return redirect('/videos')
except Exception as e:
print(e.args)
print('update failed..!')
# delete the video from my server
video.file_field.delete()
return redirect('/videos')
def get_dailymotion_d(user):
d = dailymotion.Dailymotion()
d.set_grant_type('token', api_key=settings.DAILYMOTION_API_KEY, api_secret=settings.DAILYMOTION_API_SECRET, scope=['email', 'userinfo', 'manage_videos'], info={'redirect_uri': settings.DAILYMOTION_REDIRECT_URI})
# get credentiaols from database
access_token = user.dailymotionuser.access_token
expires = user.dailymotionuser.expires
refresh_token = user.dailymotionuser.refresh_token
session_params = {'access_token': access_token, 'expires': expires, 'refresh_token': refresh_token}
# set the credentials
d._session_store.set(session_params)
# check if the user revoked or not
try:
force_refreshed_access_token = d.get_access_token(force_refresh=True)
except dailymotion.DailymotionAuthError as e:
print(e.args[0])
return 'revoked'
# get valid access token
valid_access_token = d.get_access_token()
# update database with the valid access token
DailymotionUser.objects.filter(user=user).update(access_token=valid_access_token, expires=expires, refresh_token=refresh_token)
# prepare dic of the valid access token
valid_access_token_dic = {'access_token': valid_access_token}
# set the valid access token
d._session_store.set(valid_access_token_dic)
return d
but the update fails except title field with the following message,
'access_forbidden: You are not allowed to change existing video source.'
from doc,
access_forbidden: Thrown when the user doesn't have the permission to access the data (e.g. missing a required scope to access certain fields).
but I'm sure that the permission has manage_videos scope which is an enough scope to update the existing video source because the doc says,
manage_videos: Allows to modify or delete the user's uploaded videos and to publish new ones.
and described above,
Only the title field of the video is updated with the input_title properly.
Thanks for reading, I researched their docs carefully, but still don't understand this response.
Only partner users can update the video source urls.
Best,
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]