Getting a 404 error whenever I fork a repo - github-api

I'm trying to create a website that can fork a repo using Octokit, but I keep getting 404 errors.
const octokit = new Octokit({
auth: accessToken
})
try {
const response = await octokit.request('POST /repos/{owner}/{repo}/forks', {
owner: 'google',
repo: 'googletest'
})
console.log(response)
}
catch(e) {
console.log(e)
}
RESPONSE:
POST https://api.github.com/repos/google/googletest/forks 404
HttpError: Not Found
NOTE:
The personal access token has repo permissions allowed.
The Github client ID and secret are valid.
I'm not sure what else to try.

Related

504 error when apis are run in sever but in local it is working nodejs

i am new to hosting in aws ec2 i used a ubnuu 20 instance i used nginx and pm2 to run my express js app
i run my app in localshost and its working fine but in production sever i am getting error 504 time out it occours only for apis that are in POST method i tryed both in frontend and postman i am not sure what is the issue
i tryed pm2 log and got this error not sure what it means
[enter image description here]
(https://i.stack.imgur.com/GAafX.png)
this is the api i am getting error u can try to use this api in postman and try it yourself i will add some creditial to use it in post man
u can use this credential in postman body to reprduce the error
https://shezhealthy.shebirth.com/login
username : test#gmail.com
password :2211
i will add the login code here i am not sure what else code ypu want to fix this so i will add full index.js in another file and link here
also i am adding a get api to show u that i have configured aws corrctly
https://shezhealthy.shebirth.com/files
pls if u are willing to help and pls add a comment so i can undersand whats wrong with the qustion if u close the question i wont undesand the issue and will be a waste of my time so pls help me with comments to improve the question
app.post("/login", async function (req, res) {
try {
let formData = req.body;
const user = await mydb
.collection("signup")
.findOne({ useremail: formData.username });
if (!user) {
console.log(user);
return res.status(401).send({ error: "User not found" });
}
if (formData.password !== user.password) {
return res.status(401).send({ error: "Invalid password" });
}
let payload = {
useremail: user.email,
_id: user._id,
};
let token = jwt.sign(payload, "secretKey");
res.json({ token, result: user });
} catch (error) {
console.log(error);
res.status(500).send({ error: "Internal server error" });
}
});
i have added full code here but i am not able to do npm i here for u to insatll node_modules so its error here
https://codesandbox.io/p/sandbox/blissful-rgb-538rkk?file=%2Findex.js&selection=%5B%7B%22endColumn%22%3A39%2C%22endLineNumber%22%3A298%2C%22startColumn%22%3A39%2C%22startLineNumber%22%3A298%7D%5D

Node js login using passport-local working in postman but getting error in frontend Vue JS

I am using passport-local for user authentication. When I try to get logged in User it works in postman but gives error message which i set to "You need to be logged in first to get data". My user is successfully logging in from vue js but when i try to get logged in user its gives my error message.
here is my route :
router.get('/jobs', auth ,async(req, res) => {
const jobs = await Job.find({}).sort({
createdAt : -1
})
console.log(req.user)//This is working in postman but gives error in vue js
res.send(jobs)
})
I am using cors and specifying origin and set credentials to true.
here is my frontend request :
try{
const res = await axios.get('http://localhost:3000/jobs', {
withCredentials : true
})
this.jobs = await res.data
console.log(this.jobs) // It gives my error message even i am logged in
}catch(error) {
if(error.response) {
this.message = error.response.data
}
}
If you use token, you need to pass it with your request like that:
const config = {
withCredentials : true,
headers: {
Token: user.value.token
},
};
try{
const res = await axios.get('http://localhost:3000/jobs', config)
this.jobs = await res.data
console.log(this.jobs) // It gives my error message even i am logged in
}catch(error) {
if(error.response) {
this.message = error.response.data
}
}
Look in postman the headers you are sending.
edit: added image

CORS Error in a working setup while trying to authenticate using Google+ API in React/Node setup

I was implementing the Oauth2.0 authentication using Google. I used react-google-login npm on the frontend to authenticate the user using Google Oauth2.0. I successfully created the CLient-id and secret under google cloud platform for my project, along with the URI as needed.
The frontend is running on default localhost:3000 and backend (node/express) running on localhost:9001 with proxy enabled on frontend to redirect the request to backend.
I was able to authenticate using Google more than 2 dozen times last night as i was working on the backend siginIn contoller. I was also able to add the user to my Mongodb after successful authentication from Google.
All of a sudden, i was getting CORS error which is a bit strange as none of the code or Google configs were changed.
My Google config looks as follows.
My code on the frontend is still successfully redirecting the user to Google for authentication. Its also generating the right google credentials.
SignIn Component Code snippet passing the info to responseGoogle which resides in withLogin HOC Parent Component.
<GoogleLogin
clientId={GOOGLE_CLIENT_ID}
buttonText="Google"
render={(renderProps) => (
<button onClick={renderProps.onClick} style={customStyle}>
<img className="googleBtn" src={googleIcon} alt="GMAIL ICON" />
</button>
)}
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={"single_host_origin"}
/>
withLogin HOC Parent Component dispatching the info to Redux thunk.
const responseGoogle = (res) => setGoogleResp(res);
useEffect(() => {
googleResp?.error &&
setValues({ ...values, serverError: "GOOGLE LOGIN FAILED" });
googleResp?.tokenId && dispatchGoogleSignInDataToBackend()
}, [googleResp]);
const dispatchGoogleSignInDataToBackend=async ()=>{
const data=await dispatch(allActions.googleSignInAction(googleResp,whoLoggedIn));
if (data.error) {
setValues({ ...values, serverError: data.error, success: false });
} else {
const {
email,
name,
_id,
role,
listOfEmailOfAllClientsForLawyerLogin,
} = data.userCred;
saveJwtToLocalStorage(
data.token,
{ name, email, _id, role, listOfEmailOfAllClientsForLawyerLogin },
() => {
setValues({
email,
serverError: false,
success: true,
});
}
);
}
}
I am sending the appropriate CORS header in the request to the backend.
export const dataHeaders = {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
"Access-Control-Allow-Headers" :"*"
};
Redux thunk code:-
export const googleSignInAction=(googleResp,whoLoggedIn)=>{
console.log("Login Success: currentUser:", googleResp);
return async (dispatch) => {
dispatch({ type: SIGNIN_LOADING });
try {
const response = await axios.post(
`${API_URL}/googlesignin`,
{
googleResp,
whoLoggedIn
},
{
headers: dataHeaders,
}
);
console.log("response inside googleSignInAction", response);
// CHANGED COZ OF ESLINT WARNING.
if (
response.status === 201 &&
Object.keys(response.data).includes("token") &&
Object.keys(response.data).includes("userCred")
) {
dispatch({ type: SIGNIN_SUCCESS, data: response.data });
return response.data;
} else {
dispatch({ type: SIGNIN_FAILED });
}
} catch (error) {
dispatch({ type: SIGNIN_FAILED });
return error.response.data;
}
};
}
API URL Points to following:-
export const API_URL="http://localhost:9001/api";
No request is reaching the backend because of CORS error.
Frontend receiving the Correct Response from Google Post authentication.
Errors on the Frontend.
Browsers will first send a pre-flight request to check CORS. In your backend code, you have to allow the front-end host and port. In this case localhost:3000.
The reason you are getting the cors error is bacause its on two different ports.
But if proper cors response is given by backend (port 9000), it will resolve.
Clearing the browser cookies and cache made everything work again. googlesignin is working without cors error. I have added following line of code to serve all static files from backend to frontend.
app.use(express.static(path.join(__dirname, '../frontend/public')));

API Token returning 401 Unauthorised when its working in URL

I am making a Multi-Purpose API Service and as I got the token in the URL working perfect and authorising as expected with a 200. I've been having issues with the token not authorising with curl command or superagent, as its always return a 401 error.
auth.js
const { DB } = require('../src/Routes/index.js');
module.exports = function auth(req, res, next) {
if(!req.query.apiKey) {
return res.status(401).json({"error": "401 Unauthorized", message: "API Token is missing in the query. You will need to generate a Token and put in the apiKey query."})
} else {
let check = DB.filter(k => k).map(i => i.apiToken);
console.log(check);
let t = check.some(e => e == req.query.apiKey)
if(t !== true)
return res.status(401).json({"error": "401 Unauthorized", message: "The API Key you provided is invalid. Please refer to our Docs () and Generate a Token ()"});
return next();
}
}
This is the middleware for the token, I am using this in my routers so then the token will authenticate. However, if I remove the if statement for checking if an API Token is present. It seem to fix the issue kinda but always authenticates with any key (even ones not saved in the db) and is still not properly fixed.
and an example for requesting endpoint with token on a Discord Command:
const { MessageEmbed } = require("discord.js");
const { get } = require("superagent");
exports.run = async (bot, message, args) => {
const { body } = await get(`https://example.com/generators/3000years`)
.query({ image: message.author.displayAvatarURL({ dynamic: true, size: 2048 }) })
.set("Authorization", `Bearer MY_TOKEN`);
const embed = new MessageEmbed()
.setTitle(`**3000 Years**`)
.attachFiles({ attachment: body, name: "3000years.png" })
.setImage("attachment://3000years.png")
.setColor(`#ed8a5c`);
message.channel.send(embed);
}
You can see that if I authorise with Superagent, it will not work and return a 401 Unauthorised in the console.
I would like to ask why this is doing this and if I did something wrong. Any help is appreciated.

Youtube upload failing with 403 - Download Service Forbidden

I'm using the google-api-nodejs-client and I'm trying to script up an uploader. I've finally got to the stage where everything is OAuth2 authenticated and I can make requests.
When trying to do an upload however, I'm getting 403 - Download Service Forbidden errors. Googling the error is returning utterly nothing (a rarity these days), and the official error code listing doesn't list it.
I've attached the JSON response below.
{ errors:
[ { domain: 'global',
reason: 'downloadServiceForbidden',
message: 'Download Service Forbidden' },
[length]: 1 ],
code: 403,
message: 'Download Service Forbidden' }
Has anyone seen this or knows what it means?
My upload code.
var yt_api = googleapis.discover('youtube', 'v3');
var auth_scopes = [
"https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.upload",
"https://www.googleapis.com/auth/youtubepartner"
]
var authClient = new googleapis.OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
//performs the authorisation with the above scopes
ensureAuthorisation(authClient, doRequest);
function doRequest() {
log.msg('Executing...');
yt_api.execute(function(err, client){
// open the video as a stream
var buffer = fs.readFileSync('../files/test.mp4');
client
.youtube.videos.insert({part: "contentDetails", mine: true})
.withAuthClient(authClient)
.withMedia('video/*', buffer)
.execute(function(err, response){
if (err) {
log.err("Error in upload");
dumpObj(err);
} else {
log.msg("Succeeded!");
}
});
});
}
Thanks!

Resources