config#USER_SESSION TypeScript Examples

The following examples show how to use config#USER_SESSION. 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: Logout.tsx    From glific-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
Logout: React.SFC<LogoutProps> = ({ match }) => {
  const { setAuthenticated } = useContext(SessionContext);
  const [redirect, setRedirect] = useState(false);
  const client = useApolloClient();
  const { t } = useTranslation();
  const location = useLocation();

  // let's notify the backend when user logs out
  const userLogout = () => {
    // get the auth token from session
    axios.defaults.headers.common.authorization = getAuthSession('access_token');
    axios.delete(USER_SESSION);
  };

  const handleLogout = () => {
    userLogout();
    // clear local storage auth session
    clearAuthSession();

    // update the context
    setAuthenticated(false);

    // clear local storage user session
    clearUserSession();

    // clear role & access permissions
    resetRolePermissions();

    // clear local storage list sort session
    clearListSession();

    // clear apollo cache
    client.clearStore();

    setRedirect(true);
  };

  useEffect(() => {
    // if user click on logout menu
    if (match.params.mode === 'user') {
      handleLogout();
    }
  }, []);

  const dialog = (
    <DialogBox
      title={t('Your session has expired!')}
      buttonOk={t('Login')}
      handleOk={() => handleLogout()}
      handleCancel={() => handleLogout()}
      skipCancel
      alignButtons="center"
    >
      <div style={divStyle}>{t('Please login again to continue.')}</div>
    </DialogBox>
  );

  if (redirect) {
    return <Redirect to={{ pathname: '/login', state: location.state }} />;
  }

  return dialog;
}
Example #2
Source File: Login.tsx    From glific-frontend with GNU Affero General Public License v3.0 4 votes vote down vote up
Login: React.SFC<LoginProps> = () => {
  const { setAuthenticated } = useContext(SessionContext);
  const [authError, setAuthError] = useState('');
  const { i18n, t } = useTranslation();
  const history = useHistory();
  const location: any = useLocation();

  // function to unauthorize access
  const accessDenied = () => {
    setAuthError(notApprovedMsg);
    clearAuthSession();
    clearUserSession();
  };

  // get the information on current user
  const [getCurrentUser, { data: userData, error: userError }] = useLazyQuery(GET_CURRENT_USER);

  useEffect(() => {
    if (userData) {
      // set the current user object
      setUserSession(JSON.stringify(userData.currentUser.user));

      // get the roles
      const { roles } = userData.currentUser.user;

      // check for user role none or empty
      if ((roles.includes('None') && roles.length === 1) || roles.length === 0) {
        accessDenied();
      } else {
        // needed to redirect after login
        setAuthenticated(true);

        // role & access permissions
        setUserRolePermissions();

        // set the language
        if (i18n.changeLanguage) {
          i18n.changeLanguage(userData.currentUser.user?.language.locale);
        }

        if (location.state) {
          history.push(location.state);
        } else {
          // redirect to chat
          history.push('/chat');
        }
      }
    }
    if (userError) {
      accessDenied();
    }
  }, [userData, userError, setAuthenticated]);

  const formFields = [
    {
      component: PhoneInput,
      name: 'phoneNumber',
      type: 'phone',
      placeholder: t('Your phone number'),
      helperText: t('Please enter a phone number.'),
    },
    {
      component: Input,
      name: 'password',
      type: 'password',
      placeholder: t('Password'),
    },
  ];

  const FormSchema = Yup.object().shape({
    phoneNumber: Yup.string().required(t('Input required')),
    password: Yup.string().required(t('Input required')),
  });

  const initialFormValues = { phoneNumber: '', password: '' };

  const onSubmitLogin = (values: any) => {
    setAuthError('');
    axios
      .post(USER_SESSION, {
        user: {
          phone: values.phoneNumber,
          password: values.password,
        },
      })
      .then((response: any) => {
        const responseString = JSON.stringify(response.data.data);
        getCurrentUser();
        setAuthSession(responseString);
      })
      .catch((error) => {
        setAuthError(t('Invalid phone or password.'));
        // add log's
        setLogs(`phoneNumber:${values.phoneNumber} URL:${USER_SESSION}`, 'info');
        setLogs(error, 'error');
      });
  };

  return (
    <Auth
      pageTitle={t('Login to your account')}
      buttonText={t('Login')}
      alternateLink="registration"
      alternateText={t('Create a new account')}
      mode="login"
      formFields={formFields}
      linkText={t('Forgot Password?')}
      linkURL="resetpassword-phone"
      validationSchema={FormSchema}
      saveHandler={onSubmitLogin}
      initialFormValues={initialFormValues}
      errorMessage={authError}
    />
  );
}