Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i get the user details from this code #346

Open
Thirumalakond-Ganesh opened this issue May 3, 2024 · 4 comments
Open

How can i get the user details from this code #346

Thirumalakond-Ganesh opened this issue May 3, 2024 · 4 comments

Comments

@Thirumalakond-Ganesh
Copy link

import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({
onSuccess: tokenResponse => console.log(tokenResponse),
});

Sign In With Google

Output i am getting:-
{access_token: 'ya29.a0AXooCgt6w-E0IUzjRPO5uYnhSpS2o5kJoEK0cWiCQ6W…TsaCgYKAZcSARASFQHGX2MiMEc1HD3QuJX2AVIvH7A5Aw0170', token_type: 'Bearer', expires_in: 3599, scope: 'email profile openid https://www.googleapis.com/au…le https://www.googleapis.com/auth/userinfo.email', authuser: '0', …}
access_token
:
"ya29.a0AXooCgt6w-E0IUzjRPO5uYnhSpS2o5kJoEK0cWiCQ6WEMpJq4KW4xs-_lOubdorhj8Cdhf3AfyVFsU6c0IxHigK7WAqP1MYJ-OQdYVkuVlcaVMihQYDcJ4xQ4-PMFAx_qYu58Gl4jtdI7juHPAJf4Icq1-mcCvLnlTsaCgYKAZcSARASFQHGX2MiMEc1HD3QuJX2AVIvH7A5Aw0170"
authuser
:
"0"
expires_in
:
3599
prompt
:
"none"
scope
:
"email profile openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
token_type
:
"Bearer"

actual output i need is:-

aud
:
"160074142288-8o973fd5lsgdliic5i6ie83aod662gab.apps.googleusercontent.com"
azp
:
"160074142288-8o973fd5lsgdliic5i6ie83aod662gab.apps.googleusercontent.com"
email
:
"mrabhi74744@gmail.com"
email_verified
:
true
exp
:
1714723617
family_name
:
"Abhi"
given_name
:
"Mr"
iat
:
1714720017
iss
:
"https://accounts.google.com"
jti
:
"4b9458ffefa2a0275d05b52fe80c69f58f767299"
name
:
"Mr Abhi"
nbf
:
1714719717
picture
:
"https://lh3.googleusercontent.com/a/ACg8ocKg0az7NVhTLD-8mb0OIzpQISCFY2ehyYTLzL8IK5UM-QW6kA=s96-c"
sub
:
"114964555203191333911"

@aniketharx10x
Copy link

aniketharx10x commented May 22, 2024

hello, try this:

(prerequisite: npm i axios)

import { useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';

const login = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      try {
        const response = await axios.get(
          'https://www.googleapis.com/oauth2/v3/userinfo',
          {
            headers: { 
              Authorization: `Bearer ${tokenResponse.access_token}` 
            },
          }
        );
        console.log(response.data);
      } catch (err) {
        console.log(err);
      }
    },
  });

I got the user details on the console from this code

@Thirumalakond-Ganesh
Copy link
Author

But for me this error came Access to XMLHttpRequest at 'https://www.googleapis.com/oauth2/v3/userinfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Login.js:62 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}code: "ERR_NETWORK"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Network Error"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …}onabort: ƒ handleAbort()onerror: ƒ handleError()onload: nullonloadend: ƒ onloadend()onloadstart: nullonprogress: nullonreadystatechange: nullontimeout: ƒ handleTimeout()readyState: 4response: ""responseText: ""responseType: ""responseURL: ""responseXML: nullstatus: 0statusText: ""timeout: 0upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}onabort: nullonerror: nullonload: nullonloadend: nullonloadstart: nullonprogress: nullontimeout: null[[Prototype]]: XMLHttpRequestUploadwithCredentials: true[[Prototype]]: XMLHttpRequeststack: "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:146504:14)"[[Prototype]]: Error
Login.js:50

    GET https://www.googleapis.com/oauth2/v3/userinfo net::ERR_FAILED  How can i fix this and this my code 
    
    import React, { useState } from "react";

import { Link, useNavigate } from "react-router-dom";
import { InputText } from "primereact/inputtext";
import { Button } from "primereact/button";
import { useForm } from "react-hook-form";
import "../Login/Login.css";
import axios from "axios";
import { SERVER_url } from "../../config";
import { GoogleLogin, useGoogleLogin } from "@react-oauth/google";
import jwtDecode from "jwt-decode"; // Correct import

const Login = () => {
axios.defaults.withCredentials = true;
const navigate = useNavigate();
const [error, setError] = useState("");
const {
handleSubmit,
formState: { errors },
register,
} = useForm();

const onSubmit = async (data) => {
try {
const response = await axios.post(${SERVER_url}/login, data);
doLogin(response);
} catch (error) {
setError("An error occurred while logging in");
console.error("Error occurred", error);
}
};

const doLogin = (response) => {
console.log("Response Status:", response.status);
console.log("Response Data:", response.data);

if (response.status === 200) {
  setError(""); // Clear any previous error
  localStorage.setItem("token", response.data.jwtToken);
  sessionStorage.setItem("token", response.data.jwtToken);
  navigate("/home");
  console.log("Login successful");
} else {
  setError("Incorrect email or password");
}

};

const login = useGoogleLogin({
onSuccess: async (tokenResponse) => {
try {
const response = await axios.get(
'https://www.googleapis.com/oauth2/v3/userinfo',
{
headers: {
Authorization: Bearer ${tokenResponse.access_token}
},
}
);
console.log(response.data);
// Handle the response data here, such as logging in the user
doLogin({ status: 200, data: { jwtToken: tokenResponse.access_token } });
} catch (err) {
console.log(err);
}
},
onError: (error) => console.log("Login Failed:", error),
});

return (




LogIn



<InputText
{...register("email", {
required: "Email is required",
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i,
message: "Invalid email address",
},
})}
placeholder="Email Id"
/>
{errors.email &&

{errors.email.message}

}
<InputText
type="password"
{...register("password", {
required: "Password is required",
pattern: {
value:
/^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\d@$!%?&]{8,}$/,
message:
"Password must be at least 8 characters long and include at least one lowercase letter, one uppercase letter, one digit, and one special character.",
},
})}
placeholder="Password"
/>
{errors.password && (

{errors.password.message}


)}
{error &&

{error}

}





Forgot Password?



Don't have an account yet ?{" "}

<span
style={{
color: "red",
fontWeight: "800",
paddingLeft: "5px",
}}
>
Sign up here







Sign In With Google




);
};

export default Login;

@Thirumalakond-Ganesh
Copy link
Author

Please help me in this

@Thirumalakond-Ganesh
Copy link
Author

Thirumalakond-Ganesh commented May 22, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants