check-token-from-serverless-env

1.2.3 • Public • Published

check token

This project serves serverless methods or where process.env exists.

After encrypting the userId inside the webtoken use this method to verify that the sent userId matches the userId inside the sent webtoken. This way it will not be necessary to query an external api to validate if the token matches the userId.

It also has a method to decrypt and encrypt the token based on the secretWebToken variable which must exist in env as its secret string.

Methods

encrypt

const {encrypt} = require('check-token-from-serverless-env')
try{
    let webtokenstring = encrypt({userId:"xpto", otherThing:234})
} catch(e){
    //
}

decrypt

const {decrypt} = require('check-token-from-serverless-env')
exports.handler = async (event) => {
    //get token from header or json body
    const webtokenstring = event?.headers?.token || eventBody?.token
    try{
        let myObject = decrypt(webtokenstring);
        //here supouse to have userId
        let userId = myObject?.userId
    } catch(e){
        //
    }
}

checkTokenByUserId


const {checkTokenByUserId} = require('check-token-from-serverless-env')


exports.handler = async (event) => {
    //get web token from header or json body
    const webtokenstring = event?.headers?.token || eventBody?.token
    //get userId from header or json body
    const userId = event?.headers?.userId || eventBody?.userId
    if(!checkTokenByUserId(webtokenstring, userId)){
        return {
            statusCode: 403,
            body: JSON.stringify({ success: false, message:["wrong token or userId"] })
        };
    }
    //...
}

| Remember: Use need to use your token like this

{
    userId: 'foo',
    ...
}

checkTokenByEvent


const {checkTokenByEvent} = require('check-token-from-serverless-env')


exports.handler = async (event) => {
    //get web token, userId or user_id from event (body, header, path)
    if(!checkTokenByEvent(event)){
        return {
            statusCode: 403,
            body: JSON.stringify({ success: false, message:["wrong token or userId"] })
        };
    }
    //...
}

Readme

Keywords

none

Package Sidebar

Install

npm i check-token-from-serverless-env

Weekly Downloads

1

Version

1.2.3

License

ISC

Unpacked Size

3.9 kB

Total Files

3

Last publish

Collaborators

  • reytuty