How to use jwt-decode - 10 common examples

To help you get started, we’ve selected a few jwt-decode examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jsbin / jsbin / src / reducers / user.js View on Github external
...state,
      settings: getSettingsChange(
        `editor.${action.option}`,
        action,
        state.settings
      ),
    };
  }

  if (type === SET_TOKEN) {
    if (!action.value) {
      // anything falsy will sign out
      return defaultState;
    }

    const user = decode(action.value);
    const {
      username,
      pro,
      githubToken,
      // settings
    } = user;

    return {
      ...state,
      token: action.value,
      ...{
        username,
        pro,
        githubToken,
        // settings
      },
github cloudmu / react-redux-starter-kit / src / utils / apiUtils.js View on Github external
export function loadUserProfile() {
  try {
    const idToken = localStorage.getItem(ID_TOKEN);
    const userProfile = jwt_decode(idToken);
    const now = new Date().getTime() / 1000; // Date().getTime() returns milliseconds.
    // So divide by 1000 to get seconds
    if (now > userProfile.exp) {
      // user profile has expired.
      removeIdToken();
      return null;
    }
    return userProfile;
  } catch (err) {
    return null;
  }
}
github DSpace / dspace-angular / src / app / core / auth / models / auth-token-info.model.ts View on Github external
constructor(token: string) {
    this.accessToken = token.replace('Bearer ', '');
    try {
      const tokenClaims = decode(this.accessToken);
      // exp claim is in seconds, convert it se to milliseconds
      this.expires = tokenClaims.exp * 1000;
    } catch (err) {
      this.expires = 0;
    }
  }
}
github lancetw / react-isomorphic-bundle / src / client / admin / actions / UserActions.js View on Github external
return new Promise((resolve, reject) => {
    const user = jwtDecode(token)
    if (!user || !user.isAdmin) reject('invalid token')

    request
      .post('/api/admin/v1/users')
      .set('Accept', 'application/json')
      .set('Authorization', 'JWT ' + token)
      .send(form)
      .end(function (err, res) {
        if (!err && res.body) {
          resolve(res.body)
        } else {
          reject(err)
        }
      })
  })
}
github rjwats / esp8266-react / interface / src / authentication / AuthenticationWrapper.js View on Github external
.then(response => {
          const user = response.status === 200 ? jwtDecode(accessToken) : undefined;
          this.setState({ initialized: true, context: { ...this.state.context, user } });
        }).catch(error => {
          this.setState({ initialized: true, context: { ...this.state.context, user: undefined } });
github feathers-nuxt / template-app / template / src / client / utils / initAuth.js View on Github external
function getValidPayloadFromToken(token) {
  if (token) {
    try {
      var payload = decode(token)
      return payloadIsValid(payload) ? payload : undefined
    } catch (error) {
      return undefined
    }
  }
  return undefined
}
github kids-first / kf-portal-ui / src / components / Login / utils.js View on Github external
export const validateJWT = ({ jwt }) => {
  if (!jwt) return false;
  const validatedPayload = jwtDecode(jwt);
  const isCurrent = new Date(validatedPayload.exp * 1000).valueOf() > Date.now();
  const status = get(validatedPayload, 'context.user.status', '');
  const isApproved =
    isAdminToken({ validatedPayload }) || [status].map(toLower).includes('approved');
  return isCurrent && isApproved && validatedPayload;
};
github klarna / higher-order-components / src / withJwtProps.js View on Github external
buildState(token) {
      try {
        const decodedToken = jwtDecode(token)

        if (!propsMapping) {
          return decodedToken
        }

        return Object.keys(propsMapping).reduce((result, fromKey) => {
          const toKey = propsMapping[fromKey]
          result[toKey] = decodedToken[fromKey]

          return result
        }, {})
      } catch (e) {
        this.props.onJwtError(e)

        return {}
      }
github vtex-apps / store-graphql / node / directives / withCurrentProfile.ts View on Github external
vtex: { adminUserAuthToken, storeUserAuthToken },
    request: {
      headers: { cookie },
    },
  } = context
  const parsedCookies = parseCookie(cookie || '')

  const userToken = storeUserAuthToken
  const adminToken = adminUserAuthToken

  if (userToken) {
    return identity
      .getUserWithToken(userToken)
      .then(data => ({ userId: data.userId, email: data.user }))
  } else if (!userToken && !!adminToken) {
    const adminInfo = jwtDecode(adminToken) as any

    const callOpUserEmail = adminInfo && adminInfo.sub
    const isValidCallOp =
      callOpUserEmail &&
      (await isValidCallcenterOperator(context, callOpUserEmail))

    if (!isValidCallOp) {
      throw new AuthenticationError('User is not a valid callcenter operator')
    }

    const customerEmail = parsedCookies['vtex-impersonated-customer-email']

    return profile
      .getProfileInfo({ email: customerEmail, userId: '' })
      .then(({ email, userId }) => ({ email, userId }))
  }
github lancetw / react-isomorphic-bundle / src / client / admin / actions / PostActions.js View on Github external
return new Promise((resolve, reject) => {
    const token = getToken()
    const user = jwtDecode(token)
    if (!user || !user.isAdmin) reject('invalid token')

    request
      .get(LOCAL_PATH + '/api/admin/v1/posts')
      .set('Accept', 'application/json')
      .set('Authorization', 'JWT ' + token)
      .query({ offset: offset })
      .query({ limit: limit })
      .query({ start: start })
      .query({ end: end })
      .query({ keyword: keyword })
      .query({ status: status })
      .set('Accept', 'application/json')
      .end(function (err, res) {
        if (!err && res.body) {
          resolve(res.body)

jwt-decode

Decode JWT tokens, mostly useful for browser applications.

MIT
Latest version published 1 year ago

Package Health Score

82 / 100
Full package analysis

Popular jwt-decode functions