Get current user information in vue

Viewed 34

I want to print the user information on my profile page in the project I am logged in using amazon cognito. I tried something but it didn't work.I want to get the data seen in ss.ss below shows the data that is local storage. Can I show UserAttributes data on page?enter image description here

Template

<template>
  <div>
    <PageHeader />
  </div>
  <!--begin::Row-->
  <div class="row g-5">
    <div class="col-lg-9">
      <div class="card card-flush card-stretch shadow">
        <div class="card-body mt-15">
          <h3 class="card-title py-2">
            {{ $t("settingsInfo.name") }} :
            <input v-model="given_name" type="text" />
          </h3>
          <h3 class="card-title py-2">{{ $t("settingsInfo.surname") }} :</h3>
          <h3 class="card-title py-2">{{ $t("settingsInfo.company") }} :</h3>
          <h3 class="card-title py-2">{{ $t("settingsInfo.email") }} :</h3>
        </div>
        <div class="card-footer"></div>
      </div>
    </div>
  <!--end::Row-->
</template>

Script

<script lang="ts">
    
    export default defineComponent({
      name: "settings-menu",
      components: {
        PageHeader,
      },
      setup() {
        const router = useRouter();
        const i18n = useI18n();
        const store = useStore();
        const userInfo = ref("");
        const userName = ref("");
    
        onMounted(() => {
          const user = UserService.getUserInfo();
          userInfo.value = user ? user["given_name"] : "";
          userName.value = user ? user["given_name"] + " " + user["family_name"] : "";
        });
    
        const currentUser = computed(() => {
          return store.getters.currentUser;
        });
    
        watch(currentUser, () => {
          const user = UserService.getUserInfo();
          userInfo.value = user ? user["given_name"] : "";
          userName.value = user ? user["given_name"] + " " + user["family_name"] : "";
        });
        return {
          userInfo,
        };
      },
    });
    </script>
1 Answers

Perhaps you can find what you need in the following code snippet. First call getUser, then getAttributes:

import { CognitoUserPool, AuthenticationDetails, CognitoUser, CognitoUserAttribute } from 'amazon-cognito-identity-js';

export default
{
  data: function()
  {
    var a =
      {
        userPool: null,
        authData: null,
        curUser: null,
        first_name: '',
        last_name: '',
        email: '',
      };
    return a;
  },
  methods:
  {
    getUserPool: function()
    {
      this.userPool = new CognitoUserPool(
        {
          UserPoolId : process.env.AWS_COGNITO_USER_POOL_ID,
          ClientId : process.env.AWS_COGNITO_CLIENT_ID,
        });
    },
    getUser: function(email)
    {
      if(this.userPool == null) this.getUserPool();
      this.curUser = new CognitoUser(
        {
          Username : email.toLowerCase(),
          Pool : this.userPool
        });
    },
    resendConfirm: function(email,cb_ok,cb_err)
    {
      this.getUser(email.toLowerCase());
      this.curUser.resendConfirmationCode(function(err,result)
      {
        if(err) cb_err(err);
        else cb_ok(result);
      });
    },
    confirmCode: function(email,code,cb_ok,cb_err)
    {
      this.getUser(email.toLowerCase());
      this.curUser.confirmRegistration(code, true,function(err,result)
      {
        if(err) cb_err(err);
        else cb_ok(result);
      });
    },
    forgot: function(email,cb_ok,cb_err)
    {
      this.getUser(email.toLowerCase());
      this.curUser.forgotPassword(
        {
          onSuccess: function(data)
          {
            // successfully initiated reset password request
            if(process.env.NODE_ENV === 'development') console.log('CodeDeliveryData from forgotPassword: ' + data);
            cb_ok(data);
          },
          onFailure: function(err)
          {
            cb_err(err);
          },
        }
      );
    },
    reset: function(email,code,password,cb_ok,cb_err)
    {
      this.getUser(email.toLowerCase());
      this.curUser.confirmPassword(code,password,
        {
          onSuccess: function()
          {
            // password confirmed
            cb_ok();
          },
          onFailure: function(err)
          {
            cb_err(err);
          },
        }
      );
    },
    login: function(email,password,cb_ok,cb_err)
    {
      let self = this;
      email = email.toLowerCase();
      this.getUser(email);
      this.curUser.authenticateUser(new AuthenticationDetails(
        {
          Username : email,
          Password : password,
        }),
        {
          onSuccess: function (result)
          {
            self.getAttributes(cb_ok);
          },

          onFailure: function(err)
          {
            cb_err(err);
          },

        });
    },
    register: function(first_name,last_name,email,password,cb_ok,cb_err)
    {
      if(this.userPool == null) this.getUserPool();
      this.userPool.signUp(email.toLowerCase(),password,
        [
          new CognitoUserAttribute({Name: 'given_name', Value: first_name}),
          new CognitoUserAttribute({Name: 'family_name', Value: last_name}),
        ],
        null,function(err,result)
        {
          if(err)
          {
            if(err.statusCode != 200) cb_err(err);
            else cb_ok();
          }
          else cb_ok();
        });
    },
    signOut: function(router)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      if(this.curUser)
      {
        this.curUser.signOut();
        this.curUser = null;
        router.push('/login');
      }
    },
    isLogged: function (next)
    {
      return isAuthenticated.call(this,next);
    },
    getAttributes: function(cb_ok,cb_err)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      if(this.curUser)
      {
        let self = this;
        // NOTE: getSession must be called to authenticate user before calling getUserAttributes
        this.curUser.getSession((err,session) =>
        {
          if(err)
          {
            if(process.env.NODE_ENV === 'development') console.error(err);
            if(typeof cb_err === 'function') cb_err(err);
          }
          else if(session.isValid())
          {
            self.curUser.getUserAttributes(function(err, attributes)
            {
              if(err)
              {
                if(process.env.NODE_ENV === 'development') console.error(err);
                if(typeof cb_err === 'function') cb_err(err);
              }
              else
              {
                let i, name;
                for(i = 0; i < attributes.length; i++)
                {
                  name = attributes[i].getName();
                  if(name === 'given_name')
                  {
                    localStorage.setItem('Cognito.first_name',attributes[i].getValue());
                    self.first_name = attributes[i].getValue();
                  }
                  else if(name === 'family_name')
                  {
                    localStorage.setItem('Cognito.last_name',attributes[i].getValue());
                    self.last_name = attributes[i].getValue();
                  }
                  else if(name === 'email')
                  {
                    localStorage.setItem('Cognito.email',attributes[i].getValue().toLowerCase());
                    self.email = attributes[i].getValue().toLowerCase();
                  }
                }
                if(typeof cb_ok === 'function') cb_ok();
              }
            });
          }
        });
      }
    },
    changeEmail: function(email,cb_ok,cb_err)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      let self = this;
      // NOTE: getSession must be called to authenticate user before calling updateAttributes
      this.curUser.getSession((err,session) =>
      {
        if(err)
        {
          if(process.env.NODE_ENV === 'development') console.error(err);
          if(typeof cb_err === 'function') cb_err(err);
        }
        else if(session.isValid())
        {
          email = email.toLowerCase();
          this.curUser.updateAttributes(
            [
              new CognitoUserAttribute({
                Name: 'email',
                Value: email
              }),
            ],
            function(err, result)
            {
              if(err && err.statusCode != 200) cb_err(err);
              else
              {
                localStorage.setItem('Cognito.email', email);
                self.email = email;
                cb_ok();
              }
            });
        }
      });
    },
    emailCode: function(cb_ok,cb_err)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      let self = this;
      // NOTE: getSession must be called to authenticate user
      this.curUser.getSession((err,session) =>
      {
        if (err)
        {
          if (process.env.NODE_ENV === 'development') console.error(err);
          if (typeof cb_err === 'function') cb_err(err);
        }
        else if (session.isValid())
        {
          this.curUser.getAttributeVerificationCode('email',
            {
              onSuccess: cb_ok,
              onFailure: cb_err,
              inputVerificationCode: null
            });
        }
        else cb_err({ message: 'Invalid session in auth.emailCode' });
      });
    },
    verifyEmail: function(code,cb_ok,cb_err)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      let self = this;
      // NOTE: getSession must be called to authenticate user
      this.curUser.getSession((err,session) =>
      {
        if (err)
        {
          if (process.env.NODE_ENV === 'development') console.error(err);
          if (typeof cb_err === 'function') cb_err(err);
        }
        else if (session.isValid())
        {
          this.curUser.verifyAttribute('email',code,
            {
              onSuccess: cb_ok,
              onFailure: cb_err,
            });
        }
        else cb_err({ message: 'Invalid session in auth.verifyEmail' });
      });
    },
    updateProfile: function(info,cb_ok,cb_err)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      let self = this;
      // NOTE: getSession must be called to authenticate user before calling updateAttributes
      this.curUser.getSession((err,session) =>
      {
        if(err)
        {
          if(process.env.NODE_ENV === 'development') console.error(err);
          if(typeof cb_err === 'function') cb_err(err);
        }
        else if(session.isValid())
        {
          this.curUser.updateAttributes(
            [
              new CognitoUserAttribute({
                Name: 'given_name',
                Value: info.first_name
              }),
              new CognitoUserAttribute({
                Name: 'family_name',
                Value: info.last_name
              }),
            ],
            function(err, result)
            {
              if(err && err.statusCode != 200) cb_err(err);
              else
              {
                localStorage.setItem('Cognito.first_name', info.first_name);
                localStorage.setItem('Cognito.last_name', info.last_name);
                self.first_name = info.first_name;
                self.last_name = info.last_name;
                cb_ok();
              }
            });
        }
      });
    },
    changePass: function(old_pass,new_pass,cb_ok,cb_err)
    {
      if(!this.curUser)
      {
        if(!this.userPool) this.getUserPool();
        if(this.userPool) this.curUser = this.userPool.getCurrentUser();
      }
      this.curUser.changePassword(old_pass,new_pass, function(err,result)
      {
        if(err)
        {
          if(err.statusCode != 200) cb_err(err);
          else cb_ok();
        }
        else cb_ok();
      });
    },
    refreshToken: function(cb_ok,cb_err)
    {
      let pool;
      if(this && this.userPool) pool = this.userPool;
      else pool = new CognitoUserPool(
        {
          UserPoolId : process.env.AWS_COGNITO_USER_POOL_ID,
          ClientId : process.env.AWS_COGNITO_CLIENT_ID,
        });
      this.userPool = pool;
      this.curUser = pool.getCurrentUser();
      if(this.curUser != null)
      {
        this.curUser.getSession((err,session) =>
        {
          if(err)
          {
            if(process.env.NODE_ENV === 'development') console.error(err);
            cb_err(false);
          }
          else
          {
            //if(process.env.NODE_ENV === 'development') console.log('session validity: ' + session.isValid());
            if(session.isValid()) cb_ok();
            else cb_err(true);
          }
        });
      }
      else cb_err(false);
    }
  }
};

// this function must be accessible to the VueRouter.beforeEach global guard
export function isAuthenticated(next)
{
  let pool;
  if(this && this.userPool) pool = this.userPool;
  else pool = new CognitoUserPool(
    {
      UserPoolId : process.env.AWS_COGNITO_USER_POOL_ID,
      ClientId : process.env.AWS_COGNITO_CLIENT_ID,
    });
  let cognitoUser = pool.getCurrentUser();
  if(cognitoUser != null)
  {
    cognitoUser.getSession((err,session) =>
    {
      if(err)
      {
        if(process.env.NODE_ENV === 'development') console.error(err);
        next('/login');
      }
      else
      {
        //if(process.env.NODE_ENV === 'development') console.log('session validity: ' + session.isValid());
        if(session.isValid()) next();
        else next('/login');
      }
    });
  }
  else next('/login');
}

export function getUserID()
{
  return localStorage.getItem('CognitoIdentityServiceProvider.' + process.env.AWS_COGNITO_CLIENT_ID + '.LastAuthUser');
}

export function getTokenID()
{
  let user = getUserID();
  if(user && user.length)
    return localStorage.getItem('CognitoIdentityServiceProvider.' + process.env.AWS_COGNITO_CLIENT_ID + '.' + user + '.idToken');
  else return null;
}
Related