i want collect news from different channels and echo them in a second channel, with the code i can read channels(not all but most).
I stuck now on the echo problem and have no clue about how i can do this, mtproto is completely new to me, thanks.
Im using the following code i have from another stackoverflow question.
const { MTProto, getSRPParams } = require('#mtproto/core');
const prompts = require('prompts');
const api_id = 'xxxxx';
const api_hash = 'xxxxx';
async function getPhone() {
return (await prompts({
type: 'text',
name: 'phone',
message: 'Enter your phone number:'
})).phone
}
async function getCode() {
// you can implement your code fetching strategy here
return (await prompts({
type: 'text',
name: 'code',
message: 'Enter the code sent:',
})).code
}
async function getPassword() {
return (await prompts({
type: 'text',
name: 'password',
message: 'Enter Password:',
})).password
}
const mtproto = new MTProto({
api_id,
api_hash,
});
function startListener() {
console.log('[+] starting listener')
mtproto.updates.on('updates', ({ updates }) => {
const newChannelMessages = updates.filter((update) => update._ === 'updateNewChannelMessage').map(({ message }) => message) // filter `updateNewChannelMessage` types only and extract the 'message' object
for (const message of newChannelMessages) {
// printing new channel messages
console.log(`[${message.to_id.channel_id}] ${message.message}`)
}
});
}
// checking authentication status
mtproto
.call('users.getFullUser', {
id: {
_: 'inputUserSelf',
},
})
.then(startListener) // means the user is logged in -> so start the listener
.catch(async error => {
// The user is not logged in
console.log('[+] You must log in')
const phone_number = await getPhone()
mtproto.call('auth.sendCode', {
phone_number: phone_number,
settings: {
_: 'codeSettings',
},
})
.catch(error => {
if (error.error_message.includes('_MIGRATE_')) {
const [type, nextDcId] = error.error_message.split('_MIGRATE_');
mtproto.setDefaultDc(+nextDcId);
return sendCode(phone_number);
}
})
.then(async result => {
return mtproto.call('auth.signIn', {
phone_code: await getCode(),
phone_number: phone_number,
phone_code_hash: result.phone_code_hash,
});
})
.catch(error => {
if (error.error_message === 'SESSION_PASSWORD_NEEDED') {
return mtproto.call('account.getPassword').then(async result => {
const { srp_id, current_algo, srp_B } = result;
const { salt1, salt2, g, p } = current_algo;
const { A, M1 } = await getSRPParams({
g,
p,
salt1,
salt2,
gB: srp_B,
password: await getPassword(),
});
return mtproto.call('auth.checkPassword', {
password: {
_: 'inputCheckPasswordSRP',
srp_id,
A,
M1,
},
});
});
}
})
.then(result => {
console.log('[+] successfully authenticated');
// start listener since the user has logged in now
startListener()
});
})
Related
Trying to write a query for DynamoDB and learn promises etc. The console.log(resp.Items) returns the object that I am looking for so I think my query is formatted correctly. I get a status 200 back with an empty object.
I have read up for a few days and tried to implement various changes to the code by nothing is returning the object resp.Items. I am guessing the function is returning before the const is updated with the data but I am not sure why the console.log works.
const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB()
const getTechs = async () => {
try {
const resp = await dynamodb
.query({
ExpressionAttributeValues: {
':tech': { S: 'TECH#' },
},
KeyConditionExpression: 'PK = :tech',
TableName: process.env.TABLE_NAME,
ScanIndexForward: true,
})
.promise()
console.log(resp.Items)
if (!resp.Items) {
return {
error: 'No Techs in the DB',
}
}
return {
tech: resp.Items,
}
} catch (error) {
console.log('Error retrieving Tech List')
console.log(error)
return {
error: 'Could not retrieve Tech List',
}
}
}
handler func
const { makeHandler } = require('./utils')
const { getTechs } = require('../data')
// const { Tech } = require('../entities')
const inputSchema = {
type: 'object',
properties: {
pathParameters: {
type: 'object',
properties: {
tech: { type: 'string' },
},
required: ['tech'],
},
},
required: ['pathParameters'],
}
const handler = async (event) => {
const { techs, error } = await getTechs()
const statusCode = error ? 500 : 200
const body = error ? JSON.stringify({ error }) : JSON.stringify({ techs })
return {
statusCode,
body,
}
}
module.exports.handler = makeHandler({ handler })
executeTransactWrite func
const executeTransactWrite = async ({ tech, params }) => {
const transactionRequest = tech.transactWriteItems(params)
let cancellationReasons
transactionRequest.on('extractError', (response) => {
try {
cancellationReasons = JSON.parse(
response.httpResponse.body.toString()
).CancellationReasons
} catch (err) {
// suppress this just in case some types of errors aren't JSON parseable
console.error('Error extracting cancellation error', err)
}
})
return new Promise((resolve, reject) => {
transactionRequest.send((err, response) => {
if (err) {
err.cancellationReasons = cancellationReasons
return reject(err)
}
return resolve(response)
})
})
}
module.exports = {
executeTransactWrite,
makehandler func
const middy = require('middy')
const {
jsonBodyParser,
validator,
httpErrorHandler,
} = require('middy/middlewares')
const makeHandler = ({ handler, inputSchema }) =>
middy(handler)
.use(jsonBodyParser())
.use(validator({ inputSchema }))
.use(httpErrorHandler())
module.exports = { makeHandler }
I'm working on the user registration functionality of an application using Typescript and Redux Toolkit. When I make the fetch request to the signup endpoint, a new user is saved to the database I've connected, but I keep entering the catch error block.
export const registerUser = createAsyncThunk(
"user/registerUser",
async (form: { username:string, password:string }, thunkAPI) => {
try {
const response = await fetch('/api/auth/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userInfo: {
username: form.username,
password: form.password
}
}),
});
if (response.status === 200) return 200;
else return 400;
} catch (e) {
console.log('Error')
}
}
);
I've tried logging the response to the console a number of ways
const data = await response.json() console.log(data)
But have had no luck. I think this is an error with how I've done my fetch request using createAsyncThunk but haven't been able to figure out what I've missed.
This is the code for the initial state and slice:
interface UserState {
userProfile: {
id: number | null;
},
registration: {
status: 'loaded' | 'loading'
}
}
const initialState : UserState = {
userProfile: {
id: null,
},
registration: {
status: 'loaded'
}
};
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
},
extraReducers: (builder) => {
builder.addCase(registerUser.fulfilled, (state) => { state.registration.status = 'loaded' }),
builder.addCase(registerUser.rejected, (state) => { state.registration.status = 'loaded' }),
builder.addCase(registerUser.pending, (state) => { state.registration.status = 'loading' })
}
})
And here is the code for the function where the action is dispatched on the UI
const handleRegister= async () => {
if (!username) return alert('Username field was left empty');
if (!password) return alert('Password field was left empty');
const {payload} : any = await dispatch(registerUser({ username: username, password: password}));
if (payload === 200) {
alert('Successfully registered. Redirecting to dashboard');
return navigate('/dashboard');
} else { return alert('User creation unsuccessful'); }
}
Appreciate any help as I've looked through many other posts but haven't been able to resolve my issue.
I am new to websockets and socket.io. I have a few challenges>
I have developed the application with react and nodejs using socket.io.
useEffect(() => {
const getAllChats = async (token) => {
try {
setLoading(true)
const res = await getChats(token)
if (res) {
setChats(res)
setLoading(false)
}
} catch (err) {
console.log(err)
setLoading(false)
}
}
getAllChats(user.token)
}, [])
export const getChats = (token) => {
return request(`/api/v1/chats`, {
token,
method: 'GET',
})
}
The above code is used to fetch the chat from the backend.
At the backend, I have the code:
exports.getAllChats = catchAsync(async (req, res, next) => {
const user = await Chat.findOne({ user: req.user._id }).populate(
'chats.messagesWith'
)
let chatsToBeSent = []
if (user.chats.length > 0) {
chatsToBeSent = await user.chats.map((chat) => ({
messagesWith: chat.messagesWith._id,
firstName: chat.messagesWith.firstName,
lastName: chat.messagesWith.lastName,
profilePicUrl: chat.messagesWith.profilePicUrl,
lastMessage: chat.messages[chat.messages.length - 1].msg,
date: chat.messages[chat.messages.length - 1].date,
}))
}
return res.json(chatsToBeSent)
})
How can I make new messages remain at the top of the list? Presently, It is always ordered by created date
This is also a question on Auth0 node-auth0 library. The use case is that I am using the Auth0 create Actions API through Terraform and want to be able to writes tests against the Actions.
In this example I want to be able to test the onExecutePostLogin without using real values.
// auth0-post-login.js
exports.onExecutePostLogin = async (event, api) => {
const userId = event.user.user_id
const ManagementClient = require('auth0').ManagementClient
const management = new ManagementClient({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
audience: `https://${event.secrets.domain}/api/v2/`,
scope: 'read:users',
})
const params = { id: userId, page: 0, per_page: 50, include_totals: false }
let userPermissions = await management.getUserPermissions(params)
const map = require('array-map')
const permissions = map(userPermissions, function(permission) {
return permission.permission_name
})
api.accessToken.setCustomClaim('https://example.com/access', permissions.join(' '))
}
One of the main issues is that the functions like getUserPermissions is created through their utility wrapper:
utils.wrapPropertyMethod(ManagementClient, 'getUserPermissions', 'users.getPermissions');
This causes jest to have issues finding the functions.
I did something similar as stsmurf to mock the response of the Auth0 methods.
I have a file where I store my helper methods like "find a role by its name"
// helper.ts
import { ManagementClient } from 'auth0';
export const getRoleByName = async (roleName: string) => {
const api = new ManagementClient({
clientId: clientId,
clientSecret: clientSecret,
domain: domain,
});
const roles = await api.getRoles();
const role = roles.find((r) => r.name == roleName);
if (!role) throw new Error('Role not found');
return role;
};
// helper.test.ts
import { Role } from 'auth0';
import { getRoleByName } from './helpers';
const mockGetRoles = jest.fn();
jest.mock('auth0', () => {
return {
ManagementClient: jest.fn().mockImplementation(() => {
return {
getRoles: mockGetRoles,
};
}),
};
});
describe('Get role', () => {
beforeAll(() => {
const dummyRoles: Role[] = [
{ id: 'fake_id_1', description: 'Fake role nr 1', name: 'Fake Role 1' },
{ id: 'fake_id_2', description: 'Fake role nr 2', name: 'Fake Role 2' },
];
mockGetRoles.mockImplementation(() => dummyRoles);
});
it('can return a role if it exists', async () => {
const expectedResult: Role = {
id: 'fake_id_1',
description: 'Fake role nr 1',
name: 'Fake Role 1',
};
const result = await getRoleByName('Fake Role 1');
expect(expectedResult).toEqual(result);
});
it('will throw an error when a role is not found', async () => {
await expect(getRoleByName('Fake Role 3')).rejects.toThrowError();
});
});
In order to get to functions like getUserPermissions I needed to override the implementation of the ManagementClient. This allowed me to then define getUserPermissions as a mock function.
import { onExecutePostLogin } from './auth0-post-login'
const mockManagementClient = jest.fn()
const mockGetUserPermissions = jest.fn()
jest.mock('auth0', () => {
return {
ManagementClient: (opts) => {
mockManagementClient(opts)
return {
getUserPermissions: (params) => {
return mockGetUserPermissions(params)
},
}
},
}
})
describe('onExecutePostLogin', () => {
const mockSetCustomClaim = jest.fn()
beforeEach(() => {
mockSetCustomClaim.mockClear()
mockManagementClient.mockClear()
mockGetUserPermissions.mockClear()
mockGetUserPermissions.mockReturnValue([
{
permission_name: 'read:foo',
},
{
permission_name: 'update:bar',
},
])
})
const event = {
user: {
user_id: 'abcd123',
},
secrets: {
domain: 'test-example.us.auth0.com',
clientId: 'a-client-id',
clientSecret: 'a-client-secret',
},
}
const api = {
accessToken: {
setCustomClaim: mockSetCustomClaim,
},
}
it('initializes a ManagementClient', async () => {
await onExecutePostLogin(event, api)
expect(mockManagementClient).toHaveBeenCalledWith({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
audience: `https://${event.secrets.domain}/api/v2/`,
scope: 'read:users',
})
})
it('gets users permissions', async () => {
await onExecutePostLogin(event, api)
expect(mockGetUserPermissions).toHaveBeenCalledWith(
{ id: event.user.user_id, page: 0, per_page: 50, include_totals: false },
)
})
it('sets custom claims', async () => {
await onExecutePostLogin(event, api)
const expectedPermissions = 'read:foo update:bar'
expect(mockSetCustomClaim).toHaveBeenCalledWith(
'https://example.com/access', expectedPermissions,
)
})
})
I'm New to unit test and trying to test my controller method.my project architecture design is as follow
Controller->Service->Model.
My test scenarios :
Pass correct parameters to controller method and test success response
Pass Invalid parameters to controller method and test error response
When i going to test scenario 1 ,according to my understanding i want to mock my programService and it return values.I have write test as follow and got errors.
I would really appreciate some one can fix this
ProgramsController.js
const ProgramService = require('../../services/program/programService');
class ProgramsController {
constructor() {
this.programService = new ProgramService();
}
async subscribe(req, res) {
try {
const { userId, uuid, msisdn, body: { programId } } = req;
const data = { userId, programId, msisdn, uuid }
const subscribe = await this.programService.subscribeUser(data);
res.json({
status: true,
message: 'Success',
friendly_message: constant.MSG.SUBSCRIPTION,
data: subscribe
})
} catch (error) {
res.status(500)
.json({
status: false,
message: 'Fail',
friendly_message: constant.MSG.SUBSCRIPTION_FAIL
})
}
}
}
ProgramService.js
class ProgramService {
constructor() {
this.subscriber = new Subscriber();
this.subsciberProgram = new SubsciberProgram()
}
async subscribeUser(data) {
try {
const { msisdn, userId, programId, uuid } = data;
...
return subscribedData;
} catch (error) {
throw error;
}
}
}
module.exports = ProgramService;
test.spec.js
const ProgramsService = require('../src/services/program/programService')
const ProgramsController = require('../src/controllers/programs/programsController')
const programController = new ProgramsController()
const programsService = new ProgramsService()
beforeAll(() => {
db.sequelize.sync({ force: true }).then(() => { });
});
const mockRequest = (userId, uuid, msisdn, body) => ({
userId,
uuid,
msisdn,
body,
});
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
const serviceRecord = { userId: 1, programId: 1, msisdn: '56768382967', uuid: '46651a19-3ef1-4149-818e-9bd8a5f359ef' };
const fakeServiceReturn = { program_id: 1, amount: 5, no_of_questions: 10 }
describe('Subscribe', () => {
test('should return 200', async () => {
const req = mockRequest(
1,
'56768382967',
'46651a19-3ef1-4149-818e-9bd8a5f359ef',
{ 'programId': 1 }
);
const res = mockResponse();
const spy = jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => serviceRecord);
await programController.subscribe(req, res);
expect(programsService.subscribeUser()).toHaveBeenCalledWith(fakeServiceReturn);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith({
status: true,
message: 'Success',
friendly_message: 'successfull get data',
data : { program_id: 1, amount: 5, no_of_questions: 10 }
});
spy.mockRestore();
});
});
how can i mock programService.subscribeUser and test success response?
This mock should return a promise:
jest.spyOn(programsService, 'subscribeUser').mockImplementation(() => Promise.resolve(serviceRecord));