How to read the cookie value in response in angularjs? - angularjs

I m sending a request to the server ,for that im getting RSA key ,along with that some cookie value will be sent to client side to set the session.But i dont know to read the cookie value to set the session?
Someone please help me...
Thanks in advance..

Reading cookie at side is quite simple. You can just read the cookie with the cookie name. Lets say you have set the cookie with some name lets say
testCookie
Then you fetch the cookie with the document method
let getCookie = function (cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i].trim();
if (c.indexOf(name) === 0) {
return c.indexOf(name);
}
}
}
So now to fetch the cookie, you can call getCookie('testCookie')
Hope this helps

Related

Helping me understand session api Gatling

I am new to gatling
I am trying to loop on json response, find the country code that I am looking for and take the id coressponding the that coutry code.
Sample algorithm:
list.foreach( value => { if (value.coutrycode == "PL") then store value.id })
on Gatling:
def getOffer() = {
exec(
http("GET /offer")
.get("/offer")
.check(status.is(Constant.httpOk))
.check((bodyString.exists),
jsonPath("$[*]").ofType[Map[String,Any]].findAll.saveAs("offerList")))
.foreach("${offerList}", "item"){
exec(session => {
val itemMap = session("item").as[Map[String,Any]]
val countryCodeId = itemMap("countryCode")
println("****" + countryCodeId)
// => print all the country code on the list
if (countryCodeId =="PL"){ // if statement condition
println("*************"+ itemMap("offerd")); // print the id eg : "23"
session.set("offerId", itemMap("offerId")); // set the id on the session
}
println("$$$$$$$$$$$$$$" + session("offerId")) // verify that th session contains the offerId but is not
session
})
}
}
When I try to print the session("offerId"), it's print "item" and not the offerId.
I looked on the documentation but I didn't understand the behaviour. Could you please explain it to me ?
It's all in the documentation.
Session instances are immutable!
Why is that so? Because Sessions are messages that are dealt with in a
multi-threaded concurrent way, so immutability is the best way to deal
with state without relying on synchronization and blocking.
A very common pitfall is to forget that set and setAll actually return
new instances.
val session: Session = ???
// wrong usage
session.set("foo", "FOO") // wrong: the result of this set call is just discarded
session.set("bar", "BAR")
// proper usage
session.set("foo", "FOO").set("bar", "BAR")
So what you want is:
val newSession =
if (countryCodeId =="PL"){ // if statement condition
println("*************"+ itemMap("offerd")); // print the id eg : "23"
session.set("offerId", itemMap("offerId")); // set the id on the session
} else {
session
}
// verify that the session contains the offerId
println("$$$$$$$$$$$$$$" + newSession("offerId").as[String])
newSession

Gatling how to store and load a value for a later request

I'd like to build a load test where the second request is fed from first response. The data extraction is done in a method because it is not only one line of code. My problem is storing the value (id) and load it later. How should the value be stored and loaded? I tried some different approaches, and I come up with this code. The documentation has not helped me.
object First {
val first = {
exec(http("first request")
.post("/graphql")
.headers(headers_0)
.body(RawFileBody("computerdatabase/recordedsimulation/first.json"))
.check(bodyString.saveAs("bodyResponse"))
)
.exec {
session =>
val response = session("bodyResponse").as[String]
session.set("Id", getRandomValueForKey("id", response))
session}
.pause(1)
}
}
object Second {
val second = {
exec(http("Second ${Id}")
.post("/graphql")
.headers(headers_0)
.body(RawFileBody("computerdatabase/recordedsimulation/second.json"))
)
.pause(1)
}
}
val user = scenario("User")
.exec(
First.first,
Second.second
)
setUp(user.inject(
atOnceUsers(1),
)).protocols(httpProtocol)
Your issue is that you're not using the Session properly.
From the documentation:
Warning
Session instances are immutable!
Why is that so? Because Sessions are messages that are dealt with in a multi-threaded concurrent way, so immutability is the best way to deal with state without relying on synchronization and blocking.
A very common pitfall is to forget that set and setAll actually return new instances.
This is exactly what you're doing:
exec { session =>
val response = session("bodyResponse").as[String]
session.set("Id", getRandomValueForKey("id", response))
session
}
It should be:
exec { session =>
val response = session("bodyResponse").as[String]
session.set("Id", getRandomValueForKey("id", response))
}

Using OAuth2 with service account on gdata in python

I want to use data.photos.service.PhotosService to push and pull photos from Picasa. I got a service key file XXXXXXXX-privatekey.p12 from Google console and am now trying to authenticate using said key with google.
The documentation for OAUTH2 using appengine has led me to believe that using the following would be of use:
f = file(settings.SITE_ROOT + '/aurora/' + settings.PRIVATE_KEY, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(settings.SERVICE_ACCOUNT_NAME, key, scope = 'http://picasaweb.google.com/data https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("oauth2", "v2", http=http)
user_info = None
try:
user_info = service.userinfo().get().execute()
# neither of these two methods work
#gd_client.SetOAuthInputParameters(signature_method = gdata.auth.OAuthSignatureMethod.RSA_SHA1, consumer_key = "asdfasdfasdf.apps.googleusercontent.com", rsa_key = key, two_legged_oauth = True, requestor_id = user_info.get('email'))
#gd_client.auth_token = gdata.gauth.TwoLeggedOAuthRsaToken(consumer_key = user_info.get('email'), rsa_private_key = key, requestor_id = user_info.get('email'))
except errors.HttpError, e:
logging.error('An error occurred: %s', e)
user_inf0 = {u'verified_email': True, u'id': u'1234', u'name': u'asdfasdfasdf#developer.gserviceaccount.com', u'email': u'asdfasdfasdf#developer.gserviceaccount.com'}
The issue is that either method 1 using SetOAuthInputParameters returns a invalid token, or method 2 returns a 403 restricted.
I am at my wits' end reading through mountains of code that all do regular 3 legged oauth when I really and truly do not want to do it that way. Any ideas/articles I haven't seen yet?
Use gdata.gauth.OAuth2TokenFromCredentials.
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = auth2token.authorize(gd_client)
OAuth2TokenFromCredentials is designed to help you use apiclient and gdata at the same time. Under the covers, it uses the credentials for making sure it has the auth information it needs to perform gdata calls.
Note, if you still get 403, it may be something else entirely. I was using a service account to access a user's data and was getting 403 because I hadn't spec'd the user properly in the SignedJwtAssertionCredentials call.
UPDATE: Here's the basic pattern I used:
from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials(
    "XXXXXXXXXXX#developer.gserviceaccount.com",
    open("keyfile").read(),
    scope=(
    "https://www.googleapis.com/auth/drive",
    "https://spreadsheets.google.com/feeds",
    "https://docs.google.com/feeds"
), # For example.
    sub="user#gmail.com"
)
http = httplib2.Http()
http = credentials.authorize(http) # Not needed? See comment below.
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = gdata.photos.service.PhotosService() # For example.
gd_client = auth2token.authorize(gd_client)
If you are using MFA on your google account, you need to use the consent screen authentication method. With Picassa API, it does not work as is, as the request API is slightly different.
import gdata.gauth
import os
import pickle
import gdata.photos.service
clientid='xxx' # https://console.developers.google.com/apis/credentials
clientsecret='xxx'
Scope='https://picasaweb.google.com/data/'
User_agent='myself'
def GetAuthToken():
if os.path.exists(".token"):
with open(".token") as f:
token = pickle.load(f)
else:
token = gdata.gauth.OAuth2Token(client_id=clientid,client_secret=clientsecret,scope=Scope,user_agent=User_agent)
print token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')
code = raw_input('What is the verification code? ').strip()
token.get_access_token(code)
with open(".token", 'w') as f:
pickle.dump(token, f)
return token
token = GetAuthToken()
gd_client = gdata.photos.service.PhotosService()
old_request = gd_client.request
def request(operation, url, data=None, headers=None):
headers = headers or {}
headers['Authorization'] = 'Bearer ' + token.access_token
return old_request(operation, url, data=data, headers=headers)
gd_client.request = request
photos = gd_client.GetUserFeed(kind='photo', limit='10')
for photo in photos.entry:
print 'Recently added photo title:', photo.title.text

in CakePHP I want to have 2 cookies as they need different expiry times...can I do this?

I have been trying like this -
// ================
// = set a Cookie for the users city =
// ================
function set($cityId = null){
$this->components[] = 'RequestHandler';
$this->components[] = 'Cookie';
$this->Cookie->name = 'Exampleoffers';
//$this->Cookie->time = 3600; // or '1 hour'
//$this->Cookie->path = '/bakers/preferences/';
$this->Cookie->domain = 'www.example.co.uk';
$this->Cookie->secure = false;
$this->Cookie->key = 'kkjdDqSI232qs*&sXOw!';
$cities = ($this->City->find('list'));
if($cities[$cityId]) {
$this->Cookie->write ("Deal.city_id", (int) $cityId, false, "+2 months");
} else {
$this->Cookie->write ("Deal.city_id", key($cities), false, "+2 months");
}
however, I am not sure if it is clashing with my Authsome cookie (?) or something else, but I am unable to read this value back.
Is there some way to specify which cookie you want to read() from in CakePHP?
Is there a way to have a cookie with 2 diffferent values of expiry times? - i.e. a cookie has User.id with a expiry of 1 week, and a Deal.city_id with a expiry of 2 months, say? Or am I right to think I DO need 2 cookies?
many thanks for any tips. It's cake 1.3 btw !
You can, remember cookies are saved on the system so if you only save the cookie one time on that system it will have the set values, however, you cannot have 2 cookies with the same name set, which means that when you go and save the cookies you'll have to do this:
$this->Cookie->write('Name1', $data, false, $time);
$this->Cookie->write('Name2', $data, false, $time);
If you don't, one will overwrite the other.
EDIT: Adding some links in case you have more doubts:
API page of CookieComponent: http://api13.cakephp.org/class/cookie-component
Cookbook page of CookieComponent: http://book.cakephp.org/view/1280/Cookies

oauth problem( app engine)

i am trying to pull user's documents data from google docs using oauth,
but i cannot understand how to do it
- what's the purpose of oauth_verifier
- how to get the access token secret?
- if i try to use DocsService below, then i have a "server error"
- is there a clear tutorial for this? i cannot find any atm..
String oauth_verifier = req.getParameter("oauth_verifier");
String oauth_token = req.getParameter("oauth_token");
String oauthtokensecret = req.getParameter("oauth_token_secret");
GoogleOAuthParameters oauthparam = new GoogleOAuthParameters();
oauthparam.setOAuthConsumerKey("consumer key");
oauthparam.setOAuthConsumerSecret("secret");
oauthparam.setOAuthToken(oauth_token);
oauthparam.setOAuthTokenSecret(oauthtokensecret);
oauthparam.setOAuthVerifier(oauth_verifier);
OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();
GoogleOAuthHelper oauthhelper = new GoogleOAuthHelper(signer);
String accesstoken = "";
String accesstokensecret = "";
try {
oauthhelper.getUnauthorizedRequestToken(oauthparam);
accesstoken = oauthhelper.getAccessToken(oauthparam);
accesstokensecret = oauthparam.getOAuthTokenSecret();
// DocsService client = new DocsService("yourCompany-YourAppName-v1");
...
These may not be what you are looking for, since they are OAuth-specific and not google-related, but I found these "Getting started" articles very helpful:
http://oauth.net/documentation/getting-started
Turns out that I need to get the oauth_token_secret and reuse it later.
So (before redirecting user to google login page)
oauthhelper.getUnauthorizedRequestToken(oauthparam);
requesturl = oauthhelper.createUserAuthorizationUrl(oauthparam);
OAuthTokenSecret.tokenSecret = oauthparam.getOAuthTokenSecret();
resp.sendRedirect(requesturl);
Then after the user grants access and we have been redirected to oauth_callback url:
oauthparam.setOAuthToken(oauthtoken);
oauthparam.setOAuthVerifier(oauthverifier);
oauthparam.setOAuthTokenSecret(OAuthTokenSecret.tokenSecret);
oauthhelper.getAccessToken(oauthparam); // access token and access token secret are saved in oauthparam.
// access google service..
GoogleService googleService = new GoogleService( "cp", "test222");
googleService.setOAuthCredentials(oauthparam, signer);
BaseFeed resultFeed = googleService.getFeed(feedUrl, Feed.class);

Resources