Code Monkey home page Code Monkey logo

aws-amplify / amplify-js Goto Github PK

View Code? Open in Web Editor NEW
9.4K 214.0 2.1K 209.25 MB

A declarative JavaScript library for application development using cloud services.

Home Page: https://docs.amplify.aws/lib/q/platform/js

License: Apache License 2.0

TypeScript 91.94% JavaScript 1.34% Java 0.13% Objective-C 0.52% C 4.06% Ruby 0.11% Shell 0.10% Kotlin 1.24% Swift 0.53% Objective-C++ 0.03%
react cloud-service metrics javascript react-native aws aws-apigateway aws-cognito pinpoint aws-mobile

amplify-js's Issues

imports in the auth readme

import { Authenticator, SignIn, SignOut, ConfirmSignUp, Greetings } from 'aws-amplify-react’;

Should be SignIn, SignUp

Signing an API request

Good job on releasing this package!
I am interested in knowing how to sign API Gateway requests with Signature Version 4 using this package. I tried a couple of packages like aws4 but they are made for react native mostly because React Native doesn't support the crypto module.

Thank you!

Doc error with Hub

It is channel, not name.

  onHubCapsule(capsule) {
    const { channel, payload } = capsule;
    if (channel === 'auth') {
      this.stateChange(payload.event);
    }
  }

Always On Auth example

How can this work? In the onClick handler 'this' is not defined.

const AlwaysOn = (props) => {
    return (
        <div>
            <div>I am always here to show current auth state: {this.props.authState}</div>
            <button onClick={() => this.props.onStateChange('signUp')}>Show Sign Up</button>
        </div>
    )
}

User Information Analytics

Is there anyway to tie the Cognito user id to the Pinpoint endpoint via the Analytics module? I am looking for a way to be able to track individual usage rather than just session usage.

(I have already enabled Cognito to share data with Pinpoint by creating the IAM role)

Q: API: 403 The request signature we calculated does not match the signature you provided

I created API through awsmobile could-api and it looks like this

      hello: !com.amazonaws.mobilehub.v0.API 
        attributes:
          name: hello
          requires-signin: true
        paths:
          /hello: !com.amazonaws.mobilehub.v0.Function 
            name: hello
            codeFilename: uploads/hello-20171214123204.zip
            handler: lambda.handler
            enableCORS: true
            runtime: nodejs6.10
            environment: {}
          '/hello/{proxy+}': !com.amazonaws.mobilehub.v0.Function 
            name: hello
            codeFilename: uploads/hello-20171214123204.zip
            handler: lambda.handler
            enableCORS: true
            runtime: nodejs6.10
            environment: {}

When I call it without query parameters API.get('hello', '/hello') it works fine, but if I add anything to query e.g. API.get('hello', '/hello?name=John') I will get following error

403
{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}

Is my configuration wrong or what I am doing wrong?

Does the JWT Token refresh also updates the service-specific objects, such as S3?

Hi all, great product!

With the current workflow (non-awsamplify), once a user signs in and I retrieve the access tokens for him, I can then create service-specific objects such as S3 and DDB. After an hour I would need to re-generate the objects since the tokens have expired and everything needs to be refreshed. Does aws-amplify take care of re-instantiating the service-specific objects or do the devs need to take care of this themselves?

Thanks,
Vladimir Budilov

Signed Requests with API Gateway Cognito Authorizers

First off, I am loving this library so far. I have run into an issue though, and I'm not sure if it's a limitation with the library or something I'm doing incorrectly.

I'd like to make an API.get() call using Amplify to API Gateway and have API Gateway run a Cognito Authorizer on the request. The issue I'm having is, I can't seem to find a way to pass the Cognito Authorizer a valid Authorization Token. The "Authorization" header in the request contains an AWS Signature Version 4 value, which doesn't seem compatible with the Cognito Authorizer.

Am I doing something wrong, or is there a work around for this?

Thanks!

Warning when installing aws-amplify-react-native

When you install aws-amplify-react-native, you get a warning:

yarn add v1.3.2
[1/4] πŸ”  Resolving packages...
warning aws-amplify-react-native > [email protected]: πŸ™Œ  Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!
[2/4] 🚚  Fetching packages...

Chaining onStateChange

Again from the readme...

The internal implementation of onStateChange() does a lot of needed things. This replaces the internal onStateChange() with your own version. But you don't want to do that, you need to call both of them, your replacement and the internal version.

handleAuthStateChange(state) {
    if (state === 'signedIn') { /* GO TO Main Page */ }
}

render() {
    return (
        <Authenticator hideDefault={true} onStateChange={this.handleAuthStateChange}>
            <SignIn/>
            <SignUp/>
            <ConfirmSignUp/>
            <Greetings/>
            <AlwaysOn/>
        </Authenticator>
    )
}

The doc of Amazon S3 Bucket CORS Policy still renders wrong

I have tried to fixed this with the already merged pull request #53 but Amazon S3 Bucket CORS Policy still renders wrong at:

https://aws.github.io/aws-amplify/media/storage_guide.html#amazon-s3-bucket-cors-policy

However, it renders OK at:

https://github.com/aws/aws-amplify/blob/master/media/storage_guide.md#amazon-s3-bucket-cors-policy

How is the former page updated?

It either has not been updated yet, or it wasn't the superfluous space that caused the problem. In any case, please check.

console.log statements pollute developer console

There are plenty console.log statements in the source. Some of them may be useful for library users. But these are just polluting console on every request and have no value if you are not a library maintainer:
image

Missing authenticator in react-native

It looks like Authenticator is not exported with the react-native module.

To reproduce:
import { Authenticator } from 'aws-amplify-react-native';

= Authenticator does not exist...

How to set cache-control on uploads, plus set custom private path?

Hi

  1. Is there any way to add cache-control when uploading files to S3 using aws-amplify? I looked into the source code, but couldn't find where I could add this.

  2. When using private level, aws-amplify will automatically put files inside a folder based on region:identityId
    Is there any way to cusomize this path? For example: private/users/userId etc.

Allow SignUp with custom attributes

Seems like it almost here:
https://github.com/aws/aws-amplify/blob/master/packages/aws-amplify/src/Auth/Auth.ts#L93-L106

Missing few lines to push rest attributes into attributes array and pass into this.userPool.signUp call.

My use case is to allow user to specify name attribute while signing up.

Auth.signUp(username, password, email, name)

Probably the signature should be changed: leave username and password params and provide all other attributes as third param:

Auth.signUp(username, password, { email, name })

XHR Fails Loading OPTIONS

After running through the developer guide for both react web/native, I do not see the 'up-tick in graphs' mentioned here and instead receive the following network errors in Chrome:

XHR failed to load: OPTIONS "https://mobileanalytics.us-west-2.amazonaws.com/2014-06-05/events"

OPTIONS https://mobileanalytics.us-west-2.amazonaws.com/2014-06-05/events net::ERR_NAME_NOT_RESOLVED

Presumably, there is something hindering the Amazon Mobile Analytics SDK from successfully calling the service, but I'm stuck attempting to troubleshoot. This issue occurs in both Chrome and Safari. Any advice or suggestions?

userPoolWebClientId

Docs should mention that when creating the Cognito user pool that you should uncheck the check box for generating a client secret when used with a web app. Might also mention that you can have multiple apps connected to a single pool, so the web app has the secret turned off and the mobile app has it turned on.

Documentation wrong Storage.md

In storage.md the configuration indicates to specify identitypoolid within the Storage options. This does not work - one needs to specify this within AUTH - otherwise amplify throws an error. I guess just a bug in the docu .

Cursor in the Auth Dialogs is wrong

For example cursor over:
Confirm a Code Sign In
Is I-beam when it should be pointing hand

Cursor over the button is arrow, should be pointing hand.

Cursor over:
Please Sign In / Sign Up

Should be pointing hand

Using FederatedSignIn in with aws-amplify-react-native

Hello. I couldn't find any examples with Federated Identities sign in using only the aws-amplify-react-native. Would it be possible to use FederatedSignIn of aws-amplify-react in a react-native mobile app? If yes, what would be the best way of doing this? If not what's the alternative? Thanks

How to persist the user session/ status?

It would be great if you could provide some informations how to persist the user session.

I am trying to avoid that users need to enter their credentials every time they start the app. After login, i store the userdata in redux and localstore. But how to validate the session and status?

Facebook access token not mapped correctly in federated signin

In aws-amplify-react package, the src/Auth/Provider/withFacebook.jsx doesn't correctly map the facebook access token when doing a federatedSignIn. It tries to map the accessToken directly from the root of the response, instead of getting it from the authResponse property of the response object.

I.e: (line 42 currently)
const { accessToken } = response;

should have been:

const { accessToken } = response.authResponse;

How to find the bidirectional map between Cognito identity ID and Cognito user information?

Given the Cognito identity ID, I would like to programmatically find the user name, e-mail address, etc. For example, one issue is that each user gets his/her own folder in S3 (e.g. private/${cognito-identity.amazonaws.com:sub}/ according to the myproject_userfiles_MOBILEHUB_123456789 IAM policy) but I cannot relate that folder name (S3 prefix) to the user attributes in my user pool. The closest thing that I have found is this rather complicated code:

AWS Lambda API gateway with Cognito - how to use IdentityId to access and update UserPool attributes?

Is it my best bet? Is it really this difficult?

(As a workaround, I would be happy with a post confirmation lambda trigger that creates for example a ${cognito-identity.amazonaws.com:sub}/info.txt file in some S3 bucket, and in the info.txt file it could place the user sub from the user pool. I am not sure that this is feasible at all, it was just an idea.)

reactnative auth configuration

Configuration method of AuthClass is referencing the config.analytics of the configuration object
it should be changed to config.Auth.

configure(config) { logger.debug('configure Auth'); let conf = config? config.Analytics || config : {};

Should be

configure(config) { logger.debug('configure Auth'); let conf = config? config.Auth || config : {};

implementation help (solved) RNAWSCognito.xcodeproj manually linked

User able to signup and pool has the credentials. but I got this error when I try sign-in, not sure what's going on there, anyone came across it?

undefined is not an object (evaluating 'RNAWSCognito.computeModPow)

...
import Amplify, { withAuthenticator } from 'aws-amplify-react-native';
import aws_exports from './awsmobilejs/#current-backend-info/aws-exports';
Amplify.configure(aws_exports);

class App extends Component<{}> {
 ......
}
export default withAuthenticator(App);
"dependencies": {
  "aws-amplify": "^0.1.0",
  "aws-amplify-react-native": "^0.1.8",
  "react": "16.0.0",
  "react-native": "0.51.0"
},

New federation support and Cognito user pools

Have you considered making Cognito user pools into a federated service like Google and Facebook? Cognito supports AWS generated UIs now. If you do that there is no need for the user dialogs in the react app any more.

Please don't use the Cognito self-hosted UI that also supports Google/Facebook. That UI makes the federated users in the User Pool, not the Federation Pool. Doing it that way causes a Google login from the User Pool UI and a mobile login via the Federation Pool to end up with two different Cognito IDs.

If you use the Cognito User Pool UI just for Cognito users and leave the current amplify Google/Facebook login code alone, everything is fine for mobile integration (ie app generated via Mobile Hub).

Here's a demo login page I made using the AWS User Pools hosted UI:
https://digispeaker.auth.us-east-1.amazoncognito.com/login?client_id=71hfsop6tn8sr85kqg088emdkr&redirect_uri=https%3A%2F%2Flocalhost%3A3000%2Fredirect.html&response_type=token&scope=openid%20profile%20email&state=cjanc9fdf0000325kmnz959zq

How do I setup the credentials for the SDK?

I put together a test function for lambda, but the credentials are not set into the SDK.
-- Error: Missing credentials in config
Am I using the same copy of the SDK as amplify?
Had amplify set the credentials into the SDK?
I also noted that AWS.config.region is not set either.

Previously I did setup like this:
AWS.config.update({region: 'us-east-1'});
AWS.config.credentials = new AWS.Credentials({
accessKeyId: sessionStorage.getItem('accessKeyId'),
secretAccessKey: sessionStorage.getItem('secretAccessKey'),
sessionToken: sessionStorage.getItem('sessionToken'),
});
But I had expected aws-amplify to set this up for me.

import React, { Component } from 'react';
import AWS from 'aws-sdk'

var Lambda = new AWS.Lambda({region: 'us-east-1', apiVersion: '2015-03-31'});

export default class Page2 extends Component {

  build_table () {
    // create JSON object for parameters for invoking Lambda function
    var pullParams = {
      FunctionName : 'digi-dev-getEvents',
      InvocationType : 'RequestResponse',
      LogType : 'None'
    };
    // create variable to hold data returned by the Lambda function
    var events;

    Lambda.invoke(pullParams, function(error, data) {
      if (error) {
        prompt(error);
      } else {
        events = JSON.parse(data.Payload);
        var t = "<table border=1 padding=3>";
        events.forEach(function(r) {
          t += "<tr>";
          var x = new Date( r["timestamp"] );
          var formatted = x.toLocaleString();
          t += "<td>" + formatted + "</td>";
          t += "<td>" + r["thing"] + "</td>";
          t += "<td>" + r["type"] + "</td>";
          t += "</tr>";
        });
        t += "</table>";
        console.log(t);
      }
    });
  }

Do I need to do something like this?

_ensureCredentials() {
    if (this._options.credentials) { return Promise.resolve(true); }

    return Auth.currentCredentials()
        .then(credentials => {
            const cred = Auth.essentialCredentials(credentials);
            logger.debug('set credentials for storage', cred);
            this._options.credentials = cred;

            return true;
        })
        .catch(err => {
            logger.warn('ensure credentials error', err)
            return false;
        });
}

I just expected amplify to supply me with a global AWS handle that always has valid credentials in it (ie refresh is taken care of).

propTypes warnings on sign in and sign up pages

When wrapping App inside Authenticator component:

export default props => (
  <Authenticator
    amplifyConfig={amplifyConfig}
  >
    <App {...props} />
  </Authenticator>
);

I am getting that warning on sign in page:
image

This on on sign up page:
image

How to resolve cognito user status: FORCE_CHANGE_PASSWORD

Hi,

https://github.com/aws/aws-amplify/blob/3ff3a8c696e478a2f0d4f01d17c8e83e82bd85c9/packages/aws-amplify/src/Auth/Auth.ts#L190-L196

This code is reached when the user has the status FORCE_CHANGE_PASSWORD i.e. after a new user was created in cognito (by the admin in the aws-webconsole, with a temporary password, because signup is not allowed for example).

In my old code I resolved this with a call on cognitoUser object:

cognitoUser.completeNewPasswordChallenge(this.new_password, {email}, ctx);

You initialized the CognitoUser object around line 166, but did not add it to the resolved promise - any chance to get access on this or any suggestions how to solve the initial FORCE_CHANGE_PASSWORD state of the user?

Thanks

Custom Auth UI not visible

I have following component and it gives me black screen.

class AppWithAuth extends Component {
  render () {
    return (
      <Authenticator hideDefault>
        <SignIn />
        <SignUp />
        <ConfirmSignUp />
      </Authenticator>
    )
  }
}
  "dependencies": {
    "aws-amplify": "^0.1.0",
    "aws-amplify-react": "^0.1.23",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.0.17"
  }

Am I missing something? If I remove hideDefault prop I will see two signIn forms.

Add service_info to API Config (want to use custom domain at endpoint)

Hi.
I can't English. I use Google Translate.
I'm sorry if I do not understand the sentences I wrote...

I want to be able to set serice_info as below ↓

Amplify.configure({
  Auth: {
    identityPoolId: "ap-northeast-1:********-****-****-****-************",
    region: "ap-northeast-1",
    userPoolId: "ap-northeast-1_*********",
    userPoolWebClientId: "**************************"
  },
  API: {
    endpoints: [
      {
        name: "API",
        endpoint: "https://custom-domain.com",
        service_info: {
          service: "execute-api",
          region: "ap-northeast-1"
        }
      }
    ]
  }
}

I could not resolve the service_info and it caused an error when I made the endpoint of the API a custom domain.

parse_service_info is expecting /([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/.
service_info.region and service_info.serivce are always null when you are in a custom domain.
https://github.com/aws/aws-amplify/blob/master/packages/aws-amplify/src/Common/Signer.ts#L104

parse_service_info doesn't execute when service_info exists.
https://github.com/aws/aws-amplify/blob/master/packages/aws-amplify/src/Common/Signer.ts#L249

But always execute parse_service_info, because RestClient does not setting service_info.
https://github.com/aws/aws-amplify/blob/master/packages/aws-amplify/src/API/RestClient.ts#L165

I think it will solve it, if you can pass the service_info set in config to the third argument when Signer.sign calls.

Updating mutable user attributes

Is there a way to update a way to update user attributes using this library?

Checked the documentation but doesn't mention anything about updating user attributes.

App UI Customization

I've made changes to the UI of the web client but I don't see any changes when loading up the sign in/up page.

Does aws-amplify support the App UI Customization made for app client in user pool?

NB: I'm using aws-amplify-react

Sharing state across multiple Authenticator instances

Attempting to share authentication state in a react native app between multiple Authenticator components that wrap only a selected few of my react-navigation tabs. Currently, I store both authState and authData in my redux store. Everything works fine until I attempt to log out. If I try simply nullifying authState and authData in my redux store the Authenticator component re logs my user back in when it is shown. If i try to first call Auth.logout I receive the warning [WARN] Hub - error dispatching auth event to noname and my user is re-logged in when the Authenticator component is shown.

AWS SDK use

How are you bundling in the AWS SDK? I use several SDK calls that are not covered under amplify. So I need to include my own version of the SDK. It would be very useful if I could go to https://sdk.amazonaws.com/builder/js/ and generate a single SDK containing the APIs I need and the ones amplify needs. This should also reflect what amplify modules are in use, for example I am not using S3 support.

Maybe there could be a way to automate minified SDK generation. amplify could select the modules it needs and then I could add the names of the modules I need. Then as part of the build process build a single SDK.

Don't default to the entire SDK, it is about 4MB. The small, customized one I use is 200KB.

federated logins are not getting persisted in browser

Using a browser and the demo React app...
login with user pool
close tab/visit site again
your session is properly restored
this works as expected

login in with google
close tab/visit site again
session is not restored
I see session data for Google stored in the browser local storage
it is just not being used to restore the session

same happens with facebook.

aws-amplify from 12/14

What is recommended way to get the initial login state?

My web app has both authenticated and unauthenticated parts. I need to know if there is a valid persistent authenticated login to decide whether or not to show the authorized UI when the app is first loaded. How do I get this state without doing anything in the UI?

Probably Auth.currentAuthenticatedUser() or Auth.currentSession(), but how do I tell if the user is the authenticated or unauthenticated role on the pool? I need to know if there is a persistent login to the authenticated role.

---- I just tried this when logged out
Auth.currentAuthenticatedUser()
.then(user => console.log(user))
.catch(err => console.log(err));

Died on Auth.js line 364, can't get Session on null.

Does there need to be Auth.currentAuthenticatedSession() to differentiate between sessions using the authenticated and unauthenticated roles?

I think what I need is to register a callback with Auth that gets called back on state change.
I have this complex mess currently...

class App extends Component {

handleAuthState(state) {
  this.setState({ authState: state });
  console.log("handleAuthState " + state);
}

constructor(props) {
  super(props);
  this.stateChange = this.handleAuthState.bind(this);
  Auth.currentSession()
    .then(user => this.stateChange('signedIn'))
    .catch(err => this.state = {authState: 'signIn'});
  this.state = {authState: 'signIn'};
}

render() {
  return (
    <Route
      render={({ location }) => (
        <NavigationDrawer
          drawerTitle="Digispeaker"
          toolbarTitle="Welcome to Digispeaker"
          navItems={
            (this.state.authState !== 'signedIn') ?
            navItems.map(props => (<NavLink {...props} key={props.to} />)) :
            navItemsAuth.map(props => (<NavLink {...props} key={props.to} />))
          }
        >
          <Switch key={location.key}>
            <Route exact path="/" location={location} component={Home} />
            <Route path="/page-1" location={location} component={Page1} />
            <Route path="/page-2" location={location} component={Page2} />
            <Route path="/page-3" location={location} component={Page3} />
            <Route path='/signon' render={(props) => (
              <Signon handleAuthState={this.stateChange} {...props} />
            )} />
          </Switch>

export default class Signon extends Component {

handleAuthStateChange(state) {
  this.props.handleAuthState(state);
}

render() {
    return (
      <Authenticator onStateChange={this.handleAuthStateChange.bind(this)}>
      </Authenticator>
    );
  }
}

Signon.propTypes = {
  handleAuthState: PropTypes.func,
};

How can I modify aws-amplify components?

I apply aws-amplify to my project but I want to modify signIn, signUp and other components of aws-amplify.

exactly, when I try to use aws-amplify, I didn't have a choice but to use this view.

amplify

Leveraging Already Existing Identity Pool

Hey all,

Love where the project is. The code is very clean (I've been digging through it this afternoon) and well documented. We've just started looking into Amplify and our team was curious as to whether it works with Identity Pools (not just User Pools). If so, can you point me in the right direction to get this working? I noticed in the documentation there is this example:

Amplify.configure({
    Auth: {
        identityPoolId: 'xx-xxxx-x:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
        region: 'xx-xxxx-x'
    }
})

We already have an Identity Pool with our own authentication, and I'm of course able to get a hold of an Identity ID and Access Token. However, I'm not sure where to go from here (such as, what Object to instantiate and pass the ID/Token into). Any help would be appreciated, thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.