Save data in localstorage of browers in ember simple auth - javascript

I have used ember-simple-auth for fb login.I am able fetch the fb's access_token and sending the token to my server for exchange of server token.This works fine and and I am able to make my transition to user feed page.But the problem I am facing is for the first time user.I have to show them some onboarding screen before taking them to their feed screen.And from next time I can skip the onboarding process for them.
torii.js
export default Torii.extend({
torii: service('torii'),
authenticate() {
return new RSVP.Promise((resolve, reject) => {
this._super(...arguments).then((data) => {
console.log(data.accessToken);
raw({
url: 'http://example.co.in/api/socialsignup/',
type: 'POST',
dataType: 'json',
data: { 'access_token':data.accessToken,'provider':'facebook'}
}).then((response) => {
console.log(response.token);
resolve({
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
access_token: response.token,
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
provider: data.provider
});
}, reject);
}, reject);
});
}
});
The response for I am getting from my server is something like this.
For First Time User.
{access_token:'abcd...',signup_done:false}
When Signup_done is false I have to show user the onboarding screen and the make a POST request to server "http://example.co.in/api/post/signupdone"
For normal user
{access_token:'abcd...',singup_done:true}
This time I have to just move the user to thier the feed screen skipping the onboarding screen.
I want to save the singup_done from server to my cookie or brower local storage ( not sure ).So that I can use this value in my handlebars,controller,model,component.I am also open to other suggestion to achieve this with simple method.Please use code to example.Thanks in advance.

You can save data in the session's data by just setting it:
this.get('session').set('data.signupDone', true);
That way signupDone will be persisted (also when the session is invalidated). Of course if the user logs in in another browser that data won't be present anymore so you should probably store the property in a resource on the server side instead.

Related

Sveltekit Todos Example... Where is the data being stored?

I'm learning how SvelteKit works. There is a pretty nice "hello world PLUS" place to start with the "create-svelte" example. In that example there is a "todos" page. Source files here. It's a simple page where you can add an delete things to do tasks. And I'm trying to figure out how the individual tasks are managed.
I can see where an todos array is created in Javascript on the client; I can verify that via console.logs in index.svelte file. I can see via Chrome Inspect (dev tools, network tab) where the creation of a task generates a todos.json network Post request http://localhost:3000/todos.json The get/post request simply returns the original content back to the client.
What I'm not seeing is where the data is being stored on the browser. I was fully expecting to see something in local storage, session storage, cookies or even indexeddb.
What I'm not seeing is where that content is being stored. If I close the browser tab and reopen, the data is there. If I open a different browser on the same local computer, no task data exists. If I "empty cache and hard reload" the task data remains.
After doing some testing, I can see one cookie.
Name: userid Value: d38b9b44-1a8b-414e-9a85-1c2b2c0700f4 Domain: localhost Path: / Expires/MaxAge: Session Size: 42 HttpOnly: ✓ Priority: Medium
If I modify or delete this cookie in any way then the stored task data disappears.
So where is the todos task data being temporarily stored? What am I not seeing?
I read the header for this file _api.js multiple times. I tested "https://api.svelte.dev" in the browser and got back null responses.. I just assumed that this was a dead server.
It turns out that the folks at svelte do offer a fully functional api server, both receiving, deleting and storing todo task data. See my test notes within api function.
A browser request to https://api.svelte.dev/todos/d38b9b44-1a8b-414e-9a85-1c2b2c0700f4 absolutely returns my task data, and now I can see how this stuff works. Info offered here in case anybody else is wondering what's going on here.
Here is the complete _api.js file
/*
This module is used by the /todos.json and /todos/[uid].json
endpoints to make calls to api.svelte.dev, which stores todos
for each user. The leading underscore indicates that this is
a private module, _not_ an endpoint — visiting /todos/_api
will net you a 404 response.
(The data on the todo app will expire periodically; no
guarantees are made. Don't use it to organise your life.)
*/
const base = 'https://api.svelte.dev';
export async function api(request, resource, data) {
console.log("resource: ", resource);
// returns--> resource: todos/d38b9b44-1a8b-414e-9a85-1c2b2c0700f4
//https://api.svelte.dev/todos/d38b9b44-1a8b-414e-9a85-1c2b2c0700f4 <--- test this !!
// user must have a cookie set
if (!request.locals.userid) {
return { status: 401 };
}
const res = await fetch(`${base}/${resource}`, {
method: request.method,
headers: {
'content-type': 'application/json'
},
body: data && JSON.stringify(data)
});
// if the request came from a <form> submission, the browser's default
// behaviour is to show the URL corresponding to the form's "action"
// attribute. in those cases, we want to redirect them back to the
// /todos page, rather than showing the response
if (res.ok && request.method !== 'GET' && request.headers.accept !== 'application/json') {
return {
status: 303,
headers: {
location: '/todos'
}
};
}
return {
status: res.status,
body: await res.json()
};
}

How can access google calendar of user and edit it without asking for user permisssion again and again

On my website, I am asking for google calendar access. I can edit the user calendar but, I don't want to ask for user permission, again and again, so once the user authorized and give access to google calendar, I can edit it anytime until the user revokes the access. Should I implement it on the frontend or the backend and how? I checked few answers where they mention we can use a service account but, it is not clear how can I edit or read the individual user's calendar events and how can I remove it once the user revokes access. This question was deleted because code was missing so adding code below.
I tried this so once user login I get access token and I am using it
window.gapi.load("client:auth2", () => {
window.gapi.client.setApiKey("api_key");
window.gapi.client.load("https://content.googleapis.com/discovery/v1/apis/calendar/v3/rest")
.then(() => {
window.gapi.auth.setToken({ access_token: access_token })
window.gapi.client.calendar.events.insert({
"calendarId": "id",
'resource': event
}).then((res) => {
console.log("calendar data res "+JSON.stringify(res))
}).catch(err => console.log("error getting calendar data "+JSON.stringify(err)))
}).catch(err => console.error("Error loading GAPI client for API", err) )
})
but once access token expires how can I get a new access token( I don't want to show login popup to the user again and again. I want to know how can I do it using refresh token on client-side).
You can't get a refresh token on the client-side without exposing your secret key to the public.
You can create an endpoint that accepts oAuth code and return the token, save the refresh token for later. You set up a corn job that checks for expired token and refreshes them.
Every time the user accesses your app, you grab a fresh token from the server and proceed to work normally.
As per Google guidelines. You do POST to https://oauth2.googleapis.com/token. Assuming your server-side stack is in Node.js, you do something like this using an HTTP client like Axios:
const Axios = require('axios');
const Qs = require('querystring');
const GOOGLE_CLIENT_ID = 'abc';
const GOOGLE_CLIENT_SECRET = '123';
let refreshToken = getFromDataBase(); // should be stored in database
Axios.post('https://oauth2.googleapis.com/token', Qs.stringify({
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
refresh_token: refreshToken,
grant_type: 'refresh_token'
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
})
.then(({ data }) => console.log(data.access_token)) // new token that expires in ~1 hour
.catch(console.log)
Firstly, do you (a) want to update the calendar when the user is not logged in, for example in response to an external event? ... OR ... do you (b) only want to update the calendar from within a browser session?
If (a), then you need to ask the user for offline access which will give you a Refresh Token , which you can securely store on a server and use whenever you need to. (Forget all about Service Accounts).
If (b), then you need the following pieces of information :-
When the access token expires, request access again, but add the flag prompt=none. This will give you a fresh Access Token without the user seeing any UX.
Do this in a hidden iframe so that it is happening in the background and is invisible to the user. Your iframe will therefore always have an up to date Access Token which it can share with your app via localStorage or postMessage.

How to open POST url in device browser from React native application

I have a shopping website where user can add items to the user's cart. But in the checkout process, I want the user to navigate in my website with the user's cart token. I want to open URL in Device browser from the react-native application with post data.
There's a library called Linking you could use.
You can open the url like so:
Linking.openURL('<insert-url-here');
This will open the URL in the default browser.
According to Linking documentation, you can't pass any POST data with the url. You can only send POST data with fetch. You will have to find another way for this to work.
You could definitely just send your token with GET data:
Linking.openURL('https://yoururl.com/?cart_token=[token]');
If you want to check if any installed app can handle a given URL
beforehand you can call:
Linking.canOpenURL(url)
.then((supported) => {
if (!supported) {
console.log("Can't handle url: " + url);
} else {
return Linking.openURL(url);
}
})
.catch((err) => console.error('An error occurred', err));
https://facebook.github.io/react-native/docs/linking#opening-external-links

serviceworker is it possible to add headers to url request

I have a website which I don't want to make people create accounts. It is a news feed with each news article categorized. I want to allow people to tag the categories they are interested in so that next time they go to the site it only shows news for the categories that are tagged.
I'm saving the tags in an indexedDB which I understand is available in a service worker.
Hence in my service worker I want to "intercept" requests to www.my-url.com, check the indexDB for what categories this person is interested in, and add some headers like 'x-my-customer-header': 'technology,physics,sports' so that my server can respond with a dynamic html of those categories only.
However I'm struggling to get the service worker to properly cache my root response. In my serviceworker.js, I console log every event.request for the onFetch handler. There are no requests that are related to my root url. I'm testing right now on my localhost, but I only see fetch requests to css & js files.
Here is my onFetch:
function onFetch(event) {
console.log('onFetch',event.request.url);
event.request.headers["X-my-custom-header"] = "technology,sports";
event.respondWith(
// try to return untouched request from network first
fetch(event.request).catch(function() {
// if it fails, try to return request from the cache
caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// if not found in cache, return default offline content for navigate requests
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
return caches.match('/offline.html');
}
})
})
);
}
I'm using rails so there is no index.html that exists to be cached, when a user hits my url, the page is dynamically served from my news#controller.
I'm actually using the gem serviceworker-rails
What am I doing wrong? How can I have my service worker save a root file and intercept the request to add headers? Is this even possible?
Credit here goes to Jeff Posnick for his answer on constructing a new Request. You'll need to respond with a fetch that creates a new Request to which you can add headers:
self.addEventListener('fetch', event => {
event.respondWith(customHeaderRequestFetch(event))
})
function customHeaderRequestFetch(event) {
// decide for yourself which values you provide to mode and credentials
// Copy existing headers
const headers = new Headers(event.request.headers);
// Set a new header
headers.set('x-my-custom-header', 'The Most Amazing Header Ever');
// Delete a header
headers.delete('x-request');
const newRequest = new Request(event.request, {
mode: 'cors',
credentials: 'omit',
headers: headers
})
return fetch(newRequest)
}

backbone.js - handling if a user is logged in or not

Firstly, should the static page that is served for the app be the login page?
Secondly, my server side code is fine (it won't give any data that the user shouldn't be able to see). But how do I make my app know that if the user is not logged in, to go back to a login form?
I use the session concept to control user login state.
I have a SessionModel and SessionCollection like this:
SessionModel = Backbone.Model.extend({
defaults: {
sessionId: "",
userName: "",
password: "",
userId: ""
},
isAuthorized: function(){
return Boolean(this.get("sessionId"));
}
});
On app start, I initialize a globally available variable, activeSession. At start this session is unauthorized and any views binding to this model instance can render accordingly. On login attempt, I first logout by invalidating the session.
logout = function(){
window.activeSession.id = "";
window.activeSession.clear();
}
This will trigger any views that listen to the activeSession and will put my mainView into login mode where it will put up a login prompt. I then get the userName and password from the user and set them on the activeSession like this:
login = function(userName, password){
window.activeSession.set(
{
userName: userName,
password: password
},{
silent:true
}
);
window.activeSession.save();
}
This will trigger an update to the server through backbone.sync. On the server, I have the session resource POST action setup so that it checks the userName and password. If valid, it fills out the user details on the session, sets a unique session id and removes the password and then sends back the result.
My backbone.sync is then setup to add the sessionId of window.activeSession to any outgoing request to the server. If the session Id is invalid on the server, it sends back an HTTP 401, which triggers a logout(), leading to the showing of the login prompt.
We're not quite done implementing this yet, so there may be errors in the logic, but basically, this is how we approach it. Also, the above code is not our actual code, as it contains a little more handling logic, but it's the gist of it.
I have a backend call that my client-side code that my static page (index.php) makes to check whether the current user is logged in. Let's say you have a backend call at api/auth/logged_in which returns HTTP status code 200 if the user is logged in or 400 otherwise (using cookie-based sessions):
appController.checkUser(function(isLoggedIn){
if(!isLoggedIn) {
window.location.hash = "login";
}
Backbone.history.start();
});
...
window.AppController = Backbone.Controller.extend({
checkUser: function(callback) {
var that = this;
$.ajax("api/auth/logged_in", {
type: "GET",
dataType: "json",
success: function() {
return callback(true);
},
error: function() {
return callback(false);
}
});
}
});
Here is a very good tutorial for it http://clintberry.com/2012/backbone-js-apps-authentication-tutorial/
I think you should not only control the html display but also control the display data. Because user can use firefox to change your javascript code.
For detail, you should give user a token after he log in and every time he or she visit your component in page such as data grid or tree or something like that, the page must fetch these data (maybe in json) from your webservice, and the webservice will check this token, if the token is incorrect or past due you shouldn't give user data instead you should give a error message. So that user can't crack your security even if he or she use firebug to change js code.
That might be help to you.
I think you should do this server sided only... There are many chances of getting it hacked unit and unless you have some sort of amazing api responding to it

Categories

Resources