I'am building a backend API as NPM-package using aws-amplify and typescript. Wrapping all functionality works good. But i have an issue loading the currentSignedIn user.
My log-in script:
import {Auth} from "aws-amplify";
import "../app.config";
import {SignInOpts} from "@aws-amplify/auth/src/types";
import {CognitoUser} from "amazon-cognito-identity-js";
/**
* @name SignIn
* @description:
* sign in with username, password.
*
* @type function
* @async
* @param {string} usernameOrSignInOpts the email of the user
* @param {string} pw the password of the user
* @return {Promise<CognitoUser | any>}
*/
const SignIn = async (
usernameOrSignInOpts: string | SignInOpts,
pw?: string
): Promise<CognitoUser | any> => {
try {
return await Auth.signIn(usernameOrSignInOpts, pw);
} catch (err) {
throw err;
}
}
export {
SignIn
}
export default SignIn;
After this am trying to use sign in function (after i signed-up a new user and been confirmed). But it does catch an error: "The user is not authenticated".
I was searching a lot but no answers found for my issue.
My config file:
import Amplify from 'aws-amplify';
import awsExports from './aws-exports';
import * as dotenv from 'dotenv';
Amplify.configure(awsExports);
dotenv.config();
Script where sign in works:
import {SignUp, ConfirmSignUp, ResendSignUp} from "./Authentication/SignUp";
import SignIn from "./Authentication/SignIn";
import Validator from "./Services/Validator";
import {RegexPatterns, RegexTypes} from "./Enums/Regex";
import SignOut from "./Authentication/SignOut";
import DeleteUser from "./Authentication/DeleteUser";
import UserManagement, {ChangePassword} from "./Authentication/UserManagement";
import "./app.config";
import {Auth} from "aws-amplify";
import NotAuthorizedException from "./Exceptions/NotAuthorizedException";
export default {
SignIn,
SignUp,
SignOut,
ConfirmSignUp,
ResendSignUp,
Validator,
UserManagement,
RegexPatterns,
DeleteUser,
}
SignIn('xxxxxx', 'xxxx').then(() =>
Auth.currentAuthenticatedUser()
.then(authenticatedUser => {
console.log(authenticatedUser);
}).catch(err => {
throw new NotAuthorizedException(err);
}));
But if i seperate Sign-in function and cuurentAuthenticatedUser i will get an error. My question is does sign-in save a session for the user somewhere? I want to be able to call cuurentAuthenticatedUser in another file in my application and get the current user.
In short, Why signIn function is not able to save a session with my logged-in user? I can only login at the same runtime and after that the user is not authenticated.
help pls!
Op, you may need to add a conditional statement, like so:
if (!authenticatedUser) return <Authenticator /> (or your custom sign in component);