how to get awstoken from AWS cognito - javascript

I want to use accessToken variable outside the success function. I tried different ways to use variable but it didn't work.
var authenticationData = {
Username : 'username',
Password : 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_ExaMPle',
ClientId : '1example23456789'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'username',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer */
var idToken = result.idToken.jwtToken;
},
onFailure: function(err) {
alert(err);
},
});

Why not add the accessToken to the authenticationData object?
var authenticationData = {
Username : 'username',
Password : 'password',
AccessToken : ''
};
// And then set the token in the success method:
authenticationData.AccessToken = result.getAccessToken().getJwtToken();
Once authenticationData.AccessToken has been set, you can use the value anywhere in scope.

Related

Unable to access CognitoIdentityServiceProvider with credentials after user logged in

I'm currently using this package amazon-cognito-identity-js to login my user using cognito user pool
import { Config, CognitoIdentityCredentials, CognitoIdentityServiceProvider } from "aws-sdk";
import {
CognitoUser,
CognitoUserPool,
AuthenticationDetails,
CognitoRefreshToken,
} from "amazon-cognito-identity-js";
const region = this.options.REGION
const userPoolId = this.options.USER_POOL_ID // user pool id of User Pool
const clientId = this.options.CLIENT_ID // client id of app client
const identityPoolId = this.options.IDENTITY_POOL_ID // identify pool id of federated identity pool
let authenticationData = { Username: params.username, Password: params.password }
let authenticationDetails = new AuthenticationDetails(authenticationData)
let poolData = {
UserPoolId: userPoolId,
ClientId: clientId
}
let userPool = new CognitoUserPool(poolData)
let userData = {
Username: params.username,
Pool: userPool
}
let cognitoUser = new CognitoUser(userData)
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken()
var logins = {}
logins['cognito-idp.' + region + '.amazonaws.com/' + userPoolId] = accessToken
const credentials = new CognitoIdentityCredentials({
region: region,
IdentityPoolId: identityPoolId,
Logins: logins
})
// **** IM GETTING AN ERROR HERE IN CognitoIdentityServiceProvider ****
var cognitoIdentityProvider = new CognitoIdentityServiceProvider({
apiVersion: '2016-04-18',
region: region,
credentials: credentials
});
var params = {
GroupName: 'STB',
UserPoolId: userPoolId,
};
cognitoIdentityProvider.listUsersInGroup(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
},
onFailure: function(err) {
console.log(err)
}
})
I'm able to login successfully but I'm getting an error when calling listUsersInGroup function
CredentialsError: Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1
I also checked that the credentials returns
console.log(credentials)
> CognitoIdentityCredentials {expired: true, expireTime: null, refreshCallbacks: Array(0), accessKeyId: undefined, sessionToken: undefined, …}
What am I missing here? I checked that it's possible to pass credentials instead of AccessKey and Secret according to this documentation

How do I set role in Node JS JWT Authentication?

I'm really new with Node JS and now I'm learning about how to use JWT Authentication in my Rest API
I already make token generator in my login function but when I try to verify the token with setting up some role where if the role equal 2 I could get a data. And now I having trouble because I can't verify my token
Log in:
exports.login = function(req, res){
var post = {
email : req.body.email,
password : req.body.password
}
var query = "SELECT * FROM ?? WHERE ?? = ? AND ?? = ?";
var table = ["user", "password", md5(post.password), "email",post.email];
query = mysql.format(query,table);
connection.query(query, function(error, rows){
if(error){
console.log(error);
}else{
if (rows.length == 1){
//ini 1440 dalam second
var token = jwt.sign({rows}, config.secret);
id_user = rows[0].id;
username = rows[0].username;
email = rows[0].email;
tanggal_daftar = rows[0].tanggal_daftar;
role = rows[0].role;
var data = {
id_user : id_user,
access_token : token,
username : username,
email : email,
tanggal_daftar : tanggal_daftar,
role : role,
ip_address : ip.address()
}
res.json({
success : true,
message : "Token JWT generate",
token : token,
idUser: data.id_user,
username : username,
email : data.email,
tanggal_daftar : tanggal_daftar,
role : data.role
});
}else{
res.json({"Error": true, "Message":"Email atau password anda salah"});
}
}
});
}
Token check:
const jwt = require('jsonwebtoken');
const config = require('../config/secret');
function verifikasi(role){
return function (req, rest, next){
// var role = req.body.role;
//cek authorization header
var tokenWithBearer = req.headers.authorization;
if(tokenWithBearer){
var token = tokenWithBearer.split(' ')[1];
//verifikasi
jwt.verify(token, config.secret, function(err, decoded){
if(err){
return rest.status(401).send({auth:false, message:"Token tidak terdaftar!"});
}else{
if(role == 2){
req.auth = decoded;
next();
}else{
return rest.status(401).send({auth:false, message:"gagal melakukan otorisasi!"});
}
}
});
}else{
return rest.status(401).send({auth:false, message:"Token tidak tersedia!"});
}
}
}
module.exports = verifikasi;
Index:
// alamat dengan otoritas khusus
router.get('/api/v1/rahasia', verifikasi(), auth.halamanrahasia);
There's an error in your if(role == 2) you should change it to (decoded.role == 2)
Edit: change if(role == 2) to if(decoded.rows.role == 2)

Cognito adminDeleteUser user pool does not exist error

Why does the AWS Cognito adminDeleteUser function as shown in the code below give a "User pool does not exist" error message?
const aws = require('aws-sdk');
aws.config.accessKeyId = 'aaaaaaa';
aws.config.secretAccessKey = 'sssssss';
aws.config.region = 'us-west-2';
const CognitoIdentityServiceProvider = new
aws.CognitoIdentityServiceProvider();
global.fetch = require('node-fetch');
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
// this section of code produces a correct userPool object
let poolData =
{
UserPoolId: 'ppppppp',
ClientId: 'ccccccc'
};
let userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
console.log('userPool: ', userPool);
// this section of code reports error: "ResourceNotFoundException:
User pool ppppppp does not exist."
let params =
{
UserPoolId: 'ppppppp',
Username: 'nnnnnnn'
};
CognitoIdentityServiceProvider.adminDeleteUser(params, (err,data) =>
{
if (err) console.log(err);
else console.log('user deleted');
});
Problem has been resolved by changing code from
aws.config.accessKeyId = 'aaaaaaa';
aws.config.secretAccessKey = 'sssssss';
aws.config.region = 'us-west-2';
to the following
aws.config.update(
{
accessKeyId: 'aaaaaaa',
secretAccessKey: 'sssssss',
region: 'us-west-2'
});
Note also that the following code creates a userPool object whether or not a valid UserPoolId value is provided:
let poolData =
{
UserPoolId: 'ppppppp,
ClientId: 'ccccccc'
};
let userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

Firebase Update with custom string

When this code executes, the result is
userId : {
userName : userN
}
when it actually should be the params from the rest call. How can I dynamically add data to ref.update?
exports.addUser = functions.https.onRequest((req, res) => {
const userId = req.query.userId;
const userN = req.query.userName;
var ref = admin.database().ref("users")
ref.update({
userId : {
userName : userN
}
});
res.status(200).send("User added successfully");
});
I guess you need to specify that userId is a variable.
exports.addUser = functions.https.onRequest((req, res) => {
const userId = req.query.userId;
const userN = req.query.userName;
const ref = admin.database().ref("users")
ref.update({
[userId]: {
userName: userN,
},
});
res.status(200).send("User added successfully");
});
PS: I don't know firebase

Nodejs with ExpressJS including external js code files for use

learning NodeJS here... I have this very basic "class" file I put into an external JS file. How do I make this available for all my routing files and or other external js files(that i also like to load) see?
/classes/music/usermanager.js
function User(){
this.email = "";
this.password = "";
this.userid = "";
}
function UserManager()
{
this.user = new User();
}
UserManager.prototype.login = new function (email, password){
var db = new DbManager();
db.Open();
params = {
$email : email,
$password : password
}
db.serialize(function(){
db.get("SELECT * FROM Users WHERE email = $email and password = $password", params, function(err,row) {
if (!err && row) {
//log in passed
this.user.userid = row.user.id;
this.user.email = row.user.email;
this.user.password = row.user.password;
return this.user;
}
else if (!err) {
//log in failed log event
return null;
}
else {
//error happened through out an event to log the error
return null;
}
});
});
}
/config/strategies/local.strategy.js example of how I would be using it in another file.
var passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
module.exports = function () {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, done) {
//vadliating user here
var userManager = new UserManager();
var user = userManager.login(email, password);
done(null, user);
}));
};
I tried doing something like this in my app.js file and it is barfing on compiling stating "throw new TypeError('app.use() requires middleware functions');". I could of sworn I read somewhere you could do that but now can't find the resource.
/asp.js
/*load external js library files for application use*/
app.use ("./classes/music/:path*");
Have a feeling i am missing a basic a understanding here still when trying to organize a nodejs/expressjs project.
Your actually using the answer in one of your examples. You make modules available by using the module.exports = whatever;. Meaning that you can export anything a string, an object, or a "class". So you could export UserManager by adding this to the end of the file (or really anywhere).
module.exports = UserManager;
and require it in another filer by using its relative file path. So if its in the same directory.
var UserManager = require('./usermanager.js');
So for the local.strategy.js file to require UserManager it would look like: (if you filepaths are all in the same root directory)
var UserManager = require('../../classes/music/usermanager.js');
/classes/music/usermanager.js
// Working for me, try it, hope this may help you
var model = module.exports;
function User() {
this.email = "";
this.password = "";
this.userid = "";
}
function UserManager() {
this.user = new User();
}
UserManager.prototype.login = function(email, password) {
var db = new DbManager();
db.Open();
params = {
$email : email,
$password : password
}
db.serialize(function(){
db.get("SELECT * FROM Users WHERE email = $email and password = $password", params, function(err,row) {
if (!err && row) {
//log in passed
this.user.userid = row.user.id;
this.user.email = row.user.email;
this.user.password = row.user.password;
return this.user;
}
else if (!err) {
//log in failed log event
return null;
}
else {
//error happened through out an event to log the error
return null;
}
});
});
};
model.login = function (email, password){
var usrmng = new UserManager();
return usrmng.login(email, password);
};
/config/strategies/local.strategy.js
var usermanager = require('./usermanager'); // path to ur file
var passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
module.exports = function () {
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function (email, password, done) {
//vadliating user here
//var userManager = new UserManager();
var use = usermanager.login(email, password);
done(null, user);
}));
};

Categories