What is the AWS SDK library for signin in Cognito (from backend without using Amplify)? - aws-sdk

I have implemented user signup using #aws-sdk/client-cognito-identity-provider but not able to find the module or API from AWS SDK to implement sign in to cognito

#aws-sdk/client-cognito-identity-provider is the right lib for what you want to do.
import * as AWS from "#aws-sdk/client-cognito-identity-provider";
const client = new AWS.CognitoIdentityProvider({ region: "REGION" });
client.initiateAuth({
ClientId: '...',
AuthFlow: 'USER_PASSWORD_AUTH',
AuthParameters: {
USERNAME: 'my_test_user',
PASSWORD: '...'
}
}, function(err, data) {});

Related

Is it possible to use express.js to build rest api in frontend?

the plan is to build the web app with react.js and also build the backend using express.js specfically using rest api to connec to mySQL database....the problem is
for authentication, my supervisor doesnt want me to store password anywhere, instead he suggested me to build an authentication using the usename and password that we use to connect to mySQL database. For example, when i try to make a connection with mysqlCreateConnection method, theres a section where i have to fill out the ip address and username and password. the problem is if i do this, when the user logs out, the connection between backend and database will disconnect......
is it possible to use mySQL createconnection in the front end? so whenever the user logs in it will connect to the database directly from the frontend? once the connection is created, then use backend rest api? if this works i assume the rest api has to be hosted with the same url as the frontend, since we made the connection to mySQL database in the frontend.......but again if we do this, doesnt it defeat the purpose of backend? meaning anyone can login to the frontend and change whatever they want to the backend?
so the result will be like
within the frontend. user logs in using mySQL workbench username and password, then that username and password is going to fill out the mysql createconnection method(this method is written in the frontend). which will then try to connect to the database.
user logs in successfull
user fills out a form about a product and clicks on submit and this data is send to our rest api, and mySQL database adds the data in.
here are examples of router-token and router-session within the app if you are at express.js.
db.js
const mysql = require("mysql2")
const config = require("../../config/config.json").DB
module.exports = mysql.createPool({
host: config.host,
user: config.username,
password: config.password,
database: config.database,
waitForConnections: true,
connectionLimit: 100,
queueLimit: 0,
multipleStatements: true
})
db.fun.js
const db = require("./db").promise()
let query = async(sql, data) => {
try {
let d = await db.query(sql, data);
return d[0];
} catch (err) {
console.log(`EDB: ./app/database/db.fun.js 8rows \n${err}`);
return { err: 1, errdata: err };
}
}
module.exports = {
query: query
}
import query
(async function(){
const { query } = require("../database/db.fun");
let user = await query("SELECT * FROM users",[]);
console.log(user)
})();

Quasar + Feathers-Vuex: how to integrate?

I want to integrate Quasar with FeathersJS using Feathers-Vuex
Feathers-Vuex uses a pattern to:
promise to authenticate from localStorage/cookies
.then( /*start the new Vue() app */ )
I created my app with Quasar CLI 1.0.beta16-ish and looked through /src and couldn't find the main entry point for Quasar. I feel like I'm missing something.
What includes src/store/index.js?
quasar.conf.js includes this comment - where is the main.js
// app boot file (/src/boot)
// --> boot files are part of "main.js"
boot: ["axios"],
Feathers-Vuex includes a Nuxt integration guide that may solve the same problem. These packages are all new to me, and I'm excited to learn them!
Thank you!
The part of main.js is included in quasar app.js that you can find in .quasar folder. The src/store/index.js contains the Vuex Store definition. A "store" is basically a container that holds your application state.
For more detail visit - https://quasar-framework.org/guide/app-vuex-store.html https://quasar-framework.org/guide/app-plugins.html
I ended up with two things:
Adding Feathers-Vuex to my backend.
Adding this "boot file" in my Quasar project
The comments are a bread-crumb trail if I ever have to figure it out again :-)
/*
Context:
For 3rd-party API's, we us /src/boot/axios.js
For our own API's, we use FeathersClient (socket.io & REST)
https://docs.feathersjs.com/guides/basics/clients.html
https://docs.feathersjs.com/api/authentication/client.html#appconfigureauthoptions
Our FeathersClient is in `/src/lib/feathersClient.js`
and imported into `/src/store/index.js`
which is imported by Quasar's build system. /src/quasar.conf.js setting(?)
Feathers-vuex integrates Vuex with FeathersClient:
https://feathers-vuex.feathers-plus.com/auth-module.html
Feathers-Vuex proxies it's authentication/logout actions to FeathersClient
https://github.com/feathers-plus/feathers-vuex/blob/master/src/auth-module/actions.js
The parameters for these actions are here:
https://docs.feathersjs.com/api/authentication/client.html#appauthenticateoptions
In addition to this module, you can use FeathersVuex state in UI from here:
https://feathers-vuex.feathers-plus.com/auth-module.html
This module:
Create a Feathers Auth integration for Vue as a Quasar Boot Module.
// Use case: test if user is authenticated
if (Vue.$auth.currentUser()) { ... }
// Use case: get current user's email
name = Vue.$auth.currentUser("email") || "anonymous"
// Use case: Login
Vue.$auth.login({
strategy: 'local',
email: 'my#email.com',
password: 'my-password'
});
// Use case: Logout
// logs out and sends message
let p = Vue.$auth.logout();
// After logout, go home
p.then(() => {
// User data still in browser
router.push({ name: "home"});
// To clear user data, do a hard refresh/redirect - https://feathers-vuex.feathers-plus.com/common-patterns.html#clearing-data-upon-user-logout
location && location.reload(true)
});
*/
export default ({ app, router, store, Vue }) => {
// Create the API demonstrated above
const auth = {
currentUser(prop) {
let u = store.state.auth.user || false;
if (u && prop) return u[prop];
return u;
},
login(authData, quiet) {
return store
.dispatch("auth/authenticate", authData)
.then(() => {
Vue.prototype.$q.notify({
message: "Welcome back!",
type: "info"
});
})
.catch(err => {
if (!quiet) {
console.log(err);
Vue.prototype.$q.notify({
message: "There was a problem logging you in.",
type: "error"
});
}
});
},
logout(quiet) {
return store.dispatch("auth/logout").then(() => {
if (!quiet)
Vue.prototype.$q.notify({
message: "You've been logged out.",
type: "info"
});
});
},
register(authData) {}
};
// Auth from JWT stored in browser before loading the app. true => suppress token not found error
auth.login("jwt", true);
// Add API to Vue
Vue.prototype.$auth = auth;
// If you would like to play with it in the console, uncomment this line:
// console.log(auth);
// Then, in the console:
/*
temp1.login({
strategy: "local",
email: "feathers#example.com",
password: "secret"
})
*/
// If you haven't created this user, see here:
// https://docs.feathersjs.com/guides/chat/authentication.html
// For this REST api endpoint
/*
curl 'http://localhost:3001/users/' -H 'Content-Type: application/json' --data-binary '{ "email": "feathers#example.com", "password": "secret" }'
*/
};

Connect react-native to firebase and mysql

I'm developing an application using react-native. I can easily connect my react-native application to firebase. My idea is to use firebase authentication, but with data from my MySQL database.
What is the best/correct way to use firebase and mysql?
My idea is use ajax request from react-native to mysql in order to validate the username and password against the data into my MySQL database. Then use the ID returned from this request to create or load a user from firebase. Is it the correct way?
I am sorry if it doe snot make sense. I just start working with react-native and firebase.
Thanks
Well...
For mysql you can use axios plugin. Is the best way to work with mysql database.
Firebase use asynchronous request, if you want work with both the best way is using axios.
First, you get user from your mysql table, correct?
So.. you do something like that :
return axios.get(server_address&param=PARAM_VALUE)
.then(response => {
return(response);
}).catch(function(error) {
alert.error(error.message);
});
Axios aways return a JSON response.
You can use GET or POST method.
So... with the JSON, you can send for firebase your data for load or create user.
like that:
return firebase
.auth()
.signInWithEmailAndPassword(loginEmail,loginPassword)
.then( user => {
return user;
})
.catch(error => {
if ((error.code == 'auth/user-not-found') || (error.code == 'auth/invalid-email')) {
return new Promise((resolve, reject) => {
Alert.alert(
'User not found',
'Create ?',
[{
text: 'No',
onPress:() => resolve(),
style:'cancel'
},{
text:'Yes',
onPress: () =>{
firebase
.auth()
.createUserWithEmailAndPassword(loginEmail,loginPassword)
.then(resolve)
.catch(reject)
}
}],
{cancelable: false}
)
})
}
return Promise.reject(error)
})
For a complete guide to axios :
https://github.com/qiangmao/axios#readme
For a complete guide to firebase:
https://firebase.google.com/docs/auth/?hl=en

Using AWS Javascript SDK with NativeScript

I'm planning to build an app using Nativescript. However, I want to integrate AWS services in the app architecture.
Please, can someone tell me whether I can use AWS JS SDk with nativescript or not.
If yes, how?
Thank you.
Yes, you can use AWS SDK with NativeScript. I am using it to upload files to S3. You need to install it using
npm i aws-sdk
File upload to AWS S2 example
In your component file, import it
import * as AWS from 'aws-sdk';
const AWSService = AWS;
const region = 'Your_Region_name';
this.bucketName = 'bucketName ';
const IdentityPoolId = 'IdentityPoolId';
// Configures the AWS service and initial authorization
AWSService.config.update({
region: region,
credentials: new AWSService.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
})
});
// adds the S3 service, make sure the api version and bucket are correct
this.s3 = new AWSService.S3({
apiVersion: '2006-03-01',
params: { Bucket: this.bucketName }
});
this.s3.upload({ Key: 'test/' + file.name, Bucket: this.bucketName, Body: file, ACL: 'public-read' }, function (err, data) {
if (err) {
console.log(err, 'there was an error uploading your file');
}
console.log('upload done');
});
P.S. You need to create a Idendity pool in cognito if you don't have one.

Obtain an id token in the Gmail add-on for a backend service authentication

The background
I'm using the Google Apps Script to create a Gmail Add-on.
Via this plugin, I would like to connect to my backend server (a non-Google service) using a REST service request. The request has to be authorised. When authorised, I could then make requests to that server to receive data associated with that user in the database. I'm already using Google sign-in in my webapp to sign in to the backend service - at the front end, I receive the id_token inside of the GoogleUser object in the authorisation response.
The problem
I need this id_token to log in to my backend service when connecting to it via the Gmail plugin. However, I couldn't find a way how to access the token.
The research
I would assume the token must be available through the API in the Apps Script.
In the webapp, I receive the id_token using the Google Auth API like this:
Promise.resolve(this.auth2.signIn())
.then((googleUser) => {
let user_token = googleUser.getAuthResponse().id_token; // this is the id_token I need in the Gmail plugin, too
// send the id_token to the backend service
...
};
In the Google Apps Script API I could only find the OAuth token:
ScriptApp.getOAuthToken();
I assumed the token could also be stored in the session. The Google Apps Script API contains the Session class and that itself contains the getActiveUser method, which returns the User object. The User object, however, only contains the user's email address, no id token (or anything else for that matter):
Session.getActiveUser().getEmail();
The question(s)
Is there a way to obtain the id token?
Am I choosing the right approach to logging in to the backend server using the data of the signed-in user in the Gmail?
Method 1: use getIdentityToken()
Gets an OpenID Connect identity token for the effective user:
var idToken = ScriptApp.getIdentityToken();
var body = idToken.split('.')[1];
var decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
var payload = JSON.parse(decoded);
var profileId = payload.sub;
Logger.log('Profile ID: ' + profileId);
Method 2: use Firebase and getOAuthToken()
Steps to get Google ID Token from Apps Script's OAuth token:
Enable Identity Toolkit API for your Apps Script project.
Add new Firebase project to your existing Google Cloud Platform project at https://console.firebase.google.com/
Create Firebase app for platform: Web.
You will get your config data: var firebaseConfig = {apiKey: YOUR_KEY, ...}.
Enable Google sign-in method for your Firebase project at https://console.firebase.google.com/project/PROJECT_ID/authentication/providers.
Use Apps Script function to get ID Token for current user:
function getGoogleIDToken()
{
// get your configuration from Firebase web app's settings
var firebaseConfig = {
apiKey: "***",
authDomain: "*.firebaseapp.com",
databaseURL: "https://*.firebaseio.com",
projectId: "***",
storageBucket: "***.appspot.com",
messagingSenderId: "*****",
appId: "***:web:***"
};
var res = UrlFetchApp.fetch('https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key='+firebaseConfig.apiKey, {
method: 'POST',
payload: JSON.stringify({
requestUri: 'https://'+firebaseConfig.authDomain,
postBody: 'access_token='+ScriptApp.getOAuthToken()+'&providerId=google.com',
returnSecureToken: true,
returnIdpCredential: true
}),
contentType: 'application/json',
muteHttpExceptions: true
});
var responseData = JSON.parse(res);
idToken = responseData.idToken;
Logger.log('Google ID Token: ');
Logger.log(idToken);
return idToken;
}
Kudos to Riƫl Notermans
You should enable oAuth scopes,
https://developers.google.com/apps-script/concepts/scopes