Send a direct message to someone's rocketChat account using rocketChat API - rocket.chat

Is it possible to send a direct message from my RocketChat Account to another account using RocketChat API (RocketChat Rest API)?
I've looked around the API documentation but I didn't find what I need.

I used code below:
let RocketChat = require('rocketchat-nodejs').Client;
let Client = new RocketChat({
host: 'myHost',
port: 80,
scheme: 'http',
username: 'myUser',
password: 'myPass'
});
let Authentication = Client.Authentication();
let Users = Client.Users();
let Chat = Client.Chat();
Client.login().then(() => {
Authentication.me().then((result) => {
Users.list({ userId: 'muUser' }).then((result) => {
var list = result;
Chat.postMessage({ roomId: list.users[0]._id, text: 'test'})
.then((result) => {
})
});
});
}).catch((error) => {
console.log(error);
});

Related

How to work on 2FA when I am trying to log in into an account using Cypress?

I want to log in into an account, but I am receiving 2FA and to confirm the new device I am getting emails in my inbox, and I am not able to login in into account.
Anyone, can you please tell me how to handle this or if I can do something with MailSlurp in Cypress?
I short, I want to open the website, fill in username, pw, and login into the account successfully even after I get 2FA dialog box popping out, where the 2FA confirmation email is getting into my email inbox.
Thanks in advance and I appreciate your help.
Best,
Preeti D
MailSlurp is fine but you can use Twilio as well, here is my working example source code
const accountSid = 'AC793683c4982a14f01714321bd3f90ca7';
const authToken = '819068e54369ac58bb8aad976fa517bc';
const githubEmail = 'your_github_email'
const githubPassword = 'your_github_password'
describe('Login with github credentials', () => {
beforeEach(()=>{
cy.visit('https://github.com/login');
cy.get('#login_field').type(githubEmail);
cy.get('#password').type(githubPassword);
cy.get('input[type="submit"]').click()
})
it('Get SMS and apply it in 2FA form', () => {
cy.request({
method: 'GET',
url: `https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`,
auth: {
username: accountSid,
password: authToken,
AuthMethod: 'BasicAuth',
}
})
.its('body').then((res) => {
cy.wait(1500) //wait for SMS
const otpcode = res.messages[0].body.substring(0, 6)
cy.get('#otp').type(otpcode);
cy.url().should('eq', 'https://github.com/');
})
});
});

"[Network] undefined" when trying to use subscriber - URQL

I am trying to set up a subscriber to log some output on the creation of a new Message.
Currently using Urql, with ApolloServerExpress on the backend.
I am receiving an error from the useSubscription method which I am logging to the console :
message: "[Network] undefined"
name: "CombinedError"
I know for sure my backend is working as I can subscribe using the Graphiql playground just fine.
As far as front end goes, I have followed almost exactly as the example in the Urql docs.
WS Client:
const wsClient = createWSClient({
url: "ws://localhost:4000/graphql",
});
Subscriber Exchange:
subscriptionExchange({
forwardSubscription(operation) {
return {
subscribe: (sink) => {
const dispose = wsClient.subscribe(operation, sink);
return {
unsubscribe: dispose,
};
},
};
},
}),
MessageList Component:
const newMessages = `
subscription Messages {
newMessage {
content
status
sender {
id
email
}
recipient {
id
email
}
}
}
`;
...
const handleSub = (messages: any, newMessage: any) => {
console.log("Messages: ", messages);
console.log("newMessages: ", newMessage);
};
const [res] = useSubscription({ query: newMessages }, handleSub);
console.log("Res: ", res);
I was getting the same error when using subscriptions with urql. In my case, I was able to do console.log(error.networkError); which gave a much more helpful error message than [Network] undefined.
You can read more about errors in urql here.
The error I got from error.networkError was:
Event {
"code": 4400,
"isTrusted": false,
"reason": "{\"server_error_msg\":\"4400: Connection initialization failed: Missing 'Authorization' or 'Cookie' header in JWT authenticati",
}
I was able to fix it by adding authentication to my subscription exchange setup. Here's the code I'm using now:
const wsClient = createWSClient({
url: "wss://your-api-url/graphql",
connectionParams: async () => {
// Change this line to however you get your auth token
const token = await getTokenFromStorage();
return {
headers: {
Authorization: `Bearer ${token}`,
},
};
},
});
Ended up chalking graphql-ws and switched over to subscriptions-transport-ws.
Fixed my issues.

Authorize GMail API with JWT

I'm trying to send an email through the gmail API from a Node.js application. I had this working, following the documentation and using the node-mailer package. However, I noticed that when we change our organizations password, the connection is no longer good (which makes sense). I'm therefore trying to authorize with a JWT instead.
The JWT is correctly generated and posted to https://oauth2.googleapis.com/token. This request then returns an access_token.
When it comes time to write and send the email, I tried to simply adapt the code that was previously working (at the time with a client_secret, client_id and redirect_uris):
const gmail = google.gmail({ version: 'v1', auth: access_token });
gmail.users.messages.send(
{
userId: 'email',
resource: {
raw: encodedMessage
}
},
(err, result) => {
if (err) {
return console.log('NODEMAILER - The API returned: ' + err);
}
console.log(
'NODEMAILER Sending email reply from server: ' + result.data
);
}
);
The API keeps returning Error: Login Required.
Does anyone know how to solve this?
EDIT
I've modified my code and autehntication to add the client_id and client_secret:
const oAuth2Client = new google.auth.OAuth2(
credentials.gmail.client_id,
credentials.gmail.client_secret,
credentials.gmail.redirect_uris[0]
);
oAuth2Client.credentials = {
access_token: access_token
};
const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
gmail.users.messages.send(
{
userId: 'email',
resource: {
raw: encodedMessage
}
},
(err, result) => {
if (err) {
return console.log('NODEMAILER - The API returned: ' + err);
}
console.log(
'NODEMAILER Sending email reply from server: ' + result.data
);
}
);
But now the error is even less precise: Error: Bad Request
Here's the final authorization code that worked for me:
var credentials = require('../../credentials');
const privKey = credentials.gmail.priv_key.private_key;
var jwtParams = {
iss: credentials.gmail.priv_key.client_email,
scope: 'https://www.googleapis.com/auth/gmail.send',
aud: 'https://oauth2.googleapis.com/token',
exp: Math.floor(new Date().getTime() / 1000 + 120),
iat: Math.floor(new Date().getTime() / 1000),
sub: [INSERT EMAIL THAT WILL BE SENDING (not the service email, the one that has granted delegated access to the service account)]
};
var gmail_token = jwt.sign(jwtParams, privKey, {
algorithm: 'RS256'
});
var params = {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: gmail_token
};
var params_string = querystring.stringify(params);
axios({
method: 'post',
url: 'https://oauth2.googleapis.com/token',
data: params_string,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(response => {
let mail = new mailComposer({
to: [ARRAY OF RECIPIENTS],
text: [MESSAGE CONTENT],
subject: subject,
textEncoding: 'base64'
});
mail.compile().build((err, msg) => {
if (err) {
return console.log('Error compiling mail: ' + err);
}
const encodedMessage = Buffer.from(msg)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
sendMail(encodedMessage, response.data.access_token, credentials);
});
});
So that code segment above uses a private key to create a JSON Web Token (JWT), where: iss is the service account to be used, scope is the endpoint of the gmail API being accessed (this must be preauthorized), aud is the google API oAuth2 endpoint, exp is the expiration time, iat is the time created and sub is the email the service account is acting for.
The token is then signed and a POST request is made to the Google oAuth2 endpoint. On success, I use the mailComposer component of NodeMailer to build the email, with an array of recipients, a message, a subject and an encoding. That message is then encoded.
And here's my sendMail() function:
const oAuth2Client = new google.auth.OAuth2(
credentials.gmail.client_id,
credentials.gmail.client_secret,
credentials.gmail.redirect_uris[0]
);
oAuth2Client.credentials = {
access_token: access_token
};
const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
gmail.users.messages.send(
{
userId: 'me',
resource: {
raw: encodedMessage
}
},
(err, result) => {
if (err) {
return console.log('NODEMAILER - The API returned: ' + err);
}
console.log(
'NODEMAILER Sending email reply from server: ' + result.data
);
}
);
In this function, I am creating a new googleapis OAuth2 object using the credentials of the service account (here stored in an external file for added security). I then pass in the access_token (generated in the auth script with the JWT). The message is then sent.
Pay attention to the userId: 'me' in the sendMail() function, this was critical for me.
This is the way I was able to only use googleapis package instead of axios + googleapis with your service account. You will need domain wide authority for this account with the scope used below associated with it. Follow this to do that https://support.google.com/a/answer/162106?hl=en
You can also use the mailComposer example up above to create the email. keys is the service_credentials.json file you get when making this service account
const { google } = require('googleapis');
const scope = ["https://www.googleapis.com/auth/gmail.send"];
const client = new google.auth.JWT({
email: keys.client_email,
key: keys.private_key,
scopes: scope,
subject: "emailToSendFrom#something.com",
});
await client.authorize();
const gmail = google.gmail({ version: 'v1', auth: client});
const subject = '🤘 Hello 🤘';
const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
const messageParts = [
'From: Someone <emailToSendFrom#something.com>',//same email as above
'To: Someone <whoever#whoever.com>',
'Content-Type: text/html; charset=utf-8',
'MIME-Version: 1.0',
`Subject: ${utf8Subject}`,
'',
'This is a message just to say hello.',
'So... <b>Hello!</b> 🤘❤️😎',
];
const message = messageParts.join('\n');
// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
const res = await gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: encodedMessage,
},
});
console.log(res.data);

Social authentication in GraphQL

I am creating a backend which relies in Express and GraphQL which will serve clients apps (android and react).
I have been following this article on how to nail social authentication in GraphQL using passport.js.
The article uses passport-google-token strategy and is based on Apollo-server but personally I prefer to use express-graphql.
After setting my android app to use google auth and try to send mutation to server I get this error
Google info: { InternalOAuthError: failed to fetch user profile
at E:\_Projects\myProject\myProject-backend\node_modules\passport-google-token\lib\passport-google-token\strategy.js:114:28
at passBackControl (E:\_Projects\myProject\myProject-backend\node_modules\oauth\lib\oauth2.js:132:9)
at IncomingMessage.<anonymous> (E:\_Projects\myProject\myProject-backend\node_modules\oauth\lib\oauth2.js:157:7)
at IncomingMessage.emit (events.js:194:15)
at endReadableNT (_stream_readable.js:1125:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'InternalOAuthError',
message: 'failed to fetch user profile',
oauthError:
{ statusCode: 401,
data:
'{\n "error": {\n "code": 401,\n "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",\n "status": "UNAUTHENTICATED"\n }\n}\n' } }
I believe token I pass maybe does not reach where it supposed but I cant figure out how to solve.
I have tested my token here https://oauth2.googleapis.com/tokeninfo?id_token=MyToken and they are working correctly.
Here is graphQL config in app.js
app.use('/graphql', graphqlHTTP((req, res) => ({
schema,
graphiql: true,
context: {req, res}
})));
Here is google auth mutation
googleAuth: {
type: authPayLoad,
args: {token: {type: new GraphQLNonNull(GraphQLString)}},
async resolve(_, {token}, {req, res}) {
req.body = {
...req.body,
access_token: token,
};
try {
const {data, info} = await authenticateGoogle(req, res);
console.log("Google data: ", data);
if (data) {
const user = await User.upsertGoogleUser(data);
if (user) {
return ({
name: user.name,
username: user.username,
token: user.generateJWT(),
});
}
}
if (info) {
console.log("Google info: ", info);
switch (info.code) {
case 'ETIMEDOUT':
return (new Error('Failed to reach Google: Try Again'));
default:
return (new Error('something went wrong'));
}
}
return (Error('server error'));
} catch (e) {
console.log("Error: ", e);
return e
}
},
},
And here is my auth controller
const passport = require('passport');
const {Strategy: GoogleTokenStrategy} = require('passport-google-token');
// GOOGLE STRATEGY
const GoogleTokenStrategyCallback = (accessToken, refreshToken, profile, done) => done(null, {
accessToken,
refreshToken,
profile,
});
passport.use(new GoogleTokenStrategy({
clientID: 'MY_CLIET_ID',
clientSecret: 'SERVER-SECRET'
}, GoogleTokenStrategyCallback));
module.exports.authenticateGoogle = (req, res) => new Promise((resolve, reject) => {
passport.authenticate('google-token', {session: false}, (err, data, info) => {
if (err) reject(err);
resolve({data, info});
})(req, res);
});
I expected when client app submit mutation with token as arg the request will be sent to google and returns user data. How do I solve this.
passport-google-token is archived and seems deprecated to me. Why don't you try passport-token-google.
It can be used in similar way.
passport.use(new GoogleStrategy({
clientID: keys.google.oauthClientID,
clientSecret: keys.google.oauthClientSecret
},
function (accessToken, refreshToken, profile, done) {
return done(null, {
accessToken,
refreshToken,
profile,
});
}
));
module.exports.authenticate = (req, res) => new Promise((resolve, reject) => {
passport.authenticate('google-token', {session: false}, (err, data, info) => {
if (err) reject(err);
resolve({data, info});
})(req, res);
});
Hope this helps.

Programmatically upload videos to YouTube using FWT authentication

Seems like uploading videos to Youtube via its API is restricted to user explicit authorization, and all points that this is only possible via OAuth2 instead of FWT.
Using the V3 API I'm getting a 401 response code, however I can perform read-only operations, like fetch playlists etc...
For server-to-server tasks automation OAuth is not the best solution.
Here's is the test code using node.js:
var fs = require('fs')
var google = require('googleapis')
var youtube = google.youtube('v3')
var authClient = new google.auth.JWT(
'service-account-email#developer.gserviceaccount.com',
'path/to/key.pem',
null,
['https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.upload'])
authClient.authorize(function (err, tokens) {
if (err) {
return console.log(err)
}
google.options({ auth: authClient })
youtube.videos.insert({
media: {
body: fs.createReadStream('video.mp4')
},
autoLevels: true,
part: 'status,snippet',
mediaType: 'video/mp4',
resource: {
snippet: {
title: 'test video',
description: 'This is a test video uploaded from the YouTube API'
},
status: {
privacyStatus: 'public'
}
}
}, function (err, res) {
if (err) {
return console.error(err)
}
console.log('Upload done!')
})
})
Google API node.js client original example:
https://github.com/google/google-api-nodejs-client/blob/master/examples/jwt.js

Resources