how to get data from local google Auth? - authentication

I am facing a problem in findding a login data of user and user is logedin to my site using google auth platform and i want to get that login data and store data in my local storage and I am working on Angular 14
Kindly help if any one know the soluiton of this problem
Thanks
I had searched a lot but not find a convieniet solution

It's work for me in this way.
According to the new documentation of Google (https://developers.google.com/identity/gsi/web/guides/overview), you should follow next steps:
Create a google app in google cloud console platform and generate a client id.
Load the client library. Add this script "<script src="https://accounts.google.com/gsi/client" async defer>" between the <head></head> tags of your index.html file of Angular project.
Add this code on ngOnInit() function in the component that you would like to have "Sign in with Google button."
ngOnInit() {
// #ts-ignore
google.accounts.id.initialize({
client_id: "YOUR GOOGLE CLIENT ID",
callback: this.handleCredentialResponse.bind(this),
auto_select: false,
cancel_on_tap_outside: true,
});
// #ts-ignore
google.accounts.id.renderButton(
// #ts-ignore
document.getElementById("google-button"),
{ theme: "outline", size: "large", width: "100%" }
);
// #ts-ignore
google.accounts.id.prompt((notification: PromptMomentNotification) => {});
}
async handleCredentialResponse(response: any) {
// Here will be your response from Google.
console.log(response);
}
Add div or button element to the html file of this component, with the same id that you mentioned into the initialization. ( "google-button" ):
<div class="" id="google-button"></div>.
Let me know if you have any issues.

Related

Why Vercel Web vitals is not loading for my Astro Project?

I created a landing page using Astro with Tailwind CSS. And it is currently hosted on Vercel. I wanted to try out the analytics service provided by Vercel. I have been able to avail the Audience analytics service provided by Vercel. However, I cannot avail the web vitals services. After enabling the service and redeploying my project, I am stuck in this screen (screen shot provided).
Please note that I did turn off the ad blocker but that did not resolve the issue.I also added the following meta tag to resolve any CSP issue
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' vitals.vercel-insights.com"/>
But that has not solved the problem.That is why I want to know does Vercel support analytics for Astro projects and if they do, then what am I doing wrong? Thank you.
Vercel’s Web Vitals analytics currently only has out-of-the-box support for Next, Nuxt, and Gatsby.
To track Web Vitals with a different framework like Astro, you need a bit of manual set up work as documented in Vercel’s Web Vitals API docs.
For example in your base Astro layout you could include a script tag that will import their example code and run it:
---
// src/layouts/BaseLayout.astro
---
<script>
import { webVitals } from '../scripts/vitals';
const analyticsId = import.meta.env.PUBLIC_VERCEL_ANALYTICS_ID;
webVitals({
path: window.location.pathname,
analyticsId,
});
</script>
Here’s Vercel’s example vitals.js snippet:
// src/scripts/vitals.js
import { getCLS, getFCP, getFID, getLCP, getTTFB } from 'web-vitals';
const vitalsUrl = 'https://vitals.vercel-analytics.com/v1/vitals';
function getConnectionSpeed() {
return 'connection' in navigator &&
navigator['connection'] &&
'effectiveType' in navigator['connection']
? navigator['connection']['effectiveType']
: '';
}
function sendToAnalytics(metric, options) {
const body = {
dsn: options.analyticsId, // qPgJqYH9LQX5o31Ormk8iWhCxZO
id: metric.id, // v2-1653884975443-1839479248192
page: options.path, // /blog/my-test
href: location.href, // https://my-app.vercel.app/blog/my-test
event_name: metric.name, // TTFB
value: metric.value.toString(), // 60.20000000298023
speed: getConnectionSpeed(), // 4g
};
if (options.debug) {
console.log('[Analytics]', metric.name, JSON.stringify(body, null, 2));
}
const blob = new Blob([new URLSearchParams(body).toString()], {
// This content type is necessary for `sendBeacon`
type: 'application/x-www-form-urlencoded',
});
if (navigator.sendBeacon) {
navigator.sendBeacon(vitalsUrl, blob);
} else
fetch(vitalsUrl, {
body: blob,
method: 'POST',
credentials: 'omit',
keepalive: true,
});
}
export function webVitals(options) {
try {
getFID((metric) => sendToAnalytics(metric, options));
getTTFB((metric) => sendToAnalytics(metric, options));
getLCP((metric) => sendToAnalytics(metric, options));
getCLS((metric) => sendToAnalytics(metric, options));
getFCP((metric) => sendToAnalytics(metric, options));
} catch (err) {
console.error('[Analytics]', err);
}
}
For a slightly more real-world implementation you, check out the <TrackVitals> Astro component in the astro-badge repo.
Vercel analytics has support for frameworks other than Next, Nuxt Gatsby etc. The way to achieve it in Astro (1.6, 2.0 etc.) is to install the #vercel/analytics package and inject a simple <script> tag that imports it and calls its exported function inject():
<script>
import { inject } from '#vercel/analytics'
// #ts-ignore: process.env.NODE_ENV is required by #vercel/analytics internally
// so that it can determine the correct path for importing the analytics script
globalThis.process = { env: { NODE_ENV: import.meta.env.MODE } }
inject()
</script>
You can inject this code in your <head> section in any .astro template file.
Unfortunately, the package is expecting a non-ESM runtime environment and is internally conditionally checking for process.env.NODE_ENV to determine which script to load (local-relative path to JS or from a remote host, fully qualified domain name). This is the reason, the MODE needs to be exposed as process.env.NODE_ENV. I tried to achieve this via Vite using define, but Astro seems to check for process somewhere else internally and fails.

Shopify node backend- frontend communication

I am really new in shopify app development.
I have an allready a working app what i have created with next.JS (I have worked with node/express too)
I just would like to create a connection between my frontend and backend with a simple endpoint.
It means i send a get request and i receive something nonsense. The main goal would be that is the backend can communicate with the frontend.
I have created a git repo too.: https://github.com/akospaska/shopify-outofthebox
The app has been created with shopify-cli
In my pages folder there is an index.js file, where my frontend "lives". 
I have created (or i think ) 2 differend endpoints.
pages/api/test   endpoint: "/test"
server/server.js  endpoint: "/test2"
When i call the endpoints i get an error. 
I have read the documentation but it just makes me confused.
How should i authenticate between my backend and frontend exactly?
Thank you for your help Guys in advance.
The endpoints aren't pages, they are routes on your express app.
Here is a related question with answer:
Node backend communication between react frontend and node backend | Shopify related
Here is a checklist for you how to set up an endpoint (POST):
1.) Navigate to your index.js file in the /web directory
2.) Insert this code:
app.post("/api/test", async (req, res) => {
try {
res.status(201).send(response);
} catch (error) {
res.status(500).send(error.message);
}
});
}
app.post() sets up a route in your project.
3.) Navigate to your index.jsx file in /pages directory and insert this code (I set up a callback when a form submit button is clicked):
const handleSubmit = useCallback(
(body) => {
(async () => {
const parsedBody = body;
const response = await fetch("/api/test?shop=YOUR_SHOP_URL, {
method: "POST",
body: parsedBody
});
if (response.ok) {
console.log("Success");
}
})();
return { status: "success" };
},
[]
);
<Form onSubmit={handleSubmit}>
</Form>
it should call this API endpoint. So now you communicate with an API endpoint.
Maybe I could help you with my answer!

Implementing Google One Tap Login using angular

navbar.template.html
<div id="g_id_onload"
data-client_id="832#################m921.apps.googleusercontent.com"
data-cancel_on_tap_outside="false"
data-login_uri="http://localhost:3010/auth/g-one-tap"
data-callback="handleCredentialResponse">
</div>
The API get the response I am able to validate the user and return the validated JWT token, how can I capture the response and avoid the redirection of the page to http://localhost:3010/auth/g-one-tap
How can I us some click function to be used in typsecript file which can help in following the normal login flow which I am using earlier with google login button.
public socialSignIn(responseData) {
this.googleSubscription = this._globalService.googleLogin(responseData)
.subscribe(
data => {
if (data['success']) {
const token = data['data']['token'];
if (this.platformId === 'browser') {
// login to save the token
}
}
},
error => {
console.log('error');
}
);
}
As mentioned here, you should not use both data-login_uri and data-callbck attributes at the same time.
You need to remove the data-login_uri attribute in you code.
And povide an implementation for the callback function (whose name is handleCredentialResponse in your code) if not yet.

How do I display the captcha icon only on certain pages (VUE reCAPTCHA-v3)?

I use this package : https://www.npmjs.com/package/vue-recaptcha-v3
I add on my main.js :
import { VueReCaptcha } from 'vue-recaptcha-v3'
Vue.use(VueReCaptcha, { siteKey: 'xxxxxxx' })
I add this code :
await this.$recaptcha('login').then((token) => {
recaptcha = token
})
to my component to get token from google recapchta
My problem is the captcha icon in the lower right corner appears on all pages
I want it to only appear in certain components
Maybe I must to change this : Vue.use(VueReCaptcha, { siteKey: 'xxxxxxxxxxxxxxxxx' }). Seems it still mounting to Vue.use. I want to mount to a certain component instead of vue root instance
How can I solve this problem?
Update
I try like this :
Vue.use(VueReCaptcha, {
siteKey: 'xxxxxxx',
loaderOptions: {
useRecaptchaNet: true,
autoHideBadge: true
}
})
It hides the badge. I want the badge to still appear. But only on 1 page, the registration page. How can I do it?
I've had the same issue while using the npm package, it's pretty annoying.
At the end of the day, I've decided not to use the package & follow Google's documentation.
This line here :
grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'login'}).then(function(token) {
recaptcha = token
})
Is equivalent to this line here from the npm package :
this.$recaptcha('login').then((token) => {
recaptcha = token
})
You just need to add this line into your < head > for recaptcha to work :
<script src="https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key"></script>
But as soon the script tag is in your < head >, you will be facing the same issue of it showing on every page.
The hack is that you only insert it into the < head > on components that you need.
There are ways to do this but I ended up referencing this.
You can put it in the methods of your component & call the method when the component is loaded.
That way it will only show up on the pages that you need it to.
in main.js set autoHideBadge true:
import { VueReCaptcha } from 'vue-recaptcha-v3'
Vue.use(VueReCaptcha, { siteKey: 'your site key',
loaderOptions:{autoHideBadge: true }})
in every page you want to show the badge you can show the badge in mounted,
for some reasons until a few seconds after mounted event this.$recaptchaInstance is null and you cant use it, so I use a timeout to showing the badge 5 second after page load in mounted.
mounted(){
setTimeout(()=>{
const recaptcha = this.$recaptchaInstance
recaptcha.showBadge()
},5000)
},
when you show it you have to hide it again in the same page.
beforeDestroy() {
const recaptcha = this.$recaptchaInstance
recaptcha.hideBadge()
},
If you are using composition API setup this is what you need:
const reCaptchaIn = useReCaptcha().instance
onMounted(() => {
setTimeout(() => {
reCaptchaIn.value.showBadge()
}, 3000)
})
Just use this code:
const recaptcha = this.$recaptchaInstance
// Hide reCAPTCHA badge:
recaptcha.value.hideBadge()
// Show reCAPTCHA badge:
recaptcha.value.showBadge()
vue-recaptcha-v3 npm
I stumbled upon this incredibly simple answer. It is excellent especially if you wish to hide the badge from all your pages. You can perhaps use scoped css to hide on some pages as well.
.grecaptcha-badge { visibility: hidden; }
You can read the post here

How to shorten url which contains Id and parse that id when the url is clicked

I am using linking to link my react-native app to my domain
https://www.example.com/
I am also passing an id which changes based on the article shared
So the shared url looks like:
https://www.example.com/12234503
What i want to do is shorten this using firebase dynamic links(I can only use this)
I have no clue how to pack this id into the createShortDynamicLink function or how to access the id i got when i will open this short link in my app
This is what my code without firebase links looks right now
Accepting the url
componentDidMount() {
Linking.addEventListener('url', this.handleUrl);
Linking.getInitialURL().then((url) => {
if (url) {
Linking.openURL(url);
}
}).catch(err => console.error('An error occurred', err));
DeepLinking.addScheme('https://');
DeepLinking.addRoute('www.example.com/:id', (response) => {
this.props.navigation.navigate('Article',{id:response});
});
So i open the app and then take the use to the page where i use the id to load the article
Sharing the Url using react-native-share
let shareOptions = {
title: "Share This Story",
message: "Read This Awsome Article:",
url: "https://www.example.com/"+this.state.id,
subject: "Share Link"
};
Share.open(shareOptions).catch((err) => { err && console.log(err); });
Can you give me a rough outline of code that shows me how can i implement the same using firebase dynamic links
All this is because i want to shorten the shared link
I have a domian to confige
Have you tried this?
url: `https://www.example.com/${this.state.id}`