Ticker

6/recent/ticker-posts

Header Ads Widget

Responsive Advertisement

JWT Authentication Code with use cases

JWT Authentication Code with use cases


    What is  JWT?

    JWT Stands for JSON Web Token. It is used in HTTP request headers gets parsed with JSON payload for user authentication using a token to store the user credentials in the cookie policies for a certain time of 30 days or any frequency like a day to year.

    JWT Authentication Code with use cases

    
    const express = require('express')
    const bcrypt = require('bcrypt')
    const path = require('path')
    const {open} = require('sqlite')
    const sqlite3 = require('sqlite3')
    const jwt = require('jsonwebtoken')
    
    const app = express()
    app.use(express.json())
    
    const dbPath = path.join(__dirname, 'covid19IndiaPortal.db')
    let db = null
    
    const initailSetupDB = async () => {
      try {
        db = await open({
          filename: dbPath,
          driver: sqlite3.Database,
        })
        app.listen(3000, () => {
          console.log('Server Started at http://localhost:3000')
        })
      } catch (e) {
        console.log(`DB Error: ${e.message}`)
        process.exit(1)
      }
    }
    
    initailSetupDB()
    const authenticateToken = (request, response, next) => {
      let jwtToken
      const authHeader = request.headers['authorization']
      if (authHeader !== undefined) {
        jwtToken = authHeader.split(' ')[1]
      }
      if (jwtToken === undefined) {
        response.status(401)
        response.send('Invalid JWT Token')
      } else {
        jwt.verify(jwtToken, 'MY_SECRET_TOKEN', async (error, payload) => {
          if (error) {
            response.status(401)
            response.send('Invalid JWT Token')
          } else {
            next()
          }
        })
      }
    }
    
    // API 1
    app.post('/users/', async (request, response) => {
      const {username, name, password, gender, location} = request.body
      const hashedPassword = await bcrypt.hash(request.body.password, 10)
      const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`
      const dbUser = await db.get(selectUserQuery)
      if (dbUser === undefined) {
        const createUserQuery = `
          INSERT INTO 
            user (username, name, password, gender, location) 
          VALUES 
            (
              '${username}', 
              '${name}',
              '${hashedPassword}', 
              '${gender}',
              '${location}'
            )`
        const dbResponse = await db.run(createUserQuery)
        const newUserId = dbResponse.lastID
        response.send(`Created new user with ${newUserId}`)
      } else {
        response.status = 400
        response.send('User already exists')
      }
    })
    app.post('/login', async (request, response) => {
      const {username, password} = request.body
      const selectUserQuery = `SELECT * FROM user WHERE username = '${username}'`
      const dbUser = await db.get(selectUserQuery)
      if (dbUser === undefined) {
        response.status(400)
        response.send('Invalid user')
      } else {
        const isPasswordMatched = await bcrypt.compare(password, dbUser.password)
        if (isPasswordMatched === true) {
          const payload = {
            username: username,
          }
          const jwtToken = jwt.sign(payload, 'MY_SECRET_TOKEN')
          response.send({jwtToken})
        } else {
          response.status(400)
          response.send('Invalid password')
        }
      }
    })
    // API 2
    app.get('/states', authenticateToken, async (request, response) => {
      const ans = state => {
        return {
          stateId: state.state_id,
          stateName: state.state_name,
          population: state.population,
        }
      }
      const getStateDetails = `SELECT * FROM state`
      const stateList = await db.all(getStateDetails)
      response.send(stateList.map(state => ans(state)))
    })
    // API 3
    app.get('/states/:stateId/', authenticateToken, async (request, response) => {
      const {stateId} = request.params
      const ans = state => {
        return {
          stateId: state.state_id,
          stateName: state.state_name,
          population: state.population,
        }
      }
    
      const stateDetailsQuery = `SELECT * FROM state where state_id = ${stateId}`
      const stateDetails = await db.get(stateDetailsQuery)
      response.send(ans(stateDetails))
    })
    // API 4
    app.post('/districts/', authenticateToken, async (request, response) => {
      const {districtName, stateId, cases, cured, active, deaths} = request.body
      const addDistrictQuery = `INSERT INTO district(district_name, state_id, cases, cured, active, deaths)
        values(  '${districtName}', ${stateId}, ${cases}, ${cured}, ${active}, ${deaths})`
      await db.run(addDistrictQuery)
      response.send('District Successfully Added')
    })
    // API 5
    app.get(
      '/districts/:districtId/',
      authenticateToken,
      async (request, response) => {
        const {districtId} = request.params
        const districtDetilsQuery = `
      SELECT
        *
      FROM 
        district
      WHERE
        district_id=${districtId}
      `
        const ans = detail => {
          return {
            districtId: detail.district_id,
            districtName: detail.district_name,
            stateId: detail.state_id,
            cases: detail.cases,
            cured: detail.cured,
            active: detail.active,
            deaths: detail.deaths,
          }
        }
        const districtDetails = await db.get(districtDetilsQuery)
        response.send(ans(districtDetails))
      },
    )
    // API 6
    app.delete(
      '/districts/:districtId/',
      authenticateToken,
      async (request, response) => {
        const {districtId} = request.params
        const deleteDistrictQuery = `DELETE FROM district WHERE district_id=${districtId}`
        await db.run(deleteDistrictQuery)
        response.send('District Removed')
      },
    )
    // API 7
    app.put(
      '/districts/:districtId/',
      authenticateToken,
      async (request, response) => {
        const {districtId} = request.params
        const {districtName, stateId, cases, cured, active, deaths} = request.body
        const updateNewDistrict = `
          UPDATE
             district 
          SET 
            district_name= '${districtName}',
            state_id = ${stateId},
            cases = ${cases},
            cured  = ${cured},
            active = ${active},
            deaths = ${deaths}
          WHERE
            district_id = ${districtId}
          `
        await db.run(updateNewDistrict)
        response.send('District Details Updated')
      },
    )
    // API 8
    app.get(
      '/states/:stateId/stats/',
      authenticateToken,
      async (request, response) => {
        const {stateId} = request.params
        const stateDetailsQuey = `
      SELECT 
        sum(cases) as total_cases,
       sum(cured) as total_cured,
       sum(active) as total_active,
       sum(deaths) as total_deaths
       FROM 
      state inner join district  on 
         state.state_id = district.state_id
       where state.state_id = ${stateId}`
        const ans = detail => {
          return {
            totalCases: detail.total_cases,
            totalCured: detail.total_cured,
            totalActive: detail.total_active,
            totalDeaths: detail.total_deaths,
          }
        }
        const details = await db.get(stateDetailsQuey)
        response.send(ans(details))
      },
    )
    module.exports = app
    
      

    Post a Comment

    0 Comments