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:
When it comes to a web application, before it goes into production, the developer must make sure that it works properly in all browsers. The end user should be able to experience a fully functional site that is able to handle all critical functionalities irrespective of the browser or device used by the end user. The behavior of an application is different in different operating systems, browsers and even devices based on their resolution. Most developers usually a prefers to work on a single browser, even if multiple browsers are installed in the workstation.
Errors occur where you least expect them, JS developers face this nemesis on a daily basis.
Ever-since the introduction of World Wide Web in 1990, the domain of web development has evolved dynamically from web pages to web applications. End users no longer browse web pages for reading static content. Websites now have dynamic features to increase their engagement rate. Interactive websites are being developed using which users can perform their day to day activities like shopping for groceries, banking, paying taxes, etc. However, these applications are developed by human beings, and mistakes are supposed to happen. Often a simple mistake can impact a critical functionality in your website that will lead the user to move away to a different website, reducing your profit and SERP ranking. In this article, we shall discuss the common mistakes made by developers while developing a web application.
Website is always the front face to your business. Every user who gets to know about you goes through your website as the first line of enquiry. So, you must make sure that your website looks the best.
The staging environment is something that is suggested as best practice but considered as a burden. Many of us feel pounded with the thought of extra investment and effort involved to upkeep it. It happens very often that a company in spite of having a Staging environment ends up failing in reaping proper results from it. Which makes us ponder on what went wrong in our QA environment? Why is a change which performed so well in QA, happened to walk south after migrating to Production?
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!!