Sencha Touch 2 Session Storage - sencha-touch-2

I had created an ajax request in sencha touch 2, when i get a success message how can i set my return values to session and please also tell me a way through which i can get the value from session also.
submitLoginForm: function() {
var form = this.getLoginForm().getValues();
Ext.Ajax.request({
url: '../../authenticate.php',
method: 'POST',
params: {
email: form.email,
password: form.password
},
success: function(response) {
var json = Ext.decode(response.responseText);
if(json.message == 'success') {
Ext.Msg.alert('Login Success.....');
//Here i want to store return data in session
} else {
Ext.Msg.alert('Invalid Login Or Password.....');
}
},
failure: function(response) {
Ext.Msg.alert('The request failed.....');
}
});
},

on Success response, use HTML5 local storage to set and get the session variables:
var sessionObject = { 'var1': 1, 'var2': 2, 'var3': 3 };
// Put the session object into storage
localStorage.setItem('sessionObject ', JSON.stringify(sessionObject ));
// Retrieve the session object from storage
var sessionObject = localStorage.getItem('sessionObject ');
console.log('sessionObject : ', JSON.parse(sessionObject ));

Related

Hapi jwt extra auth check on owner id

I'm working on a project
using hapi-auth-jwt.
So when the user is logged
get this token
exports.getUserToken = function getUserToken(user) {
var userData = {
username: user.username,
scope: ['user'],
iss: apiConfig.iis,
jti: user.id
};
var token = {
token : Jwt.sign(userData, apiConfig.secret, { expiresInMinutes: apiConfig.expiresInMinutes})
};
return token;
};
and in the route
{
method: 'GET',
path: internals.resourcePath + '/{userId}',
config : {
handler : User.findById,
validate: Validator.findById,
auth: {
strategy: 'token',
scope: ['user']
}
}
},
but I've to do an other check like
(in controller for get one ,update and delete )
to see if the user is really the owner
var jti = request.auth.credentials.jti;
var id = +request.params.userId;
if( id !== jti ){
return reply( ReplyUtil.forbidden() );
}
var params =request.payload;
User.findOne
I'm wondering if there is a way to not to have
my code duplicated (sort of middleware in express)
Is it worth using a pre-hook like
server.ext('onPostAuth' , function(request, reply) {
if(request.auth && request.auth.credentials && request.auth.credentials.jti){
var jti = request.auth.credentials.jti;
var id = +request.params.userId;
if( id !== jti ){
return reply(Boom.forbidden());
}
}
return reply.continue();
});
First, in your validateFunc, add user's scope his/her id:
user.scope.push(user._id);
When you call callback function in validateFunc, don't forget to pass the user object as credentials. Then in your route, define scope something like this:
auth: {
strategy: 'token',
scope: ['admin', 'USER_ID']
}
Hope it helps.

Chrome, recognize open tab

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.

Invalidate session with custom authenticator

Using ember-cli 0.1.2 and ember-cli-simple-auth 0.7.0, I need to invalidate the session both on client and server. As explained here I need to do something similar to the authenticate method making an ajax request to the server and ensuring its success before emptying the session:
import Ember from 'ember';
import Base from "simple-auth/authenticators/base";
var CustomAuthenticator = Base.extend({
tokenEndpoint: 'http://127.0.0.1:3000/api/v1/auth/login',
restore: function(data) {
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'POST',
data: JSON.stringify({ email: credentials.identification, password: credentials.password }),
contentType: 'application/json'
}).then(function(response) {
Ember.run(function() {
resolve({ token: response.token });
});
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
},
invalidate: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'DELETE'
}).then(function(response) {
resolve();
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
}
// invalidate: function() {
// var _this = this;
// return new Ember.RSVP.Promise(function(resolve) {
// Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
// resolve();
// });
// });
// }
});
export default {
name : 'authentication',
before : 'simple-auth',
initialize : function(container) {
container.register('authenticator:custom', CustomAuthenticator);
}
};
My logout API endpoint need the token (in the headers). How do I pass it? I read this but my authorizer seems ignoring it and I got a 401:
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
var CustomAuthorizer = Base.extend({
authorize: function(jqXHR, requestOptions){
Ember.debug("AUTHORIZING!");
}
});
export default {
name : 'authorization',
before : 'simple-auth',
initialize : function(container) {
container.register('authorizer:custom', CustomAuthorizer);
}
};
My environment.js:
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'wishhhh',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
// TODO: disabled because of https://github.com/stefanpenner/ember-cli/issues/2174
ENV.contentSecurityPolicyHeader = 'Disabled-Content-Security-Policy'
ENV['simple-auth'] = {
authorizer: 'authorizer:custom',
// crossOriginWhitelist: ['http://localhost:3000']
crossOriginWhitelist: ['*']
}
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
The following is the Ember inspector output when, eventually, I try to logout:
Did you actually configure Ember Simple Auth to use your custom authorizer? In that case it should authorize the session invalidation request automatically.
Alternatively you could add the token in the authenticator's invalidate method which gets passed the session's contents.
Thanks to marcoow, I found out that it was actually a problem with every request not only the logout one. My authorizer never got called. Problem was environment setup of crossOriginWhitelist which, in order to work with my dev API, I had to set to ['http://127.0.0.1:3000']. Neither ['http://localhost:3000'] nor [*] worked.

Ajax request issue in sencha touch 2

I have a problem with sending an ajax request for the authentification..
i dont get errors but Network in chrome says : method : get , status : canceled , type : pending
and no response from this request ..
when i click on the file connection.js it point in this line :
// start the request!
xhr.send(requestOptions.data);
& my path name and the method get have the color RED
here is my code :
Ext.onReady(function() {
Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/',
method: 'GET',
useDefaultXhrHeader:false,
disableCaching: false,
timeout:120000,
params: {
client_id: 'xxxxxx',
client_secret: 'xxx',
format: 'json'
},
success: function(response) {
var resultat = Ext.JSON.decode(response.responseText);
//the response is : {"status":"ok","auth_token":"xxxxxxxxxxx"}
if (resultat.status === "ok") {
if (!resultat.access_token === "") {
access_token = resultat.access_token;
me.sessionToken = resultat.sessionToken;
}
else
{
new Ext.Ajax.request({
url: 'https://api.mysite.com/api/oauth/signin',
method: 'post',
params: {
username: username,
password: password,
authtoken: resultat.access_token,
format: 'json'
},
success: function(response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
}
},
failure: function(response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
}
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
} else {
//exception
}
}
,
failure: function(response) {
me.sessionToken = null;
Ext.Msg.alert('failed !!'); // its what it shows me
}
});

How to pass Client Side data to Server Side using Ember.js

I'm studying Ember.js myself and I'm stuck with a problem I'm creating a sample app and I need to send the client side values to Server Side but I dont know how to do that I know the traditional way like the below code
function create() {
var data = {
'EmailID': $('#emailid').val(),
'password': $('#password').val()
}
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data:data,
success: function (response) {
alert("hi");
}
});
return false;
}
but In Ember i dont Know How to do that my current code is given below
//Application
App = Em.Application.create();
//Model
App.Users = Em.Object.extend({
name: null,
password:null
});
//View
App.UserTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
App.PassTextField = Em.TextField.extend({
insertNew: function () {
App.alertController.alertDetails();
}
});
//controller
App.AlertController = Em.ObjectController.extend({
content: [],
username: '',
password: '',
alertDetails: function () {
var me = this;
var username = me.get("username");
var password = me.get("password");
alert('The User Name Is' + 'username' + 'And Password Is' + 'password');
}
});
App.alertController = App.AlertController.create();
I got the textbox values from alertDetails function and how can I pass them to server side
App.Record = Ember.Object.extend({
name: '',
other: ''
}).reopenClass({
records: [],
find: function() {
var self = this;
$.ajax({
url: "/api/records/",
type: "GET",
cache: false,
dataType: "json",
beforeSend: function() {
//if you want to call this often and need to clear + reload it
return self.records.clear();
},
success: function(results) {
var result;
for (_i = 0, _len = results.length; _i < _len; _i++) {
result = results[_i];
self.records.push(self.records.addObject(App.Record.create(result)));
}
},
error: function() {
return alert("error: failed to load the records");
}
});
return this.records;
}
});
Now that you have your model setup, you can call it from your route model hook
App.RecordsRoute = Ember.Route.extend({
model: function() {
return App.Record.find();
}
});
The find method returns an empty array right away, your template is then bound to it. When the ajax call returns w/ success and you update that array the handlebars template will update it for you w/out any DOM or jQuery glue code