Skip to content

Commit

Permalink
add twitter auth and drip functions
Browse files Browse the repository at this point in the history
  • Loading branch information
aglawson committed Sep 20, 2023
1 parent 21f8b6a commit cb9d001
Show file tree
Hide file tree
Showing 11 changed files with 687 additions and 6 deletions.
41 changes: 41 additions & 0 deletions functions/AddFaucetUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import dotenv from 'dotenv'
dotenv.config()
import { getFirestore, collection, query, getDocs, where, setDoc, doc } from 'firebase/firestore/lite'
import { initializeApp } from "firebase/app"

const firebaseConfig = {
apiKey: process.env.fb_key,
authDomain: process.env.authDomain,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
}

const fb = initializeApp(firebaseConfig)
const db = getFirestore(fb)

export const AddFaucetUser = async (req) => {
const wallet = req.query.wallet
const handle = req.query.handle

const userRef = collection(db, 'faucet_users')
const q = query(userRef, where('handle', '==', handle))
const userSnapshot = await getDocs(q)

if(userSnapshot.docs.length == 0) {
await setDoc(doc(userRef, wallet), {
handle: handle,
wallet: wallet
});
} else {
throw 'user already exists';
}

const result = {
success: true
}

return result
}
37 changes: 34 additions & 3 deletions functions/Drip.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { ethers } from "ethers"
import {getFirestore, collection, query, getDocs, where, setDoc, doc } from 'firebase/firestore/lite'
import { initializeApp } from "firebase/app"
import dotenv from 'dotenv'
dotenv.config()

const faucet_abi = [
{
Expand Down Expand Up @@ -212,20 +216,47 @@ const faucet_abi = [

export const Drip = async (req) => {
try{
const recipient = req.query.recipient
const recipient = req.query.wallet;
const provider = new ethers.providers.JsonRpcProvider("https://sepolia-rpc.scroll.io");
const contract = "0xAE9EF6F43272C1F5c12cB7530B2868D4055FCbF6"
const FaucetContract = new ethers.Contract(contract, faucet_abi, provider)

const firebaseConfig = {
apiKey: process.env.fb_key,
authDomain: process.env.authDomain,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
}

const app = initializeApp(firebaseConfig)
const db = getFirestore(app)

const docRef = collection(db, 'faucet_users')
const q = query(docRef, where("wallet", "==", recipient))
const docs = await getDocs(q)

if(docs.docs.length === 0) {
throw 'User does not exist';
}

if(Date.now() - docs.docs[0].data().lastDrip < 86400000) {
throw 'Must wait 24hrs from last claim'
}

await setDoc(doc(docRef, recipient), {
lastDrip: Date.now()
}, {merge: true})

console.log(FaucetContract)

const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider)

console.log(signer)

// Write new price to smart contract
const tx = await FaucetContract.connect(signer).drip(recipient, '10000000000000000');

return tx
} catch (error) {
console.log(error)
Expand Down
32 changes: 32 additions & 0 deletions functions/GetAuthTokens.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getFirestore, collection, query, getDocs, where, setDoc, doc } from 'firebase/firestore/lite'
import dotenv from 'dotenv'
import { InitializeFirebase } from "./InitializeFirebase.js"
dotenv.config()

export async function GetAuthTokens(req) {
const wallet = req.query.wallet
const app = await InitializeFirebase();
const db = getFirestore(app)

const docRef = collection(db, 'faucet_users')
const q = query(docRef, where("wallet", "==", wallet))
const docs = await getDocs(q)

if(docs.docs.length === 0) {
return null
}

console.log(docs.docs[0].data())
if(!docs.docs[0].data().oauth_token || !docs.docs[0].data().oauth_token_secret) {
return null
}

const auth_tokens = {
oauth_token: docs.docs[0].data().oauth_token,
oauth_token_secret: docs.docs[0].data().oauth_token_secret,
twitter_id: docs.docs[0].data().twitter_id
}

return auth_tokens

}
Empty file added functions/GetAuthUrl.js
Empty file.
30 changes: 30 additions & 0 deletions functions/GetUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { getFirestore, collection, query, getDocs, where, setDoc, doc } from 'firebase/firestore/lite'
import dotenv from 'dotenv'
import { initializeApp } from "firebase/app"
dotenv.config()

export async function GetUser(req) {
const wallet = req.query.wallet
const firebaseConfig = {
apiKey: process.env.fb_key,
authDomain: process.env.authDomain,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)

const docRef = collection(db, 'faucet_users')
const q = query(docRef, where("wallet", "==", wallet))
const docs = await getDocs(q)

if(docs.docs.length === 0) {
return null
}

return docs.docs[0].data()

}
20 changes: 20 additions & 0 deletions functions/InitializeFirebase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { initializeApp } from "firebase/app"
import dotenv from 'dotenv'
dotenv.config();

export const InitializeFirebase = async() => {
const firebaseConfig = {
apiKey: process.env.fb_key,
authDomain: process.env.authDomain,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
}

const app = initializeApp(firebaseConfig)

return app;
}

169 changes: 169 additions & 0 deletions functions/TwitterLookup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import got from 'got';
import crypto from 'crypto';
import OAuth from 'oauth-1.0a';
import qs from 'querystring';
import * as rl from 'readline';

const readline = rl.createInterface({
input: process.stdin,
output: process.stdout
});

// The code below sets the consumer key and consumer secret from your environment variables
// To set environment variables on macOS or Linux, run the export commands below from the terminal:
// export CONSUMER_KEY='YOUR-KEY'
// export CONSUMER_SECRET='YOUR-SECRET'
const consumer_key = process.env.TWITTER_API_KEY
const consumer_secret = process.env.TWITTER_API_KEY_SECRET

// These are the parameters for the API request
// specify Tweet IDs to fetch, and any additional fields that are required
// by default, only the Tweet ID and text are returned
const params = 'user.fields=created_at,description&expansions=pinned_tweet_id' // Edit optional query parameters here

const endpointURL = `https://api.twitter.com/2/users/me?${params}`;

// this example uses PIN-based OAuth to authorize the user
const requestTokenURL = 'https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=read';
const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
const accessTokenURL = 'https://api.twitter.com/oauth/access_token';

const oauth = OAuth({
consumer: {
key: consumer_key,
secret: consumer_secret
},
signature_method: 'HMAC-SHA1',
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
});

async function input(prompt) {
return new Promise(async (resolve, reject) => {
readline.question(prompt, (out) => {
readline.close();
resolve(out);
});
});
}

async function requestToken() {

const authHeader = oauth.toHeader(oauth.authorize({
url: requestTokenURL,
method: 'POST'
}));

const req = await got.post(requestTokenURL, {
headers: {
Authorization: authHeader["Authorization"]
}
});

if (req.body) {
return qs.parse(req.body);
} else {
throw new Error('Cannot get an OAuth request token');
}
}

async function accessToken(
enc_token,
verifier) {

const oauth_token = enc_token//DecryptData(enc_token)
console.log(oauth_token)

const authHeader = oauth.toHeader(oauth.authorize({
url: accessTokenURL,
method: 'POST'
}));
console.log('in accessToken', oauth_token, verifier)
const path = `https://api.twitter.com/oauth/access_token?oauth_verifier=${verifier}&oauth_token=${oauth_token}`

const req = await got.post(path, {
headers: {
Authorization: authHeader["Authorization"]
}
});

if (req.body) {
console.log('accessToken success')
return qs.parse(req.body);
} else {
throw new Error('Cannot get an OAuth request token');
}
}

async function getRequest(
oauth_token,
oauth_token_secret
) {

oauth_token = oauth_token//DecryptData(oauth_token)
oauth_token_secret = oauth_token_secret//DecryptData(oauth_token_secret)

const token = {
key: oauth_token,
secret: oauth_token_secret
};
// console.log(token)

const authHeader = oauth.toHeader(oauth.authorize({
url: endpointURL,
method: 'GET'
}, token));

const req = await got(endpointURL, {
headers: {
Authorization: authHeader["Authorization"],
'user-agent': "v2UserLookupJS"
}
});

if (req.body) {
return JSON.parse(req.body);
} else {
throw new Error('Unsuccessful request');
}
}

export const getAuthUrl = async () => {
// Get request token
const oAuthRequestToken = await requestToken();

// Get authorization
authorizeURL.searchParams.delete('oauth_token')
authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token);

return { authUrl: authorizeURL.href, requestToken: oAuthRequestToken}
}

export const getAccessToken = async (req) => {
const pin = req.query.pin
const oAuthRequestToken = req.query.requestToken
// console.log(oAuthRequestToken)
// console.log(pin)
try{
const oAuthAccessToken = await accessToken(oAuthRequestToken, pin.trim());
return oAuthAccessToken
} catch(error) {
console.log(error)
throw(error)
}
}

export const TwitterLookup = async (req) => {
try {
const oAuthAccessToken = req.query.oauth_token
const oAuthTokenSecret = req.query.oauth_token_secret

const dec_token = oAuthAccessToken//DecryptData(oAuthAccessToken)
const dec_secret = oAuthTokenSecret//DecryptData(oAuthTokenSecret)
// Make the request
const response = await getRequest(dec_token, dec_secret);
console.log(response)
return response
} catch (e) {
console.log(e);
}
}
25 changes: 25 additions & 0 deletions functions/UpdateUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { getFirestore, collection, query, getDocs, where, setDoc, doc, updateDoc } from 'firebase/firestore/lite'
import dotenv from 'dotenv'
import { InitializeFirebase } from "./InitializeFirebase.js"
dotenv.config()

export const UpdateUser = async (req) => {
const app = await InitializeFirebase();
const db = getFirestore(app)

const wallet = req.query.wallet
const attribute = req.query.attribute
const value = req.query.value

const docRef = collection(db, 'faucet_users')
const q = query(docRef, where("wallet", "==", wallet))
const docs = await getDocs(q)

if(docs.docs.length === 0) throw 'User not found';

await setDoc(doc(docRef, wallet), {
[attribute]: value
}, {merge: true})

return docs.docs[0].data()
}
Loading

0 comments on commit cb9d001

Please sign in to comment.