Best JavaScript code snippet using best
auth.js
Source: auth.js
1const jwt = require('jsonwebtoken');23const secretKey = "SuperSecret"; //secret key, used to sign and verify JWTs. (Bad practice)45function generateAuthToken(userEmail) { 6 const payload = { sub: userEmail };7 return jwt.sign(payload, secretKey, { expiresIn: '24h' });8}9exports.generateAuthToken = generateAuthToken;1011function requireAuthentication(req, res, next) {12 console.log(" -- verifying authentication");13 const authHeader = req.get('Authorization') || '';14 const authHeaderParts = authHeader.split(' ');15 console.log(" -- authHeaderParts:", authHeaderParts);16 const token = authHeaderParts[0] === 'Bearer' ? authHeaderParts[1] : null;1718 try {19 const payload = jwt.verify(token, secretKey);20 req.email = payload.sub;21 next();22 } catch (err) {23 res.status(401).send({24 error: "Invalid authentication token."25 });26 }27}28exports.requireAuthentication = requireAuthentication;293031function optionalAuthentication(req, res, next) {32 console.log(" -- verifying authentication");33 const authHeader = req.get('Authorization') || '';34 const authHeaderParts = authHeader.split(' ');35 console.log(" -- authHeaderParts:", authHeaderParts);36 const token = authHeaderParts[0] === 'Bearer' ? authHeaderParts[1] : null;37 try {38 const payload = jwt.verify(token, secretKey);39 req.email = payload.sub;40 next();41 }42 catch (err) {43 console.log("User is not logged in. Cannot create an admin for sure");44 next();45 }46}47
...
auth.ts
Source: auth.ts
1import * as jwt from 'jsonwebtoken';2import * as jwkToPem from 'jwk-to-pem';3export type JsonWebKey = {4 keys: {5 alg: string;6 e: string;7 kid: string;8 kty: string;9 n: string;10 use: string;11 }[];12};13export const verifyUser = (req, res, next) => {14 try {15 const authorization = req?.headers.authorization;16 const authHeaderParts = authorization?.split(' ');17 const token =18 authHeaderParts &&19 authHeaderParts.length === 2 &&20 authHeaderParts[0] === 'Bearer'21 ? authHeaderParts[1]22 : null;23 const jwk = JSON.parse(process.env.JWKS);24 verifyToken(token, jwk);25 next();26 } catch (err) {27 throw new VerificationFailedError(err.message);28 }29};30// NOTE: doc - https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html31export const verifyToken = (idToken: string, jwks: JsonWebKey) => {32 const decodedJwtToken = jwt.decode(idToken, { complete: true });33 const jwk = jwks.keys.find((key) => key.kid === decodedJwtToken.header.kid);34 const pem = jwkToPem(jwk);35 const decodedToken = jwt.verify(idToken, pem, { algorithms: ['RS256'] });36 return decodedToken;37};...
Check out the latest blogs from LambdaTest on this topic:
LambdaTest has recently received two notable awards from the leading business software directory FinancesOnline after their experts were impressed with our test platform’s capabilities in accelerating one’s development process.
The layout of a web page is one of the most important features of a web page. It can affect the traffic inflow by a significant margin. At times, a designer may come up with numerous layout ideas and sometimes he/she may struggle the entire day to come up with one. Moreover, design becomes even more important when it comes to ensuring cross browser compatibility.
Chrome is hands down the most used browsers by developers and users alike. It is the primary reason why there is such a solid chrome community and why there is a huge list of Chrome Extensions targeted at developers.
In a startup, the major strength of the people is that they are multitaskers. Be it anything, the founders and the core team wears multiple hats and takes complete responsibilities to get the ball rolling. From designing to deploying, from development to testing, everything takes place under the hawk eyes of founders and the core members.
We are in the era of the ‘Heads down’ generation. Ever wondered how much time you spend on your smartphone? Well, let us give you an estimate. With over 2.5 billion smartphone users, an average human spends approximately 2 Hours 51 minutes on their phone every day as per ComScore’s 2017 report. The number increases by an hour if we include the tab users as well!
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!