Making my own API, confused on how to authenticate with server - javascript

I'm trying to make a Discord bot that retrieves a player's stats from the Ubisoft Rainbow Six stat website. I've worked with APIs before and I know the basics of Node and making GET requests to certain URLs. I monitored the network activity for a player's profile and found the specific URL that I need to perform a request on but I get a HTTP 400 error. I'm assuming this is because I've never authenticated with the server who I am. So I read up on authentication and the like and figured that all I had to do was include in the request header my username and password for the website(at this point I should mention that the site makes you login to retrieve player's stats). I went on Postman and included my username/password for Basic Auth and OAuth2 and I still get a HTTP 400 error, so there's obviously got to be more that I'm missing. It seems that in the network activity that some of the requests include a token, which I'm assuming is some sort of session token. I'm just completely confused as to what I'm supposed to do, as I'm kind of diving head first into this but I would really appreciate it if someone could provide some resources where I could try to fill in the gaps or help me resolve the issue. Code at the moment using pure JS/Node:
//import
const https = require('https');
const http = require('http');
//https://public-ubiservices.ubi.com/v3/profiles?namesOnPlatform=pope&platformType=uplay
var username = '';
var password = '';
var req_username = '';
//get session_id
function get_session_id(username, password) {
const options = {
host: 'public-ubiservices.ubi.com',
port: 443,
path: '/v3/profiles/sessions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic' + Buffer.from(username + ':' + password).toString('base64'),
'Ubi-AppId': '',
}
}
const req_session_id = https.request(options, res => {
let res_body = '';
res.on('data', data => {
res_body += data;
})
res.on('end', () => {
res_body = JSON.parse(res_body);
console.log(res_body);
})
});
req_session_id.end();
}
//retrieve player stats
function get_stats(req_username) {
const options = {
host: 'public-ubiservices.ubi.com',
port: 443,
path: `/v3/profiles?namesOnPlatform=${req_username}&platformType=uplay`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic' + Buffer.from(username + ':' + password).toString('base64'),
'Ubi-AppId': '',
}
}
const req_get_stats = https.request(options, res => {
let res_body = '';
res.on('data', data => {
res_body += data;
});
res.on('end', () => {
res_body = JSON.parse(res_body);
console.log(res_body);
});
});
req_get_stats.end();
}
get_session_id(username, password);
get_stats(req_username);

try this out:
https://www.npmjs.com/package/r6api.js
heres an example:
const R6API = require('r6api.js');
const r6api = new R6API('email', 'password');
const username = 'Daniel.Nt'
const platform = 'uplay';
const id = await r6api.getId(platform, username).then(el => el[0].userId);
const stats = await r6api.getStats(platform, id).then(el => el[0]);
console.log(`${username} has played ${stats.pvp.general.matches} matches.`);

Related

How to filnd Path to Sharepoint in NodeJs

I have a code that is supposed to connect to a server, but I am getting a 'Microsoft SharePoint Foundation Error' when I try to run it. What could be causing this error and how can I fix it?
Status 200
OK
`
Microsoft SharePoint Foundation Error.
User: please report details to this Web site's Webmaster.
Webmaster: please see the server's application event log for more details.
`
const adal = require('adal-node');
const clientId = '<myclientID>';
const clientSecret = '<myclientSecret>';
const resource = 'https://<domain>.sharepoint.com/';
const folderName = '';
const context = new adal.AuthenticationContext('https://login.windows.net/common');
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
if (err) {
// console.log('Błąd podczas pobierania tokenu dostępu: ' + err);
} else {
upload(tokenResponse.accessToken)
}
});
function upload(accessToken){
const fs = require('fs');
const axios = require('axios');
const filePath = './test.txt';
const sharepointSiteUrl = resource+'teams/<name_my_Sharepoint/';
const fileName = 'test.txt';
const folderName = '';
//add(url='${fileName}',overwrite=true)
const options = {
method: 'POST',
url: sharepointSiteUrl+ "/_api://<myclientID>",
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json;odata=verbose',
'Content-Type': 'application/json;odata=verbose'
},
data: fs.createReadStream(filePath)
};
axios(options)
.then((response) => {
console.log(response.status);
console.log(response.statusText);
console.log(response.data)
})
.catch((error) => {
console.log("test")
console.error(error);
});}

Bad respond when trying to get authentication token for Reddit api 'Application Only OAuth'

So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!

How can I redirect to home as soon as i get url?

Currently, I'm trying to use my company SSO(Oauth 2.0) Service,and I pass the url to the oauth service and
then I get the url with a code to get access token from front side, and then I pass the fetch
the code from client side url to backend server with the post, and then I get the code in server
side and redirect to the other url param in server side, i can get the user's information to client and server.
However, the client side URL show the code that i sent , so I want to know how to get rid of it.
and I searched a solution that i can redirect the page to another page, but I do not know how to .
and I want to know what i was doing is right way .
Thank you in advance.i hope it's not bad explanation
this below is what i tried :
client Side
var client_id =
"client_random_id";
var state_val = "RANDOM_STATE";
var redirectURI = "http://localhost:3000";
let api_url =
"https://www.??????/oauth2.0/authorize?response_type=code&client_id=" +
client_id +
"&redirect_uri=" +
redirectURI +
"&state=" +
state_val;
const logout = `https://www.??????/oauth2.0/Logout?client_id=${client_id}&logout_redirect_uri=${redirectURI}`;
const queryParams = new URLSearchParams(window.location.search);
const [userinfo, setuserinfo] = useState();
useEffect(() => {
fetch("http://localhost:5000/create", {
method: "post",
body: queryParams,
})
.then(response => response.json())
.then(json => {
setuserinfo(json);
})
.then("<Redirect to={routes.home.path}/>")
.catch(ex => {});
});
Server Side
app.post("/create", function (req, res) {
const code = req.body.code;
res.redirect(`/callback/?code=${code}`);
});
app.get("/callback", cors(), (req, res) => {
if (req.query.code !== null && req.query.code !== undefined) {
var token_url = "https://www.?????.kr/oauth2.0/token";
var options = {
url: token_url,
method: "POST",
form: {
grant_type: "authorization_code",
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirectURI,
code: req.query.code,
state: req.query.state,
},
};
request(options, function (error1, response1, body1) {
if (!error1 && response1.statusCode == 200) {
var tdata = JSON.parse(body1);
var options2 = {
url: "https://www.??????/oauth2.0/resource",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + tdata.access_token,
},
};
request(options2, function (error2, response2, body2) {
if (!error2 && response2.statusCode == 200) {
var rdata = JSON.parse(body2);
res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });
res.end(body2);
} else {
res.status(response2.statusCode).end();
console.log("error2 = " + response2.statusCode);
}
});
} else {
res.status(response1.statusCode).end();
console.log("error1 = " + response1.statusCode);
}
});
}
});
All you need is to change this part .then("<Redirect to={routes.home.path}/>")
to something like this
.then(() => {
window.location.replace("your url")
})
you could read more about replace here

How can get data from Node.js inside app.get to react.js?

Currently, I'm using sso(Oauth) service that my company has. And I'm trying to get the data from it .
And the process is like this:
when I click the button that has sso Link and client_id or something,
then the backend server get the code (URL query) and send the code(URL query) to sso and then get the token and userId or something.
and as soon as the token is sent, then website has to change to client side.
And I was trying to get the code(URL query) from node backend server.
however, I can not get the exact url which has the code(URL query),And I want to go back to the client.
So i use res.direct in node backend server.
and it's not working and I removed it so that I can know if i can get the data in client,
But the url is changed so I can't get the exact url in client server from backend.
So my question is that how should i get the exact url query from node to react?
and How can I redirect page to client side from backend ??
this is my code :
Client:
var client_id =
"clientId ??????????????";
var state_val = "RANDOM_STATE";
var redirectURI = "http://localhost:5000";
let api_url =
"https://www.ssoservice/oauth2.0/authorize?response_type=code&client_id=" +
client_id +
"&redirect_uri=" +
redirectURI +
"&state=" +
state_val;
useEffect(() => {
const apiCall = async () => {
const response = await axios.get(`http://localhost:5000`);
console.log(response);
setRedirectURL(response);
};
apiCall();
}, []);
// this is the code that i want to get the url query
return (
<a href={api_url}>
<button>
<FormatListBulletedIcon />
<p>SSO Login</p>
</button>
</a>
)
//go to sso service to get code
backend
app.get("/", cors(), (req, res) => {
// this url is what i want to get to client side
res.redirect("http://localhost:3000"); // this is not working
if (req.query.code !== null && req.query.code !== undefined) {
var token_url = "https://www.ssoservice/oauth2.0/token";
var options = {
url: token_url,
method: "POST",
form: {
grant_type: "authorization_code",
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirectURI,
code: req.query.code,
state: req.query.state,
},
};
request(options, function (error1, response1, body1) {
if (!error1 && response1.statusCode == 200) {
var tdata = JSON.parse(body1);
var options2 = {
url: "https://www.ssoservicer/oauth2.0/resource",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + tdata.access_token,
},
};
request(options2, function (error2, response2, body2) {
if (!error2 && response2.statusCode == 200) {
var rdata = JSON.parse(body2);
res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });
res.end(body2);
console.log(rdata);
//this is what i want to get
} else {
res.status(response2.statusCode).end();
console.log("error2 = " + response2.statusCode);
}
});
} else {
res.status(response1.statusCode).end();
console.log("error1 = " + response1.statusCode);
}
});
}
});

http 401 error when providing an access token the outlook api

I am trying to create a folder for a user, and I have been unsuccessful with api call attempts. My code is able to receive the correct access token, so I believe the be bug would be in createFolderTestFunction below.
async function redirectToDashboard() {
console.log("redirect to dashboard");
// var response = await requestTokenSilent();
var response;
if (!response || !response.status == 200) {
response = await requestTokenPopup();
}
if (response.accessToken) {
console.log(response);
createFolderTest(response.accessToken);
// location.href = hostname;
} else {
console.log("Unable to acquire token");
}
}
function createFolderTest(accessToken) {
var options = {
method: "POST",
headers: {
Authorization: accessToken,
"Content-Type": "application/json"
},
mode: "cors",
body: JSON.stringify({
displayName: "#COOLMONDAY"
})
};
var graphEndpoint = "https://outlook.office.com/api/v2.0/me/Inbox/";
fetch(graphEndpoint, options)
.then(resp => {
console.log(resp);
})
.catch(err => {
console.log(err);
});
}
A recommendation would be to get this working in Graph Explorer first. As this eliminates any issues with language being used and access token permissions.
https://developer.microsoft.com/en-us/graph/graph-explorer/preview
The Microsoft Graph endpoint is actually https://graph.microsoft.com/ , you can use the outlook url but moving forward Graph is where we invest in documentation, sdks and tooling.
As per the documentation https://learn.microsoft.com/en-us/graph/api/user-post-mailfolders?view=graph-rest-1.0&tabs=http
You should be using, you're missing 'mailfolders'
POST /me/mailFolders
You could also use our JavaScript SDK which makes mistakes like these a little easier with intellisense and strongly typed objects.
const options = {
authProvider,
};
const client = Client.init(options);
const mailFolder = {
displayName: "displayName-value"
};
let res = await client.api('/me/mailFolders')
.post(mailFolder);
https://learn.microsoft.com/en-us/graph/api/user-post-mailfolders?view=graph-rest-1.0&tabs=javascript

Categories