aws-amplify#Auth TypeScript Examples

The following examples show how to use aws-amplify#Auth. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: coaching.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
createCoachingAndSetActive = async ({
  coaching
}: {
  coaching: CreateCoachingDataInput
}): Promise<CreateCoachingDataMutation> => {
  try {
    const { username } = await Auth.currentUserInfo()
    const input: CreateCoachingDataInput = {
      ...coaching,
      userId: username
    }

    const { data } = (await API.graphql(
      graphqlOperation(createCoachingData, { input })
    )) as {
      data: CreateCoachingDataMutation
    }

    await updateUserData({
      user: { id: '', userActiveCoachingId: data.createCoachingData?.id }
    })

    return data
  } catch (error) {
    return error
  }
}
Example #2
Source File: actions.tsx    From platform with MIT License 6 votes vote down vote up
export async function userPasswordForgotSubmit(
  dispatch,
  email,
  code,
  newPassword
) {
  try {
    dispatch({ type: "REQUEST_LOGIN" });
    await Auth.forgotPasswordSubmit(email, code, newPassword);
    dispatch({ type: "STOP_LOADING" });
    return "SUCCESS";
  } catch (error) {
    dispatch({ type: "LOGIN_ERROR", error: error.message });
  }
}
Example #3
Source File: coaching.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
createCoaching = async ({
  coaching
}: {
  coaching: CreateCoachingDataInput
}): Promise<CreateCoachingDataMutation> => {
  try {
    const { username } = await Auth.currentUserInfo()
    const input: CreateCoachingDataInput = {
      ...coaching,
      userId: username
    }

    const { data } = (await API.graphql(
      graphqlOperation(createCoachingData, { input })
    )) as {
      data: CreateCoachingDataMutation
    }
    return data
  } catch (error) {
    return error
  }
}
Example #4
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 6 votes vote down vote up
Amplify.configure({
  ...awsExports,
  Auth: {
    oauth: {},
    authenticationFlowType: "USER_PASSWORD_AUTH",
  },
  Analytics: {
    disabled: true,
  },
});
Example #5
Source File: coaching.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
updateCoaching = async ({
  coaching
}: {
  coaching: UpdateCoachingDataInput
}): Promise<UpdateCoachingDataMutation> => {
  try {
    const { username } = await Auth.currentUserInfo()

    const input: UpdateCoachingDataInput = {
      ...coaching,
      userId: username
    }

    const { data } = (await API.graphql(
      graphqlOperation(updateCoachingData, { input })
    )) as {
      data: UpdateCoachingDataMutation
    }
    return data
  } catch (error) {
    return error
  }
}
Example #6
Source File: useSleep.ts    From nyxo-website with MIT License 6 votes vote down vote up
listSleep = async () => {
  try {
    const { username } = await Auth.currentUserInfo()
    const {
      data: { listNights: data },
    } = (await API.graphql(graphqlOperation(listNights, { id: username }))) as {
      data: ListNightsQuery
    }

    return data
  } catch (error) {
    console.log(error)
  }
}
Example #7
Source File: container.ts    From antibody-web with MIT License 6 votes vote down vote up
appContainer: AppContainer = {
  testApi: testApi({ apiBase: config.apiBase }),
  authenticationApi: cognitoAuthenticationApi,
  getCurrentUserDetails: async () => {
    return Auth.currentAuthenticatedUser()
      .then((user) => ({ user, loggedIn: true }))
      .catch(() => ({ loggedIn: false }));
  },
}
Example #8
Source File: actions.tsx    From platform with MIT License 6 votes vote down vote up
export async function loginUser(dispatch, Email, Password) {
  dispatch({ type: "REQUEST_LOGIN" });

  if (!Email || !Password) {
    dispatch({
      type: "LOGIN_MISSING_FIELDS",
      error: "Please enter both email and password."
    });
    return;
  }

  const user = await Auth.signIn(Email, Password).catch((error) => {
    dispatch({ type: "LOGIN_ERROR", error: error.message });
  });

  if (user) {
    dispatch({ type: "LOGIN_SUCCESS", payload: user });
    localStorage.setItem("currentUser", JSON.stringify(user));
    return user;
  }
  return;
}
Example #9
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 6 votes vote down vote up
App = () => {

  const [authState, setAuthState] = React.useState<any>();
  const [user, setUser] = React.useState<any | undefined>();

  const setCurrentUser = () => {
    Auth.currentAuthenticatedUser()
      .then((user: any) => {
        setUser(user);
      })
      .catch((info: any) => {
        console.log("Info: ", info);
      });
  };

  return (authState && user) ? (
    <View style={styles.container}>
      <Text>Good day, {(authState && user) ? user.username : 'mate'}</Text>
      <Button title="Sign out" onPress={() => {
        Auth.signOut().then(
          () => {
            setAuthState(null);
            setUser(null);
          }
        ).catch((info: any) => console.log("Info: ", info));
      }} />
    </View>
  ) : (
      <Authenticator
        signUpConfig={signUpConfig}
        onStateChange={(authState: any) => {
          setAuthState(authState);
          setCurrentUser();
        }}
        theme={GreatTheme}
      />

    );
}
Example #10
Source File: authHelper.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export async function signInUser2(username: string, realPw: string) {
  const authDetails = new AuthenticationDetails({
    Username: username,
    Password: realPw,
  });
  const user = Amplify.Auth.createCognitoUser(username);
  await authenticateUser(user, authDetails, realPw);
  return user;
}
Example #11
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 6 votes vote down vote up
Amplify.configure({
  ...awsExports,
  Auth: {
    oauth: {},
    authenticationFlowType: 'USER_PASSWORD_AUTH'
  },
  Analytics: {
    disabled: true
  }
});
Example #12
Source File: index.tsx    From RareCamp with Apache License 2.0 6 votes vote down vote up
AccountMenu = () => {
  const router = useRouter()
  const mutation = useMutation(() => Auth.signOut({ global: true }), {
    onSuccess: router.reload,
    onError: (err: Error) =>
      notification.error({
        message: 'Can not logout',
        description: err.message,
        placement: 'topRight',
        duration: 1.5,
      }),
  })
  return (
    <OFMenu>
      <Menu.Item>
        <Link href="/auth/password">Update Password</Link>
      </Menu.Item>
      <Menu.Item>
        <Button
          loading={mutation.isLoading}
          onClick={() => mutation.mutate()}
        >
          Logout
        </Button>
      </Menu.Item>
    </OFMenu>
  )
}
Example #13
Source File: myprofile.compo.ts    From CloudeeCMS with Apache License 2.0 6 votes vote down vote up
ngOnInit() {
    const that = this;
    Auth.currentAuthenticatedUser().then(data => {
      console.log('user', data);
      that.userData = data;
      that.setLoading(false);
      that.userLoaded = true;
    }).catch(err => {
      that.setLoading(false);
      that.errorMessage = err.message || 'Error while loading user data';
    });
  }
Example #14
Source File: index.tsx    From RareCamp with Apache License 2.0 6 votes vote down vote up
export default function UserHeader({
  getContent,
}: {
  getContent?: any
}) {
  const { data, isLoading } = useQuery('userInfo', () =>
    Auth.currentAuthenticatedUser(),
  )
  return (
    <PageHeader>
      <Avatar size={72}>
        {isLoading ? <Spin /> : data?.attributes.name[0]}
      </Avatar>
      <div>
        <h3>
          {getContent
            ? getContent(data?.attributes).title
            : `Welcome ${data?.attributes?.name}, we are glad you are here!`}
        </h3>
        <span>
          {getContent
            ? getContent(data?.attributes).description
            : `Our goal today is to get you one step ahead in your gene
          therapy treatment roadmap`}
        </span>
      </div>
    </PageHeader>
  )
}
Example #15
Source File: App.tsx    From TwitterClone with MIT License 5 votes vote down vote up
function App() {
  const isLoadingComplete = useCachedResources();
  const colorScheme = useColorScheme();

  const getRandomImage = () => {
    return 'https://scontent.fkiv3-1.fna.fbcdn.net/v/t31.0-8/s960x960/22256588_1932617800312085_5686197942193420542_o.jpg?_nc_cat=110&_nc_sid=85a577&_nc_ohc=svjjE7DUkc0AX9yjcdC&_nc_ht=scontent.fkiv3-1.fna&tp=7&oh=1df4116c73c45a32ebad070704ca3333&oe=5F6ECD77'
  }

  const saveUserToDB = async (user) => {
    console.log(user);
    await API.graphql(graphqlOperation(createUser, { input: user }))
  }

  useEffect(() => {
    const updateUser = async () => {
      // Get current authenticated user
      const userInfo = await Auth.currentAuthenticatedUser({ bypassCache: true });

      if(userInfo) {
        // Check if user already exists in database
        const userData = await API.graphql(graphqlOperation(getUser, { id: userInfo.attributes.sub }));
        console.log(userData)
        if(!userData.data.getUser) {
          const user = {
            id: userInfo.attributes.sub,
            username: userInfo.username,
            name: userInfo.username,
            email: userInfo.attributes.email,
            image: getRandomImage(),
          }
          await saveUserToDB(user);
        } else {
          console.log('User already exists');
        }
      }


      // If it doesn't, create the user in the database
    }
    updateUser();
  }, [])

  if (!isLoadingComplete) {
    return null;
  } else {
    return (
      <SafeAreaProvider>
        <Navigation colorScheme={colorScheme} />
        <StatusBar />
      </SafeAreaProvider>
    );
  }
}
Example #16
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 5 votes vote down vote up
App = () => {
  const [authState, setAuthState] = React.useState<any>();
  const [user, setUser] = React.useState<any | undefined>();

  const setCurrentUser = () => {
    Auth.currentAuthenticatedUser()
      .then((user: any) => {
        setUser(user);
      })
      .catch((info: any) => {
        console.log("Info: ", info);
      });
  };

  return authState && user ? (
    <View style={styles.container}>
      <Text>Good day, {authState && user ? user.username : "mate"}</Text>
      <Button
        title="Sign out"
        onPress={() => {
          Auth.signOut()
            .then(() => {
              setAuthState(null);
              setUser(null);
            })
            .catch((info: any) => console.log("Info: ", info));
        }}
      />
    </View>
  ) : (
    <Authenticator
      signUpConfig={signUpConfig}
      onStateChange={(authState: any) => {
        setAuthState(authState);
        setCurrentUser();
      }}
      theme={GreatTheme}
    />
  );
}
Example #17
Source File: password.tsx    From RareCamp with Apache License 2.0 5 votes vote down vote up
export default function App() {
  const router = useRouter()
  const mutation = useMutation(
    ({ username }: { username: string }) =>
      Auth.forgotPassword(username),
    {
      onSuccess: async (_, variables) => {
        notification.success({
          message: 'Instructions sent to your emails',
          description: 'Account confirmed successfully!',
          placement: 'topRight',
          duration: 1.5,
        })
        await router.push(
          `/auth/resetpassword?username=${variables.username}`,
        )
      },
      onError: async (err: Error) => {
        notification.error({
          message: 'User confirmation failed',
          description: err.message,
          placement: 'topRight',
          duration: 3,
        })
      },
    },
  )

  return (
    <AuthLayout>
      <div>
        <Title level={3}>Forgot your password?</Title>
        <p>
          We'll send you an email with instructions.
          <p>
            or
            <Button
              type="link"
              onClick={() => router.push('/auth/login')}
            >
              Login
            </Button>
          </p>
        </p>
      </div>
      <Form
        layout="vertical"
        name="forgot_password_form"
        onFinish={mutation.mutate}
      >
        <Form.Item
          label={<span style={{ fontWeight: 500 }}>Email</span>}
          name="username"
          required={false}
          rules={[
            {
              required: true,
              message: 'Please input your email',
              type: 'email',
            },
          ]}
        >
          <Input placeholder="[email protected]" />
        </Form.Item>
        <Form.Item>
          <Button
            loading={mutation.isLoading}
            type="primary"
            htmlType="submit"
            block
            className="login-form-button"
          >
            Reset Password
          </Button>
        </Form.Item>
      </Form>
    </AuthLayout>
  )
}
Example #18
Source File: header.tsx    From nyxo-website with MIT License 5 votes vote down vote up
signOut = () => {
  Auth.signOut()
    .then(() => navigate("/me/login"))
    .catch((err) => console.log(err))
}
Example #19
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 5 votes vote down vote up
Auth.configure({
  authenticationFlowType: 'USER_PASSWORD_AUTH'
});
Example #20
Source File: cognitoAuthenticationApi.ts    From antibody-web with MIT License 5 votes vote down vote up
authenticationApi: AuthenticationApi = {
  signIn: async ({ username, password }) => {
    let response: SignInResponse = {
      user: undefined,
      successful: false,
      requiresNewPassword: false,
    };

    await Auth.signIn({ username, password })
      .then((user) => {
        response.user = user;
        response.successful = true;
        response.requiresNewPassword =
          user.challengeName === "NEW_PASSWORD_REQUIRED";
      })
      .catch((err) => {
        response.successful = false;
        response.errors = [err.message];
      });
    return response;
  },

  newPassword: async ({ user, newPassword }) => {
    let response: NewPasswordResponse = {
      successful: false,
    };

    await Auth.completeNewPassword(user, newPassword, {})
      .then(() => {
        response.successful = true;
      })
      .catch((error) => {
        response.successful = false;
        response.errors = [error.message];
      });

    return response;
  },

  signOut: async () => {
    return Auth.signOut();
  },
}
Example #21
Source File: Amplify.ts    From nyxo-app with GNU General Public License v3.0 5 votes vote down vote up
Auth.configure(awsAmplify)
Example #22
Source File: authentication.tsx    From platform with MIT License 5 votes vote down vote up
export async function resendActivationCode(email) {
  const sent = await Auth.resendSignUp(email);
  return sent;
}
Example #23
Source File: BottomTabNavigator.tsx    From TwitterClone with MIT License 5 votes vote down vote up
function HomeNavigator() {

  const [user, setUser] = useState(null);

  useEffect(() => {
    // get the current user
    const fetchUser = async () => {
      const userInfo = await Auth.currentAuthenticatedUser({ bypassCache: true });
      if (!userInfo) {
        return;
      }

      try {
        const userData = await API.graphql(graphqlOperation(getUser, { id: userInfo.attributes.sub }))
        if (userData) {
          setUser(userData.data.getUser);
        }
      } catch (e) {
        console.log(e);
      }
    }
    fetchUser();
  }, [])

  return (
    <TabOneStack.Navigator>
      <TabOneStack.Screen
        name="HomeScreen"
        component={HomeScreen}
        options={{
          headerRightContainerStyle: {
            marginRight: 15,
          },
          headerLeftContainerStyle: {
            marginLeft: 15,
          },
          headerTitle: () => (
            <Ionicons name={"logo-twitter"} size={30} color={Colors.light.tint}/>
          ),
          headerRight: () => (
            <MaterialCommunityIcons name={"star-four-points-outline"} size={30} color={Colors.light.tint}/>
          ),
          headerLeft: () => (
            <ProfilePicture size={40} image={user?.image} />
          )
        }}
      />
    </TabOneStack.Navigator>
  );
}
Example #24
Source File: authHelper.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
//setupUser will add user to a cognito group and make its status to be "CONFIRMED",
//if groupName is specified, add the user to the group.
export async function setupUser(userPoolId: string, username: string, password: string, groupName?: string) {
  const cognitoClient = getConfiguredCognitoClient();
  await cognitoClient
    .adminCreateUser({
      UserPoolId: userPoolId,
      UserAttributes: [{ Name: 'email', Value: '[email protected]' }],
      Username: username,
      MessageAction: 'SUPPRESS',
      TemporaryPassword: tempPassword,
    })
    .promise();

  //   await cognitoClient
  //     .adminSetUserPassword({
  //       UserPoolId: userPoolId,
  //       Username: username,
  //       Password: password,
  //       Permanent: true,
  //     })
  //     .promise();

  const authDetails = new AuthenticationDetails({
    Username: username,
    Password: tempPassword,
  });
  const user = Amplify.Auth.createCognitoUser(username);
  await authenticateUser(user, authDetails, password);

  if (groupName) {
    await cognitoClient
      .adminAddUserToGroup({
        UserPoolId: userPoolId,
        Username: username,
        GroupName: groupName,
      })
      .promise();
  }
}
Example #25
Source File: actions.tsx    From platform with MIT License 5 votes vote down vote up
export async function logout(dispatch) {
  await Auth.signOut();
  await DataStore.clear();
  dispatch({ type: "LOGOUT" });
  localStorage.removeItem("currentUser");
  localStorage.removeItem("token");
}
Example #26
Source File: index.tsx    From TwitterClone with MIT License 4 votes vote down vote up
Footer = ({ tweet }: FooterContainerProps) => {

  console.log(tweet);

  const [user, setUser] = useState(null);
  const [myLike, setMyLike] = useState(null);
  const [likesCount, setLikesCount] = useState(tweet.likes.items.length);

  useEffect(() => {
    const fetchUser = async () => {
      const currentUser = await Auth.currentAuthenticatedUser();
      setUser(currentUser);

      const searchedLike = tweet.likes.items.find(
        (like) => like.userID === currentUser.attributes.sub
      );
      setMyLike(searchedLike);
    }
    fetchUser();
  }, [])

  const submitLike = async () => {
    const like = {
      userID: user.attributes.sub,
      tweetID: tweet.id,
    }

    try {
      const res = await API.graphql(graphqlOperation(createLike, { input: like }))
      setMyLike(res.data.createLike);
      setLikesCount(likesCount + 1);
    } catch (e) {
      console.log(e);
    }
  }

  const removeLike = async () => {
    try {
      await API.graphql(graphqlOperation(deleteLike, { input: { id: myLike.id } }))
      setLikesCount(likesCount - 1);
      setMyLike(null);
    } catch (e) {
      console.log(e);
    }
  }

  const onLike = async () => {
    if (!user) {
      return;
    }

    if (!myLike) {
      await submitLike()
    } else {
      await removeLike();
    }

  }

  return (
    <View style={styles.container}>
      <View style={styles.iconContainer}>
        <Feather name={"message-circle"} size={20} color={'grey'}/>
        <Text style={styles.number}>{tweet.numberOfComments}</Text>
      </View>
      <View style={styles.iconContainer}>
        <EvilIcons name={"retweet"} size={28} color={'grey'}/>
        <Text style={styles.number}>{tweet.numberOfRetweets}</Text>
      </View>
      <View style={styles.iconContainer}>
        <TouchableOpacity onPress={onLike}>
          <AntDesign name={!myLike ? "hearto" : "heart"} size={20} color={!myLike ? 'grey' : 'red'}/>
        </TouchableOpacity>
        <Text style={styles.number}>{likesCount}</Text>
      </View>
      <View style={styles.iconContainer}>
        <EvilIcons name={"share-google"} size={28} color={'grey'}/>
      </View>
    </View>
  )
}
Example #27
Source File: resetpassword.tsx    From RareCamp with Apache License 2.0 4 votes vote down vote up
export default function RestPassword() {
  const [form] = Form.useForm()
  const router = useRouter()
  useEffect(() => {
    form.setFieldsValue({
      username: router.query.username,
    })
  })
  const mutation = useMutation(
    ({ username, code, password }: RestPasswordPayload) =>
      Auth.forgotPasswordSubmit(
        username.trim(),
        code.trim(),
        password.trim(),
      ),
    {
      onSuccess: async () => {
        notification.success({
          message: 'Success!',
          description:
            'Password reset successful, Redirecting you in a few!',
          placement: 'topRight',
          duration: 1.5,
        })
        await router.push('/auth/login')
      },
      onError: async (err: Error) =>
        notification.error({
          message: 'Error resetting password',
          description: err.message,
          placement: 'topRight',
          duration: 3,
        }),
    },
  )

  return (
    <AuthLayout>
      <div>
        <Title level={3}>Rest your password?</Title>
        <p>
          Please enter you reset code and new password.
          <p>
            <span>or</span>
            <Link onClick={() => router.push('/auth/login')}>
              Login
            </Link>
          </p>
        </p>
      </div>
      <Form
        layout="vertical"
        name="reset_password_form"
        form={form}
        onFinish={mutation.mutate}
      >
        <Form.Item
          label={<span style={{ fontWeight: 500 }}>Email</span>}
          name="username"
          required={false}
          rules={[
            {
              required: true,
              message: 'Please input your email',
              type: 'email',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={<span style={{ fontWeight: 500 }}>Reset code</span>}
          name="code"
          required={false}
          rules={[
            {
              required: true,
              message: 'Please input your reset code',
              max: 6,
            },
          ]}
        >
          <Input placeholder="Your password reset code" />
        </Form.Item>

        <Form.Item
          style={{ marginBottom: '10px' }}
          label={
            <span style={{ fontWeight: 500 }}>New Password</span>
          }
          name="password"
          required={false}
          rules={[
            {
              required: true,
              message: 'Please input your password',
            },
          ]}
        >
          <Input.Password placeholder="Must be at least 8 characters" />
        </Form.Item>

        <Form.Item>
          <Button
            loading={mutation.isLoading}
            type="primary"
            htmlType="submit"
            block
            className="login-form-button"
          >
            Reset Password
          </Button>
        </Form.Item>
      </Form>
    </AuthLayout>
  )
}
Example #28
Source File: AuthContextProvider.tsx    From crossfeed with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
AuthContextProvider: React.FC = ({ children }) => {
  const [authUser, setAuthUser] = useState<AuthUser | null>(null);
  const [token, setToken] = usePersistentState<string | null>('token', null);
  const [org, setOrg] = usePersistentState<
    Organization | OrganizationTag | null
  >('organization', null);
  const [showAllOrganizations, setShowAllOrganizations] = usePersistentState<
    boolean
  >('showAllOrganizations', false);
  const [feedbackMessage, setFeedbackMessage] = useState<{
    message: string;
    type: AlertProps['severity'];
  } | null>(null);
  const cookies = useMemo(() => new Cookies(), []);

  const logout = useCallback(async () => {
    const shouldReload = !!token;

    localStorage.clear();
    await Auth.signOut();
    cookies.remove('crossfeed-token', {
      domain: process.env.REACT_APP_COOKIE_DOMAIN
    });

    if (shouldReload) {
      // Refresh the page only if the token was previously defined
      // (i.e. it is now invalid / has expired now).
      window.location.reload();
    }
  }, [cookies, token]);

  const handleError = useCallback(
    async (e: Error) => {
      if (e.message.includes('401')) {
        // Unauthorized, log out user
        await logout();
      }
    },
    [logout]
  );

  const api = useApi(handleError);
  const { apiGet, apiPost } = api;

  const getProfile = useCallback(async () => {
    const user: User = await apiGet<User>('/users/me');
    setAuthUser({
      ...user,
      isRegistered: user.firstName !== ''
    });
  }, [setAuthUser, apiGet]);

  const setProfile = useCallback(
    async (user: User) => {
      setAuthUser({
        ...user,
        isRegistered: user.firstName !== ''
      });
    },
    [setAuthUser]
  );

  const refreshUser = useCallback(async () => {
    if (!token && process.env.REACT_APP_USE_COGNITO) {
      const session = await Auth.currentSession();
      const { token } = await apiPost<{ token: string; user: User }>(
        '/auth/callback',
        {
          body: {
            token: session.getIdToken().getJwtToken()
          }
        }
      );
      setToken(token);
    }
  }, [apiPost, setToken, token]);

  const extendedOrg = useMemo(() => {
    return getExtendedOrg(org, authUser);
  }, [org, authUser]);

  const maximumRole = useMemo(() => {
    return getMaximumRole(authUser);
  }, [authUser]);

  const touVersion = useMemo(() => {
    return getTouVersion(maximumRole);
  }, [maximumRole]);

  const userMustSign = useMemo(() => {
    return getUserMustSign(authUser, touVersion);
  }, [authUser, touVersion]);

  useEffect(() => {
    refreshUser();
    // eslint-disable-next-line
  }, []);

  useEffect(() => {
    if (!token) {
      setAuthUser(null);
    } else {
      getProfile();
    }
  }, [token, getProfile]);

  return (
    <AuthContext.Provider
      value={{
        user: authUser,
        token,
        setUser: setProfile,
        refreshUser,
        setOrganization: setOrg,
        currentOrganization: extendedOrg,
        showAllOrganizations: showAllOrganizations,
        setShowAllOrganizations: setShowAllOrganizations,
        login: setToken,
        logout,
        setLoading: () => {},
        maximumRole,
        touVersion,
        userMustSign,
        setFeedbackMessage,
        ...api
      }}
    >
      {api.loading && (
        <div className="cisa-crossfeed-loading">
          <div></div>
          <div></div>
        </div>
      )}
      {feedbackMessage && (
        <Snackbar
          open={!!feedbackMessage}
          autoHideDuration={5000}
          onClose={() => setFeedbackMessage(null)}
        >
          <Alert
            onClose={() => setFeedbackMessage(null)}
            severity={feedbackMessage.type}
          >
            {feedbackMessage.message}
          </Alert>
        </Snackbar>
      )}
      {children}
    </AuthContext.Provider>
  );
}
Example #29
Source File: NewTweetScreen.tsx    From TwitterClone with MIT License 4 votes vote down vote up
export default function NewTweetScreen() {

  const [tweet, setTweet] = useState("");
  const [imageUrl, setImageUrl] = useState("");

  const navigation = useNavigation();

  const getPermissionAsync = async () => {
    if (Platform.OS !== 'web') {
      const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
  };

  useEffect(() => {
    getPermissionAsync()
  }, [])

  const pickImage = async () => {
    try {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
      });
      if (!result.cancelled) {
        setImageUrl(result.uri);
      }

      console.log(result);
    } catch (E) {
      console.log(E);
    }
  };

  const uploadImage = async () => {
    try {
      const response = await fetch(imageUrl);

      const blob = await response.blob();

      const urlParts = imageUrl.split('.');
      const extension = urlParts[urlParts.length - 1];

      const key = `${uuidv4()}.${extension}`;

      await Storage.put(key, blob);

      return key;

    } catch (e) {
      console.log(e);
    }
    return '';
  }

  const onPostTweet = async () => {
    let image;
    if (!!imageUrl) {
      image = await uploadImage();
    }

    try {
      const currentUser = await Auth.currentAuthenticatedUser({ bypassCache: true });

      const newTweet = {
        content: tweet,
        image,
        userID: currentUser.attributes.sub,
      }
      await API.graphql(graphqlOperation(createTweet, { input: newTweet }));
      navigation.goBack();
    } catch (e) {
      console.log(e);
    }
  }

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.headerContainer}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <AntDesign name="close" size={30} color={Colors.light.tint} />
        </TouchableOpacity>
        <TouchableOpacity style={styles.button} onPress={onPostTweet}>
          <Text style={styles.buttonText}>Tweet</Text>
        </TouchableOpacity>
      </View>
      <View style={styles.newTweetContainer}>
        <ProfilePicture image={'https://scontent.fkiv3-1.fna.fbcdn.net/v/t31.0-8/s960x960/22256588_1932617800312085_5686197942193420542_o.jpg?_nc_cat=110&_nc_sid=85a577&_nc_ohc=svjjE7DUkc0AX9yjcdC&_nc_ht=scontent.fkiv3-1.fna&tp=7&oh=1df4116c73c45a32ebad070704ca3333&oe=5F6ECD77'}/>
        <View style={styles.inputsContainer}>
          <TextInput
            value={tweet}
            onChangeText={(value) => setTweet(value)}
            multiline={true}
            numberOfLines={3}
            style={styles.tweetInput}
            placeholder={"What's happening?"}
          />
          <TouchableOpacity onPress={pickImage}>
            <Text style={styles.pickImage}>Pick a image</Text>
          </TouchableOpacity>
          <Image source={{ uri: imageUrl }} style={styles.image} />
        </View>
      </View>
    </SafeAreaView>
  );
}