0.5.3 • Published 10 months ago

js-session-manager v0.5.3

Weekly downloads
-
License
-
Repository
-
Last release
10 months ago

@cognixus/js-session-manager 0.4.8

Session manager for Javascript/Typescript projects

You can use @cognixus/js-session-manager to easily call Cognixus common RPCs like AuthService, and also client and user token handling

Install

  • yarn: yarn --registry https://nexus.cognixus.com/repository/npm-group/ add @cognixus/js-session-manager
  • npm: npm --registry https://nexus.cognixus.com/repository/npm-group/ install @cognixus/js-session-manager

Import syntax

import { jsm } from "@cognixus/js-session-manager";

Jsm Methods

  • config (JsmConfig): js-session-manager configuration
    • baseUrl (string): Base url for APIs
    • clientCredentials (ClientCredentials)
      • clientId (string)
      • clientSecret (string)
    • headerConfig (HeaderConfig): Customize header names
      • appInstanceId (string): (Default appinstanceid)
      • authorization (string): (Default Grpc-Metadata-Authorization)
      • nonce (string) (Default Grpc-Metadata-Nonce)
    • timeout (number): Timeout for each API call (Default 10s)
    • responseInCamelCase (boolean) : Response keys in camel case (Default false)
  • This function needs to be called before accessing other API functions
jsm.setConfig({
  baseUrl: "https://api.example.com/api",
  clientCredentials: {
    clientId: "client-id",
    clientSecret: "qwer-clientsecret",
  },
  headerConfig: {
    appInstanceId: "Custom-AppInstanceId-Name",
    authorization: "Custom-Authorization-Header-Name",
    nonce: "Custom-Nonce-Header-Name",
  },
  timeout: 3000,
  responseInCamelCase: true,
});

  • To get the current JsmConfig that was set
console.log(jsm.getConfig());

  • You may skip this method if your app runs fully on the client side.
  • If this method is used, it MUST called before setConfig()
  • Pass in a cookies library that supports both client and server
  • Call the setStorageLibrary() function twice, once in the server side and once in the client side.

  • storageLibrary (StorageLibrary): Storage with available functions below

    • set (name: string, value: any, opts?: any) => void
    • get (name: string, opts?: any) => any;
    • getAll (name: string, opts?: any)? => any;
    • remove (name: string, opts?: any) => void;

Nuxt2 Example

//nuxt.config.js
modules: ["cookie-universal-nuxt"],
  //.vue files
  jsm.setStorageLibrary(this.$cookies);

Nuxt3 Example

// plugins/js_session_manager.js
import { jsm } from "@cognixus/js-session-manager";

export default defineNuxtPlugin((_) => {
  jsm.setStorageLibrary({
    set: (name, value, _) => {
      const cookie = useCookie(name);
      cookie.value = value;
    },
    get: (name, _) => {
      const cookie = useCookie(name);
      return cookie.value;
    },
    remove: (name, _) => {
      const cookie = useCookie(name);
      cookie.value = null;
    },
  });
});

TokenCaller

Calls API dynamically depending on whether user token exists

  • User token does not exists, will use ClientTokenCaller
  • User token exists, will use UserTokenCaller

  • options (any): API options

    • tokenCallerType (TokenCallerType): (OPTIONAL) (Default: TokenCallerType.Any)
      • "ANY"
      • "CLIENT"
      • "USER"
    • requestType (RequestType)
      • "GET"
      • "POST"
      • "PUT"
      • "PATCH"
      • "DELETE"
    • url (string): API Endpoint without the baseUrl
    • headers (any): Extra headers to be passed to the API
    • parameters (any): The data that should be passed to the API
    • maxRetry (number): Max retry count (Default: 1)
    • includeNonce (boolean): (Default: true)
      • true, include nonce in the header of the request
      • false, do not include nonce in the header of the request
    • useClientIdSecretCallOptions (boolean): (Default: false)
      • true, use Basic auth token from clientId and clientSecret from JsmConfig
      • false, use Client token from calling GetClientToken RPC
await jsm.tokenCaller.callApi({
  requestType: "DELETE",
  url: "/post",
  headers: {
    "Any-Header": 123456,
  },
  parameters: {
    postId: "1287wdankn1",
  },
  maxRetry: 0,
});

Services

AuthService

Returns whether we can renew the user token

console.log(jsm.services.auth.canRenewToken);

Calls the Authenticate rpc

  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.authenticate();

const response = await jsm.services.auth.authenticate({ maxRetry: 3 });

Calls the ChangePassword rpc

  • request (ChangePasswordRequest): Refer to ChangePasswordRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.changePassword({
  currentPassword: "password-1",
  newPassword: "password-2",
  lang: 3,
});

const response = await jsm.services.auth.changePassword(
  {
    currentPassword: "password-1",
    newPassword: "password-2",
    lang: 3,
  },
  { maxRetry: 3 }
);

Calls the CreatePrincipal rpc

  • request (CreatePrincipalRequest): Refer to CreatePrincipalRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.createPrincipal({
  user: {
    logins: [
      {
        loginId: "test@email.com",
        loginType: 1,
      },
    ],
    roles: ["USER"],
    namespace: 0,
  },
});

const response = await jsm.services.auth.createPrincipal(
  {
    user: {
      logins: [
        {
          loginId: "test@email.com",
          loginType: 1,
        },
      ],
      roles: ["USER"],
      namespace: 0,
    },
  },
  { maxRetry: 3 }
);

Calls the EditPrincipal rpc

  • request (EditPrincipal): Refer to EditPrincipal from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.editPrincipal({
  principalId: "principal-1234",
  editFields: [
    {
      editType: 2,
      active: false,
    },
  ],
});

const response = await jsm.services.auth.editPrincipal(
  {
    principalId: "principal-1234",
    editFields: [
      {
        editType: 2,
        active: false,
      },
    ],
  },
  { maxRetry: 3 }
);

Calls the GetWeb3Token rpc

  • request (GetWeb3TokenRequest)
    • address (string)
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.getWeb3Token({
  address: "0x94f64772371BDhC1C1a217b0faee22D8Bc3b2F72",
});

const response = await jsm.services.auth.getWeb3Token(
  {
    address: "0x94f64772371BDhC1C1a217b0faee22D8Bc3b2F72",
  },
  { maxRetry: 3 }
);

Calls the GetPrincipal rpc

  • request (GetPrincipalRequest): Refer to GetPrincipal from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.getPrincipal({
  namespace: 0,
  principalId: "principal-id-1",
});

const response = await jsm.services.auth.getPrincipal(
  {
    namespace: 0,
    principalId: "principal-id-1",
  },
  { maxRetry: 3 }
);

Calls the ListLoginDevice rpc

  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.listLoginDevices();

const response = await jsm.services.auth.listLoginDevices({ maxRetry: 3 });

Calls the RenewToken rpc, only callable after jsm.services.auth.signIn() is successful

  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
await jsm.services.auth.renewToken();

await jsm.services.auth.renewToken({ maxRetry: 2 });

Calls the ResetPassword rpc

  • request (ResetPasswordRequest): Refer to ResetPasswordRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.resetPassword({
  mobileNumber: "+60123456789",
  newPassword: "abc123",
  verificationCode: "123456",
});

const response = await jsm.services.auth.resetPassword(
  {
    mobileNumber: "+60123456789",
    newPassword: "abc123",
    verificationCode: "123456",
  },
  { maxRetry: 3 }
);

Calls the RevokeToken rpc

  • request (any)
    • accessToken (string): Access token to be revoked, if not passed, will used the one saved in the session (Default: undefined)
    • isRemoveRelatedToken (boolean): Removes related token from same user (Default: true)
    • isRemoveByUserToken (boolean): Removes current user token if exist, else it will fall back to remove current user (Default: false)
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
await jsm.services.auth.revokeToken({
  isRemoveRelatedToken: false,
});

await jsm.services.auth.revokeToken(
  {
    isRemoveRelatedToken: false,
  },
  { maxRetry: 2 }
);


Set userToken to StorageHelper

  • request (any)
    • token (string): User's user token
    • expiry (Date): User's token expiry
await jsm.services.auth.saveUserToken({
  token: "user-token",
  expiry: new Date(),
});

Calls the SendForgotPwdOtp rpc

  • request (SendForgotPasswordOtpRequest): Refer to SendForgotPwdOtpRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.sendForgotPasswordOtp({
  mobileNumber: "+60123456789",
  lang: 3,
});

const response = await jsm.services.auth.sendForgotPasswordOtp(
  {
    mobileNumber: "+60123456789",
    lang: 3,
  },
  { maxRetry: 3 }
);

Calls the SendCredentialsResetLink rpc

  • request (SendCredentialsResetLinkRequest): Refer to SendCredentialsResetLinkRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.sendCredentialsResetLink({
  email: "hannzern.sim@cognixus.com",
  isEmailReset: true,
});

const response = await jsm.services.auth.sendCredentialsResetLink(
  {
    email: "hannzern.sim@cognixus.com",
    isEmailReset: false,
  },
  { maxRetry: 3 }
);

Calls the UserSignIn rpc

  • request (UserSignInRequest): Refer to UserSignInRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.signIn({
  login: "+60123456789",
  password: "Test@123",
  loginType: 2,
  rememberMe: true,
  skipAppInsIdVerification: true,
  isSingleLoginSession: false,
});

const response = await jsm.services.auth.signIn(
  {
    login: "+60123456789",
    password: "Test@123",
    loginType: 2,
    rememberMe: true,
    skipAppInsIdVerification: true,
    isSingleLoginSession: false,
  },
  { maxRetry: 0 }
);

Calls the VerifyForgotPwdOtp rpc

  • request (VerifyForgotPasswordOtpRequest): Refer to VerifyForgotPwdOtpRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
const response = await jsm.services.auth.verifyForgotPasswordOtp({
  mobileNumber: "+60123456789",
  otp: "123456",
});

const response = await jsm.services.auth.verifyForgotPasswordOtp(
  {
    mobileNumber: "+60123456789",
    otp: "123456",
  },
  { maxRetry: 3 }
);

NotificationService

Calls the CountUnreadNotifications rpc

  • request (CountUnreadNotificationsRequest): Refer to CountUnreadNotificationsRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.notification.countUnreadNotifications({
  days: 10,
  notificationMethods: [NotificationMethod.sms],
});

Calls the ListNotifications rpc

  • request (ListNotificationRequest): Refer to ListNotificationRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.notification.listNotifications({
  pageRequest: {
    pageNum: 1,
    pageSize: 10,
  },
  orderCriteria: [
    {
      orderColumn: "createdAt",
      orderType: 1,
    },
  ],
  searchQuery: {
    condition: {
      searchField: "notificationMethod",
      matchOp: 1,
      matchValues: ["PUSH"],
    },
  },
});

const response = await jsm.services.notification.listNotifications(
  {
    pageRequest: {
      pageNum: 1,
      pageSize: 10,
    },
    orderCriteria: [
      {
        orderColumn: "createdAt",
        orderType: 1,
      },
    ],
    searchQuery: {
      condition: {
        searchField: "notificationMethod",
        matchOp: 1,
        matchValues: ["PUSH"],
      },
    },
  },
  {
    maxRetry: 3,
    tokenCallerType: "CLIENT",
  }
);

Calls the SendNotification rpc

  • request (SendNotificationRequest): Refer to SendNotificationRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.notification.sendNotification({
  recipients: {
    ids: ["recipient-1"],
  },
  notificationMsg: {
    content: "Content here",
    notificationMethod: 0,
    emailOption: {
      subject: "-",
      attachments: [],
    },
  },
  notificationCategory: "category-1",
  priority: 0,
  isStoreOnly: true,
});

const response = await jsm.services.notification.sendNotification(
  {
    recipients: {
      ids: ["recipient-1"],
    },
    notificationMsg: {
      content: "Content here",
      notificationMethod: 0,
      emailOption: {
        subject: "-",
        attachments: [],
      },
    },
    notificationCategory: "category-1",
    priority: 0,
    isStoreOnly: true,
  },
  {
    maxRetry: 3,
    tokenCallerType: "CLIENT",
  }
);

Calls the UpdateNotificationStatus rpc

  • request (UpdateNotificationStatusRequest): Refer to UpdateNotificationStatusRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.notification.updateNotificationStatus({
  nid: "notification-id-here",
  newStatus: 1,
});

const response = await jsm.services.notification.updateNotificationStatus(
  {
    nid: "notification-id-here",
    newStatus: 1,
  },
  {
    maxRetry: 3,
    tokenCallerType: "CLIENT",
  }
);

Calls the UpdateUnreadNotificationsToRead rpc

  • request (UpdateUnreadNotificationsToReadRequest): Refer to UpdateUnreadNotificationsToReadRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response =
  await jsm.services.notification.updateUnreadNotificationsToRead({
    notificationMethods: [NotificationMethod.sms],
  });

VerificationService

Calls the CheckVerificationCodeValidity rpc

  • request (CheckVerificationCodeValidityRequest): Refer to CheckVerificationCodeValidityRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.verification.checkVerificationCodeValidity({
  verificationCode: "ABC123",
  verificationReason: "RESET_PASSWORD",
});

const response = await jsm.services.verification.checkVerificationCodeValidity(
  {
    verificationCode: "ABC123",
    verificationReason: "RESET_PASSWORD",
  },
  {
    maxRetry: 3,
    tokenCallerType: "CLIENT",
  }
);

Calls the SendOtp rpc

  • request (SendOtpRequest): Refer to SendOtpRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.verification.sendOtp({
  mobileNumber: "+60123456789",
  projectCode: "PIF",
  verificationReason: "FORGOT_PWD",
  codeValidityPeriodInMin: 5,
  isCheckPrincipalExist: false,
});

const response = await jsm.services.verification.sendOtp(
  {
    mobileNumber: "+60123456789",
    projectCode: "PIF",
    verificationReason: "FORGOT_PWD",
    codeValidityPeriodInMin: 5,
    isCheckPrincipalExist: false,
  },
  {
    maxRetry: 3,
    tokenCallerType: "CLIENT",
  }
);

Calls the SendOtp rpc

  • request (SendOtpRequest): Refer to SendOtpRequest from the proto
  • options (ApiCallOptions?)
    • maxRetry (number) default = 1
    • tokenCallerType (TokenCallerType) default = TokenCallerType.ANY
const response = await jsm.services.verification.verifyCode({
  codeOwner: "+60123456789",
  verificationCode: "132465",
  verificationReason: "FORGOT_PWD",
  nextVerificationCodeOption: {
    isRequired: true,
    verificationReason: "FORGOT_PWD",
    codeValidityPeriodInMin: 5,
  },
});

const response = await jsm.services.verification.verifyCode(
  {
    codeOwner: "+60123456789",
    verificationCode: "132465",
    verificationReason: "FORGOT_PWD",
    nextVerificationCodeOption: {
      isRequired: true,
      verificationReason: "FORGOT_PWD",
      codeValidityPeriodInMin: 5,
    },
  },
  {
    maxRetry: 3,
    tokenCallerType: "CLIENT",
  }
);

0.5.3

10 months ago

0.5.2

10 months ago

0.5.1

10 months ago

0.5.0

10 months ago

0.4.9

10 months ago

0.4.8

10 months ago