Using AWS cognito from plain JavaScript - javascript

Hoping someone can shed some light on using Cognito with plain JavaScript. No npm, no webpack, just plain JavaScript. I found a post that had a great example including the required AWS JavaScript libraries. I worked from this example until I ran into the problem of sign out not working. I thought perhaps the libraries in the example were out of date so I went looking for the latest. This is where things got confusing. In the example I had the following JavaScript libraries - amazon-cognito-identity.min.js, aws-cognito-sdk.min.js, and aws-sdk.min.js. I assume that aws-cognito-sdk must no longer exist? I updated the other two and see that there is an amazon-cognito-auth library. Do I need that? Anyhow with those three libraries the existing code no longer functions. I end up with errors like "AWSCognito is undefined" etc.
Hoping someone can point me in the right direction and show me where the downloads, documentation, etc for using Cognito in plain JavaScript are

Find hereunder a template I created for myself to work from. It is in "plain javascript" and in an angularjs app.
My template: https://github.com/PouncingPoodle/aws-cognito-angularjs/tree/master
based on: https://github.com/takanorig/aws-cognito-angularjs
Always make sure that you use the correct versions of scripts and the correlating apiVersion when you call a Lambda function for example
There might be bad practice involved but as far as I could research it should be all fine.

You can perform the logout using below code snippet. I haven't faced such strange errors while using this function.
var poolData = {
UserPoolId: '...', // Your user pool id here
ClientId: '...', // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: 'username',
Pool: userPool,
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.signOut();
if you want to make the user logout from all the devices that he has got logged in from, then you can replace the last line of previous code with below code line.
cognitoUser.globalSignOut(callback);
You can refer below article to get a better understanding about the usage of amazon-cognito-identity-js package.
https://medium.com/#sankharathnayaka/aws-cognito-authentication-without-using-amplify-8d0e3af997c2

Related

Slash Commands - Discord.js

I am getting an error when I am trying to run:
(node:9164) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'applications' of undefined
Here is my code:
const discord = require('discord.js');
const client = new discord.Client();
const guildId = '820368493017825333';
client.on('ready', async () => {
console.log('ready');
const commands = await client.api.
applications(client.user.id)
.guilds(guildId)
.commands.get();
console.log(commands);
});
client.login(require(`./config.json`).Token);
Issues With the Accepted Answer
The accepted answer is incorrect in several ways. I'll walk through the inaccuracies in that answer and highlight the more likely causes of this problem, for the sake of anyone that may stumble upon this question in the future (and would've been misled by the accepted answer into believing that Slash Commands cannot be implemented in discord.js).
Well, the answer is pretty simple here. According to Discord.js docs, Class Client doesn't have api property. That's why you have the undefined error.
Incorrect. The Client class does have an api property. Or rather, it inherits the api property from the BaseClient class that it extends. This can be found in the source code of BaseClient. It is true that this is not documented in the discord.js docs. That is intentional, as the api property is intended to be a private property, more for discord.js' own use than for general use. You may notice in the source code that the property is annotated with #private, which usually indicates that it will not appear in the docs. There are many such private properties and methods that exist in discord.js classes, which are undocumented but are usable in your own code.
It seems like the tutorial that you are looking at is a bit outdated, or probably the tutor adds this property manually because Discord.js have relevant classes, like Application and ClientApplication but I still don't see an api property there as well.
The tutorial that the OP was going off of was actually more up-to-date than the tutorials posted and used by the accepted answer. The Application and ClientApplication classes are not at all relevant, as neither can access Slash Commands. Nor did hundreds of different tutorials each implement their own api property that all work in exactly the same way; they were all using the api property included in the latest versions of discord.js.
If you want to implement commands to your Discord bot with slash support, just add the following code, after ready stage.
The accepted answer misunderstood what 'Slash Commands' are, and provided code simply for creating a command with a slash for a prefix. That is not what the Slash Command system is. Slash Commands allow you to do things such as documenting, autocompleting, and validating commands and command arguments that users are typing in, in real-time while they are entering their input.
Not it shouldn't. Actually, the Discord.js lib is updated more often, the [YouTube] creators do it with their videos. I have already placed in my answer, a relevant guide made by the Discord.js community.
Yes it should. Hundreds of tutorials used the same code as each other, containing the api property, in instructing developers on how to work with Slash Commands in unmodified discord.js. I am not sure what exactly was meant by this comment.
If you look at the actual source code of discord.js, you'll find that the latest versions use the client's api property several times internally, usually in methods that directly query the Discord API for information (such as .fetch() methods). If the api property is undefined and you are using the latest version of discord.js, then much of your bot would not be working properly. So the latest client class not having an api property is not the main issue, which leads us to what the main issue really is.
So What Is the Real Issue?
There truly isn't enough context provided in the question to know for sure what exactly was causing the issue in the question. However, we can narrow the cause down to a few potential suspects, especially given the information aforementioned. Double check these to ensure they are not causing your problem:
Discord.js version. The api property does not exist for versions older than v12. Make sure you are using the latest version of discord.js. This is most likely the cause of the issue.
Missing access. You need to give your bot the application.commands scope when generating its invite link, otherwise you cannot interact with or create Slash Commands. This shouldn't really cause the api property to be undefined and should give you a different error, but it's worth double-checking.
If working with Slash Commands in simple discord.js is still not working for you even after double-checking both of these potential issues, you may want to consider an alternate (and somewhat simpler) approach to implementing Slash Commands: the discord-slash-commands-client module.
You would initialize this module like so:
const interactions = require("discord-slash-commands-client");
const iclient = new interactions.Client(
"you unique bot token",
"your bots user id"
);
Then to get a list of all existing Slash Commands, as the code in this question is attempting to do, all you would need to do with this module is:
let commands = await iclient.getCommands();
A single, clean line. As simple as it gets. The only downside to this alternate approach is that this module may not stay up-to-date as reliably as discord.js itself does. However, it would certainly be helpful if you are not able to figure out how to get Slash Commands working in discord.js itself.
If you need more help on this or want to see a more complete implementation of either approach, this question has several good, working examples on how to get Slash Commands code working properly on your bot.
This answer is a outdated!
When it was accepted Discord haven't introduced truly /slash commands. So use the answer below, if you want to integrate or migrate to newest version of Discord.js
Well, the answer is pretty simple here. According to Discord.js docs, Class Client doesn't have api property. That's why you have the undefined error.
It seems like the tutorial that you are looking at is a bit outdated, or probably the tutor adds this property manually because Discord.js have relevant classes, like Application and ClientApplication but I still don't see an api property there as well.
If you are looking for a good guide, I might recommend you this one from the official Discord recommendation page.
If you want to implement commands to your Discord bot with slash support, just add the following code, after ready stage.
const prefix = '/'
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('Pong.');
}
})

Google Script API understanding

This is a two part question, regarding the Google Script API.
First, I can read the SDK/API reference, and execute examples successfully, via the "try now" feature. But, what I am missing a step in understanding when trying to build webApps (with limited javascript knowledge - admittedly). Namely, the SDK shows the syntax for many things but not in the way I would expect to use it within Javascript.
A concrete example of my problem: I am trying to create a simple function to return verification Codes (8-digit codes) from the Admin API. Here is an example function.
function getCodes(){
var userEmail = 'testuser#exampl.com';
var user = AdminDirectory.Users.list({userKey: userEmail}).verificationCodes;
Logger.log('User data:\n %s', JSON.stringify(user, null, 2));
}
naturally, the syntax for the AdminDirectory call is wrong, I get errors. I have tried many different variation, but without a proper understanding of the reference, I feel like I am just guessing (and I have guessed a lot).
Can someone throw me a bone? Thanks
Have a look at the Users resource
You will see that verificationCodes is not part of this resource
However, there is a way to retrieve verification codes: with VerificationCodes: list
To usew the latter, you need to provide the userEmail as parameter
So modify your request to:
AdminDirectory.VerificationCodes.list(userEmail).items.forEach(function(item){Logger.log('Code: ' + item.verificationCode)});

Combining Galen and Protractor frameworks

The Story
We've been using Protractor framework extensively and have established a rather large test codebase. We've also been following the Page Object pattern to organize our tests.
Recently, we've started to use the Galen framework to fill the gap of visual/layout/responsive design testing. We really like the framework and would like to proceed with using it more.
The biggest problem right now is Page Objects. Both frameworks have its own ways of defining page objects.
Here is an example Protractor page object:
var LoginPage = function () {
this.username = element(by.id("username"));
this.password = element(by.id("password"));
this.loginButton = element(by.binding("buttonText"));
};
module.exports = new LoginPage();
And, here is a sample Galen page object:
this.LoginPage = $page("Login page", {
username: '#username',
password: '#password',
loginButton: 'button[ng-click*=login]'
});
Currently, we are duplicating the locators and repeating ourselves - violating the DRY principle. And, the other follow-up issue is that Galen only supports "by css", "by id" or "by xpath" location techniques at the moment - which means page objects don't map one-to-one.
The Question
Is there a way to avoid repeating page objects and element locators combining both Protractor and Galen together?
Given the information available, I don't see a direct way to combine it.
However, Galen and Protractor are available on Github and I don't see any bigger obstacle from aligning/forking/modifying them to what you need.
The best shot I see is to contribute to Galen framework and extend their GalenPages.js with a mapping functionality to Protractor Page Objects. Though there are 600+ lines of code in that .js-file, it seems doable within reasonable efforts.
At least to open an issue in the Galen GitHub project in that direction would sure be worth the effort.

Making Node.js work with tree-model-js

Thanks for the tree-model-js, great lib!
I am new to Node.js and I'm trying to import the tree-model. All NPMed successfully.
I am trying to make Node.js work with your library. I guess it is as much a Node question and not so much tree-model issue, but asking anyway just in case the lib needs to be changed for it.
I have the following:
var tm = require('tree-model');
//all good so far.
but when I am trying to recreate the code that works on my webpage
//is this how I access it?
tm.tree = new TreeModel();
it is giving me an error. Do you have any examples on how this can be achieved in Node?
Essentially I am trying to do this within my main.js Node file but struggling to understand how to access the variables/functions. It all works well when on a webpage when I do the following:
tree = new TreeModel();
root = tree.parse({ name: "Ben and Jerry" });
Any examples much appreciated. Please keep in mind that I am new to Node.js and somehow rookie on javascript. I learn better from examples so feel free to point me in the right direction.
The error is quite simple: TreeModel is not defined.
require('tree-model') returns new Node(this.config, model) and in your code, the Node is assigned to variable tm.
You should use new tm() to instantiate Node or change the variable name to TreeModel

Writing git API for javascript node module

Hi recently I have to implement a git API for a node module, so we can have version control through programmatic interface. I came upon this post to find some good modules that I can use.
However, after playing around with some of them, I realized that none of them provide the feature of querying the commit history of a single file (like calling 'git log --follow '). I would like to extend that feature into my module but since I have no experience before, does anyone know where I should start?
The libraries you mentioned should be a good starting point. Take node-git's lib/git.js file for example. There you can find the following lines:
// Call the native git binary
Git.prototype.call_git = function(prefix, command, postfix, options, args, callback) {
// ...
This is a good starting point to understand how the author maps Node functions on system calls and and allows the callback to work with the output.
I would start a fork of the project. Look for the log function in the same file, which starts like
Git.prototype.log = function(commit, path, options, callback) {
Copy the function, give it a proper name and try to adopt it to meet your needs.
If you succeed and like to help, you could start a pull request on GitHub to help the author and add the functionallity to the official project.
I would do it this way. I hope this helps.

Categories

Resources