1.0.0 • Published 2 years ago

check-token-from-serverless v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

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"] })
        };
    }
    //...
}
1.0.0

2 years ago