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

Feature: Implement Google Auth verification #10

Merged
merged 2 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ app.post('/verify/:platform', async (req, res) => {
const verifiedResult = await verifier.verify(accountId, handle, proof, challenge);
let verified = null;

if (platform === "twitter") {
if (platform === "twitter" || "google") {
matiasberaldo marked this conversation as resolved.
Show resolved Hide resolved
verified = verifiedResult.result;
handle = verifiedResult?.handle;
} else {
Expand All @@ -41,7 +41,7 @@ app.post('/verify/:platform', async (req, res) => {
proof
});

if (platform === "twitter") {
if (platform === "twitter" || "google") {
matiasberaldo marked this conversation as resolved.
Show resolved Hide resolved
return res.status(200).json({
...badge,
handle: handle
Expand Down
130 changes: 130 additions & 0 deletions utils/google.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import badger from './nearbadger.js';

const GOOGLE_API_URL = 'https://oauth2.googleapis.com';
const GOOGLE_OAUTH_TOKEN_ENDPOINT = 'token';
const GOOGLE_OAUTH_USERS_INFO_ENDPOINT = 'userinfo';

const GOOGLE_AUTH_URL = 'https://www.googleapis.com/oauth2/v3';

export class GoogleAPI {
static async request(endpoint, options) {
return fetch(endpoint, options)
.then(
(data) => {
return data.json();
}
);
}
static async getUserAccessToken(params) {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(
this.getAccessTokenParams(params)
),
};

const fullUrl = `${GOOGLE_API_URL}/${GOOGLE_OAUTH_TOKEN_ENDPOINT}`;

return this.request(fullUrl, options)
.then(
(info) => {
return info?.access_token || '';
}
);
}
static async getUserHandle(accessToken) {
const options = {
headers: {
Authorization: `Bearer ${accessToken}`
}
};

const fullUrl = `${GOOGLE_AUTH_URL}/${GOOGLE_OAUTH_USERS_INFO_ENDPOINT}`;

return this.request(fullUrl, options)
.then(
(user) => {
return user?.email || ''
}
);
}
static getAccessTokenParams({
code,
redirectUri,
codeVerifier
}) {
return {
code,
client_id: process.env.GOOGLE_OAUTH_CLIENT_ID,
matiasberaldo marked this conversation as resolved.
Show resolved Hide resolved
client_secret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
redirect_uri: redirectUri,
grant_type: 'authorization_code',
};
}
static getFullURL(endpoint) {
return `${GOOGLE_API_URL}/${endpoint}`;
}
}

export class GoogleAuth {
generateAuthURL({state, codeChallenge, redirectUri, handle}) {
return this.getBaseURL({
clientId: process.env.GOOGLE_OAUTH_CLIENT_ID || '',
codeChallenge,
state: `google.${handle}.${state}`,
redirectUri
});
}

generateChallenge(accountId, handle) {
const platform = 'google';
const nonce = badger.getSafeNonce();
const rawChallenge = this.getRawChallenge({
accountId,
handle,
platform,
nonce
});
const signature = Buffer.from(
badger.sign(rawChallenge)
).toString('base64');

return Buffer.from(`${rawChallenge},${signature}`).toString("base64");
}

decodeChallenge(encodedChallenge) {
const sanitizedEncodedChallenge = decodeURIComponent(encodedChallenge);
const decodedChallenge = Buffer.from(sanitizedEncodedChallenge, "base64").toString('utf-8');
const [accountId, handle, platform, nonce, encodedSignature] = decodedChallenge.split(',');

return {
challenge: this.getRawChallenge({
accountId,
handle,
platform,
nonce
}),
signature: encodedSignature
};
}

getRawChallenge({ accountId, handle, platform, nonce }) {
return `${accountId},${handle},${platform},${nonce}`;
}

getBaseURL({ clientId, codeChallenge, state, redirectUri }) {
const searchParams = new URLSearchParams({
state,
code_challenge_method: 'plain',
code_challenge: codeChallenge,
client_id: clientId,
response_type: 'code',
redirect_uri: redirectUri
});

return `${GOOGLE_AUTH_URL}?${searchParams.toString()}&scope=users.read%20tweet.read`;
}
}
64 changes: 64 additions & 0 deletions verifiers/google.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import badger from '../utils/nearbadger.js';
import { GoogleAuth, GoogleAPI } from '../utils/google.js';
import AbstractVerifier from './verifier.js';

const DEFAULT_REDIRECT_URI = 'https://near.social/mattb.near/widget/NearBadger.Pages.Authentication';
const GOOGLE_CODE_CHALLENGE = 'nearbadger';

export default class GoogleVerifier extends AbstractVerifier {
auth = null;

constructor() {
super();

this.auth = new GoogleAuth();
}
async verify(accountId, handle, proof, encodedChallenge) {
const accessToken = await GoogleAPI.getUserAccessToken({
code: proof,
redirectUri: this.getRedirectUri(),
codeVerifier: this.getCodeChallenge()
});


if (accessToken) {
const googleHandle = await GoogleAPI.getUserHandle(accessToken);


if (typeof googleHandle === "string") {
return {
result: true,
handle: googleHandle.toLowerCase()
};
}
}

return {
result: false
};
}
getChallenge(accountId, handle) {
const state = this.auth.generateChallenge(accountId, handle);
const redirectUri = this.getRedirectUri();
const codeChallenge = this.getCodeChallenge();

return this.auth.generateAuthURL({
handle,
state,
codeChallenge,
redirectUri
});
}
getCodeChallenge() {
return GOOGLE_CODE_CHALLENGE;
}
getRedirectUri() {
return DEFAULT_REDIRECT_URI;
}
verifyChallenge(challenge) {
const rawChallenge = challenge.challenge;
const encodedSignature = challenge.signature;

return badger.verifyIsMe(rawChallenge, encodedSignature);
}
}
4 changes: 3 additions & 1 deletion verifiers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import LensVerifier from "./lens.js";
import FarcasterVerifier from "./farcaster.js";
import TwitterVerifier from "./twitter.js";
import NearVerifier from './near.js';
import GoogleVerifier from './google.js';

const Verifiers = {
lens: new LensVerifier(),
farcaster: new FarcasterVerifier(),
twitter: new TwitterVerifier(),
near: new NearVerifier()
near: new NearVerifier(),
google: new GoogleVerifier()
}

export default Verifiers;
Loading