Can't tweet on twitter by using supabase user access token - twitter

I am using supabase/auth-helpers with sveltekit and using Twitter OAuth, and the sign up and login are working just fine.
I am using the twitter-api-v2 package, and it states that I can use access token as bearer token like so:
const client = new TwitterApi(MY_BEARER_TOKEN);
Here is my code:
import { variables } from '$lib/variables';
import { supabaseServerClient, withApiAuth } from '#supabase/auth-helpers-sveltekit';
import type { RequestHandler } from '#sveltejs/kit';
import { TwitterApi } from 'twitter-api-v2';
export const GET: RequestHandler<any> = async ({ locals }) =>
withApiAuth(
{
redirectTo: '/',
user: locals.user
},
async () => {
const loggedClient = new TwitterApi(locals.accessToken!, {
clientId: variables.twitter_oauth_client_id,
clientSecret: variables.twitter_oauth_secret
} as any);
const profile = await loggedClient.v2.me();
return {
body: {
data: profile as any
}
};
}
);
However, I am getting error 403 and sometimes 401. The error output reads:
Request failed with code 401
Here is a link to twitter api response codes: https://developer.twitter.com/en/support/twitter-api/error-troubleshooting

Related

"TypeError: OAuth2Strategy requires a verify callback." but i send it (nestjs)

I call the constructor of OAuth2Strategy in app.controller.ts, i send it the 2 params it needs: options with clientID, callbackURL etc, and a verify callback function. But i have this error, looks like i don't send a verify callback function to the constructor, but i did. The error happens in node_modules/passport-oauth2/lib/strategy.js.
app.controller.ts:
import { Body, Controller, Get, Post, Query, Res, Req, Next, UnauthorizedException, UseGuards } from '#nestjs/common';
import { PartieService, JoueurService, CanalService } from './app.service';
import { Joueur, Partie, Canal } from './app.entity';
import { AuthGuard } from '#nestjs/passport';
import passport = require("passport");
import OAuth2Strategy = require("passport-oauth2");
//var OAuth2Strategy = require('passport-oauth2').OAuth2Strategy;
//import OAuth2Strategy from 'passport-oauth2';
#Controller()
export class AppController {
constructor(private readonly partieService: PartieService, private readonly joueurService: JoueurService,
private readonly canalService: CanalService) {}
#Get('/oauth2')
async oauth2(#Req() req, #Res() res, #Next() next) {
passport.use('oauth2', new OAuth2Strategy(
{
clientID: 'my_clientID',
clientSecret: 'my_clientSecret',
authorizationURL: 'https://api.abc.com/oauth/authorize',
tokenURL: 'https://api.abc.fr/oauth/token',
callbackURL: 'http://localhost:3000/Connection'
},
async (accessToken: string, refreshToken: string, profile: any, done: Function) => {
//console.log(profile);
try {
if (!accessToken || !refreshToken || !profile) {
return done(new UnauthorizedException(), false);
}
const user: Joueur = await this.joueurService.findOrCreate(profile);
return done(null, user);
} catch (err) {
return done(new UnauthorizedException(), false);
}
} ));
passport.authenticate('oauth2');
return res.sendFile("/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/public/connection.html");
}
#Get('/Connection')
//#UseGuards(AuthGuard('oauth2'))
async Callback(#Req() req, #Res() res, #Next() next) {
passport.authenticate('oauth2', (err, user, info) => {
if (err || !user) {
req.session.destroy();
return res.status(401).json({
message: 'Unauthorized',
});
}
req.user = user;
return next();
})(req, res, next);
const utilisateur: Joueur = req.user;
console.log(utilisateur);
}
[...]
}
node_modules/passport-oauth2/lib/strategy.js:
function OAuth2Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = undefined;
}
options = options || {};
if (!verify) { throw new TypeError('OAuth2Strategy requires a verify callback'); }
[...]
}
Error:
[Nest] 6550 - 05/02/2023, 18:34:54 ERROR [ExceptionHandler] OAuth2Strategy requires a verify callback
TypeError: OAuth2Strategy requires a verify callback
at new OAuth2Strategy (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/passport-oauth2/lib/strategy.js:84:24)
at Injector.instantiateClass (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/injector.js:340:19)
at callback (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/injector.js:53:45)
at Injector.resolveConstructorParams (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/injector.js:132:24)
at Injector.loadInstance (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/injector.js:57:13)
at Injector.loadProvider (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/injector.js:84:9)
at async Promise.all (index 3)
at InstanceLoader.createInstancesOfProviders (/home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/instance-loader.js:47:9)
at /home/user42/Documents/Projets/ft_transcendence/services/pong/pong/node_modules/#nestjs/core/injector/instance-loader.js:32:13
at async Promise.all (index 1)
`
I tried to change the import OAuth2Strategy many times (like the commented lines). I tried a lot of things but i cannot remember all. I found no answer in internet, and no more with the not-so-well-chatgpt.
I am new in nestjs and this error is weird for me, how can it ask me a parameter that i send ? Can someone help me to resolve this pls ? :)
Sorry if the answer is obvious :/ , it's my first API with nestjs
The error was coming from another file, my bad, it's fixed.

aws-cdk TokenAuthorizer - how to pass the payload from the authorizer to the lambda for the protected endpoint?

In my cdk stack I have an api endpoint that calls a lambda and that is protected by a TokenAuthorizer using a JWT, that looks like:
// inside my cdk Construct
const auth = new apiGateway.TokenAuthorizer(this, "Authorizer", {
handler: authorizeUserLambda
});
const api = new apiGateway.RestApi(this, "ApiGateway-lambda-authorizer", {
description: "my api"
});
const users = api.root.addResource("users");
const getUser = users.addResource("{userId}");
const getUserIntegration = new apiGateway.LambdaIntegration(getUserLambda);
getUser.addMethod("GET", getUserIntegration, {authorizer: auth});
And the handler for authorizeUserLambda itself:
// types removed
function generatePolicy(principalId, effect, resource) {
const authResponse = {
principalId,
context: {
stringKey: "stringval",
numberKey: 123,
booleanKey: true
}
};
if (effect && resource) {
return {
...authResponse,
policyDocument: {
Version: "2012-10-17",
Statement: [
{
Action: "execute-api:Invoke",
Effect: effect,
Resource: resource
}
]
}
};
}
return authResponse;
}
export const handler = async function authorizeUser(event) {
const jwt = event.authorizationToken?.split(" ")[1];
try {
if (verify(jwt, secret)) {
return generatePolicy("user", "Allow", event.methodArn);
}
return generatePolicy("user", "Deny", event.methodArn);
} catch {
return "Error: Invalid token";
}
};
This code does successfully decode the JWT and authenticate a user, but how would I pass the payload of the JWT (or anything at all from authorizer function) to the getUserLambda function? Do I need to create a reference to the function's output inside the Construct? The JWT payload has a userId and role inside that I want access to for lambdas like getUser.

download attachments from mail using microsoft graph rest api

I've been successfully getting the list of mails in inbox using microsoft graph rest api but i'm having tough time to understand documentation on how to download attachments from mail.
For example : This question stackoverflow answer speaks about what i intend to achieve but i don't understand what is message_id in the endpoint mentioned : https://outlook.office.com/api/v2.0/me/messages/{message_id}/attachments
UPDATE
i was able to get the details of attachment using following endpoint : https://graph.microsoft.com/v1.0/me/messages/{id}/attachments and got the following response.
I was under an impression that response would probably contain link to download the attachment, however the response contains key called contentBytes which i guess is the encrypted content of file.
For attachment resource of file type contentBytes property returns
base64-encoded contents of the file
Example
The following Node.js example demonstrates how to get attachment properties along with attachment content (there is a dependency to request library):
const attachment = await getAttachment(
userId,
mesasageId,
attachmentId,
accessToken
);
const fileContent = new Buffer(attachment.contentBytes, 'base64');
//...
where
const requestAsync = options => {
return new Promise((resolve, reject) => {
request(options, (error, res, body) => {
if (!error && res.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
};
const getAttachment = (userId, messageId, attachmentId, accessToken) => {
return requestAsync({
url: `https://graph.microsoft.com/v1.0/users/${userId}/messages/${messageId}/attachments/${attachmentId}`,
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json;odata.metadata=none"
}
}).then(data => {
return JSON.parse(data);
});
};
Update
The following example demonstrates how to download attachment as a file in a browser
try {
const attachment = await getAttachment(
userId,
mesasageId,
attachmentId,
accessToken
);
download("data:application/pdf;base64," + attachment.contentBytes, "Sample.pdf","application/pdf");
} catch (ex) {
console.log(ex);
}
where
async function getAttachment(userId, messageId, attachmentId, accessToken){
const res = await fetch(
`https://graph.microsoft.com/v1.0/users/${userId}/messages/${messageId}/attachments/${attachmentId}`,
{
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/json;odata.metadata=none"
}
}
);
return res.json();
}
Dependency: download.js library
I don't know if this would help but you just have to add /$value at the end of your request :
https://graph.microsoft.com/v1.0/me/messages/{message_id}/attachments/{attachment_id}/$value

Saving Auth token in localStorage (React + ROR)

After login functionality, I am saving my auth token in browser's localStorage, so that i can authenticate each action fired to the server. After login i have to refresh my browser to retrieve my token, since root component is not rerendered. is there any way to rerender index.js? I am building an electron app, so browser refresh is not an option.
in index.js
const AUTH_TOKEN = localStorage.getItem('user')
if(AUTH_TOKEN){
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
store.dispatch({type: AUTHENTICATED});
}
but this will only get rendered only the first time app loads. Store and routes are defined inside. So after login auth token will be saved in localstorage but its not updated in app. Any ideas?
You can just set the axios authorization header after saving the auth token.
So this is what i did
In Auth action
localStorage.setItem('user', response.data.auth_token);
localStorage.setItem('name', response.data.user.name);
localStorage.setItem('email', response.data.user.email);
axios.defaults.headers.common['Authorization'] = response.data.auth_token;
dispatch({ type: AUTHENTICATED });
you can manage token like there, its updated on token expire, token change
const watchToken = (delay) => {
return setTimeout(() => {
myApi.getToken().then(res => {
if (res.token) {
store.dispatch({ type: AUTHENTICATED })
} else {
store.dispatch({ type: NOT_AUTHENTICATED })
}
})
}, delay);
}
class App extends Component {
tokenManager;
constructor() {
super();
this.state = {
isReady: false
};
}
componentWillMount() {
this.tokenManager = watchToken(20000)
}
componentWillUpdate(nextProps, nextState) {
if (nextProps.TOKEN !== this.props.TOKEN) {
this.tokenManager = watchToken(20000);
}
}
componentWillUnmount() {
this.tokenManager.clearTimeout();
}
render() {
return (
<div>
</div>
);
}
}

Getting Data with Header Authorization Ionic 2

I'm currently working on Ionic 2 with Ruby on Rails as a backend. The issue I face is that I have trouble understanding Observables and Promises. Are they related to each other? Right now I'm trying to retrieve the data after the POST request is authenticated with the header.
//clocks.ts (Provider)
import { Injectable } from '#angular/core';
import { Http, Headers, Response, RequestOptions } from '#angular/http';
import { Storage } from '#ionic/storage';
import 'rxjs/add/operator/map';
#Injectable()
export class Clocks {
baseUrl: string = "http://localhost:3000/api/v1"
token: any;
constructor(public http: Http, public storage: Storage) {}
getAttendanceInfo() {
return new Promise((resolve,reject) => {
// Load token
this.storage.get('token').then((value) => {
this.token = value;
let headers = new Headers();
headers.append('Authorization', 'Token ' + this.token);
this.http.get(this.baseUrl + '/attendances.json', {headers: headers})
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
})
});
});
}
At Attendance Page
//attendance.ts (Page)
loadAttendance() {
this.clocks.getAttendanceInfo().then(res => {
let response = (<Response>res).json();
this.attendance = response.data;
console.log(this.attendance)
})
}
Here are my questions.
Could I use Observables in this case to achieve the same result as the getAttendanceInfo() method? How do they work?
And also, is there any way that I can retrieve the token from the storage for every page request without rewriting the same code for headers? Eg. One method that can always be used to retrieve the token from the storage and append at the header.
Greatly appreciate if you guys can clear my confusion.
I've found the solution.
You can create a authentication as part of the service provider. For this case, I'm using localStorage. For the remarks, the structure of the Token is dependent for your backend as well. For my case, I'm using authentication_with_http_token from Rails method, the structure is like this
GET /attendances HTTP/1.1
Host: localhost:3000
Authorization: Token token=123123123
We have to match that.
// ../providers/auth.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class Auth {
constructor(public http: Http) {}
createAuthorizationHeader(headers: Headers) {
headers.append('Authorization', 'Token ' + window.localStorage.getItem('token'));
}
}
Wen you return a http request, it was returned in a Observable format. Unless you want to convert into Promises, you don't have to do anything about it.
// ../pages/attendances/attendances.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Auth } from '../../providers/auth';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
const baseUrl: string = 'http://localhost:3000/api/v1/';
export class HomePage {
constructor(public navCtrl: NavController, public auth: Auth) {}
ionViewDidLoad() {
this.getAttendances();
}
getAttendances() {
return this.http.get(baseUrl + 'bookings.json', { headers: headers })
.map(data => {
// convert your data from string to json
data = data.json();
})
.subscribe(response => {
// to subscribe to the stream for the response
console.log(response);
// you can save your response in object based on how you want it
})
}

Resources