ورود یا ثبت نام با گوگل در اپلیکیشن nodejs – قسمت ۲


برای ورود یا ثبت نام با گوگل در اپلیکیشن nodejs بعد از ساخت پروژه در google console و دریافت توکن های گوگل، یعنی “Client Id” و “Client secret”، حالا وقتشه که اپلیکیشنمون رو مستقیم وصل کنیم به گوگل

قبل از اینکه شروع کنید به یادگیری  “ورود یا ثبت نام با گوگل در اپلیکیشن nodejs”☝️

توجه داشته باشید که باید دانش خوبی رو از nodejs داشته باشین

خب شروع کنیم…

قدم 1: پیش نیاز هارو نصب کنید 🖥

روی NPM:

همین! یا حوصله نداری بری تو سایتش این دستورو بزن:

npm i googleapis

 

قدم 2: تنظیم گوگل در اپلیکیشن

حالا باید کتابخونه ای که نصب کردید و تنظیم کنید و اون توکن هایی که دریافت کردید رو اینجا به گوگل بشناسونید. منظورم “Client Id” و “Client secret” هست

Next you will need to configure the library with your credentials ,I mean “Client Id” and “Client secret”, so Google knows who is making the requests.

برای دریافت توکن ها و  credentials — اگر هنوز ایجادش نکردید — میتونید به مقاله قبلی (بخش ۱) رجوع کنید

فایل: google-auth.js

const {google} = require("googleapis");
/*******************/
/** CONFIGURATION **/
/*******************/
const googleConfig = {
clientId: '<GOOGLE_CLIENT_ID>', // e.g. 563322924764-u4o5f5o8fovn7t9f24mh92jefqpjj3hl.apps.googleusercontent.com
clientSecret: '<GOOGLE_CLIENT_SECRET>', // e.g. swQWKv9GJv2bA2l2lCs70sMI
redirect: 'http://localhost:3000/validateWithGoogle' // this must match your google api settings
};

قدم 3: URL رو بسازید و ارجاع بدید به کاربر

برای اینکه کسی رو از طریق گوگل بخواید احراز هویت کنید ، نیاز داریم یک آدرس اینترنتی بسازید و کاربرتون رو به آدرس ریدایرکت کنید. بعد از اینکه احراز هویت انجام شد، گوگل شما رو به آدرس callback که مشخص کردید هدایت میکنه و اونجا میتونید اطلاعات مد نظرتون رو بدست بیارید. پس اول باید url رو بسازیم:

شما میتونید از این تابع استفاده کنید: getGoogleAuthenticationUrl()

/**
 * Part 1: Create a Google URL and send to the client to log in the user.
 */
getGoogleAuthenticationUrl: function () {
    return new Promise(async (resolve, reject) => {
        const auth = await GA.createConnection();
        const authorizeUrl = await GA.getConnectionUrl(auth);
        resolve({
            url: authorizeUrl
        });
    });
},

برای استفاده از این تابع در express برای مثال:

router.get('/authenticate', function(req, res, next) {
    gf.getGoogleAuthenticationUrl().then(function (response) {
        res.json(response);
    });
});

این روت (route) مقدار url رو برای کاربر میفرسته که در واقع کاربر باید به همون url هدایت بشه.

توجه: ما از قبل google-auth.js بالای اپلیکیشنی که داریم توسعه میدیم import کردیم:

var gf = require('../google-auth');

قدم 4: به اطلاعات دسترسی پیدا کنید

اگر کاربر موفق بشه که از طریق گوگل احراز هویت رو انجام بده، گوگل شما رو به آدرس callback هدایت میکنه که اطلاعات رو از طریق متد GET و توسط پارامتر code  براتون میفرسته.در واقع به یه همچین url ای انتقال داده میشین:

https://yourwebsite.com/callback?code=a-bunch-of-random-characters

حالا مقدار code رو باید parse کنیم و اون رو به Google api library بفرستیم تا گوگل پاسخ بده و بگه شخص مورد نظر چه کسی هست؟؟

میتونیم از این تابع استفاده کنیم: getGoogleAccountFromCode()

/**
 * Part 2: Take the "code" parameter which Google gives us once when the user logs in, then get the user's email and id.
 */
getGoogleAccountFromCode: async function (code) {

    const auth = await GA.createConnection();
    const data = await auth.getToken(code);
    const tokens = data.tokens;
    await auth.setCredentials(tokens);

    const people = GA.getGooglePeopleApi(auth);
    const me = await people.people.get({
        resourceName: 'people/me',
        personFields: 'emailAddresses,names,photos',
    });
    return me.data;

},

برای مثال من توی express از این تابع دارم به این شکل استفاده میکنم:

router.get('/validateWithGoogle', async function(req, res, next) {
    let s = await gf.getGoogleAccountFromCode(req.query.code);
    let obj = {
        emailAddresses: s.emailAddresses[0].value,
        photos: s.photos[0].url,
        displayName: s.names[0].displayName,
        familyName: s.names[0].familyName,
        givenName: s.names[0].givenName,
    };
    res.json(obj);
});

حالا شما دوتا روت (route) دارین: GET /authenticate و GET /validateWithGoogle 😍

 

کل کد 💎

کل کد رو با تمامی کامنت هایی که کمکتون میکنه متوجه بشید کجا داره چه اتفاقی میفته رو در اختیارتون میزارم، همچنین روی گیت هاب هم وجود داره. اگه مشکلی داشتین حتما بهم انتقال بدین مشکلتون رو.

const {google} = require("googleapis");

/*******************/
/** CONFIGURATION **/
/*******************/

const googleConfig = {
    clientId: '<GOOGLE_CLIENT_ID>', // e.g. 563322924764-u4o5f5o8fovn7t9f24mh92jefqpjj3hl.apps.googleusercontent.com
    clientSecret: '<GOOGLE_CLIENT_SECRET>', // e.g. swQWKv9GJv2bA2l2lCs70sMI
    redirect: 'http://localhost:3000/validateWithGoogle' // this must match your google api settings
};

/**
 * This scope tells google what information we want to request.
 */
const defaultScope = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
];

var GA = module.exports = {

    /**
     * Create the google auth object which gives us access to talk to google's apis.
     */
    createConnection: function () {
        return new google.auth.OAuth2(
            googleConfig.clientId,
            googleConfig.clientSecret,
            googleConfig.redirect
        );
    },

    /**
     * Get a url which will open the google sign-in page and request access to the scope provided (such as calendar events).
     */
    getConnectionUrl: function (auth) {
        return auth.generateAuthUrl({
            access_type: 'offline',
            prompt: 'consent', // access type and approval prompt will force a new refresh token to be made each time signs in
            scope: defaultScope
        });
    },

    /**
     * Helper function to get the library with access to the google plus api.
     */
    getGooglePeopleApi: function (auth) {
        return google.people({
            version: 'v1',
            auth: auth,
        });
    },

    /**
     * Part 1: Create a Google URL and send to the client to log in the user.
     */
    getGoogleAuthenticationUrl: function () {
        return new Promise(async (resolve, reject) => {
            const auth = await GA.createConnection();
            const authorizeUrl = await GA.getConnectionUrl(auth);
            resolve({
                url: authorizeUrl
            });
        });
    },

    /**
     * Part 2: Take the "code" parameter which Google gives us once when the user logs in, then get the user's email and id.
     */
    getGoogleAccountFromCode: async function (code) {

        const auth = await GA.createConnection();
        const data = await auth.getToken(code);
        const tokens = data.tokens;
        await auth.setCredentials(tokens);

        const people = GA.getGooglePeopleApi(auth);
        const me = await people.people.get({
            resourceName: 'people/me',
            personFields: 'emailAddresses,names,photos',
        });
        return me.data;

    },
};

احسنت، اینه ره میخوام!! 🎉 🎊 👏

حالا اپلیکیشن شما احراز هویت با گوگل رو پشتیبانی میکنه.

فالوم کنید:  Instagram



دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *