Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "koa-jwt in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'koa-jwt' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

'use strict';

var config = require('../../server/config/config'),
    mongoSeed = require('../../server/config/mongo-seed'),
    app = require('../../app'),
    jwt = require('koa-jwt'),
    baseUrl = 'http://localhost:' + config.app.port + '/api',
    supertest = require('co-supertest'),
    request = supertest(baseUrl);

// create a valid jwt token to be sent with every request
var user = mongoSeed.users[1];
var token = jwt.sign({id: user._id, name: user.name, email: user.email}, config.app.secret);
token = 'Bearer ' + token;

// make request and token objects available
exports.request = request;
exports.token = token;

// initiate KOAN server before each test is run
// also drop and re-seed the test database before each run
console.log('Mocha starting to run server tests on port ' + config.app.port);
beforeEach(function *() {
  yield app.init(true);
});

// close the server after each test is done
afterEach(function (done) {
  app.server.close(done);
render(app, {
  root: path.join(__dirname, './static'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true,
})

// 跨域
app.use(cors())

// 请求解析
app.use(koaBody())

// jwt
app.use(koaJwt({
  secret: JWT.secret,
  passthrough: true
}).unless({
  path: [/^\/apidocs/]
}))

app.use(valid()) // 参数验证
app.use(pipe()) // 通讯

// 路由
app
  .use(router.base)
  // .use(router.v1)
  .use(router.admin)

// 404
const engine = new Engine({
  engineConfig: { apiKey: 'service:tychota-Bam-Api:1Z3thyxiVF84L4nF97NUmw' },
  graphqlPort: 3000, // GraphQL port
  endpoint: '/graphql', // GraphQL endpoint suffix - '/graphql' by default
  dumpTraffic: true,
});
engine.start();

// configure jwt middleware to connect to auth0, check the token and
const jwtConfig = {
  secret: jwksRsa.koaJwtSecret(config.get('Security.jwks')),
  ...config.get('Security.jwt'),
  passthrough: true,
};
app.use(koaJwt(jwtConfig));

app.use(engine.koaMiddleware());

// import the schema and mount it under /graphql
import schema from '../presentation/schema';
import getViewerAndRoles from '../business/utils/auth';

import { formatErrorGenerator } from 'graphql-apollo-errors';

// get the dataloader for each request
import * as business from '../business';
router.post(
  '/graphql',
  graphqlKoa(async ctx => {
    // create error formatter
    const formatErrorConfig = {
if (config.ENV === 'production') {
  mongoose.connect(`mongodb://${config.MONGODB.USER}:${config.MONGODB.PASSWORD}@${config.MONGODB.HOST}:${config.MONGODB.PORT}/${config.MONGODB.NAME}`)
} else {
  mongoose.connect(`mongodb://${config.MONGODB.HOST}:${config.MONGODB.PORT}/${config.MONGODB.NAME}`)
}

app.use(ua())
app.use(cookies())
app.use(normal())
app.use(xsrf())

app.use(handel.routes())
    .use(handel.allowedMethods())

// Below needs JWT verfiy
app.use(jwt({
  secret: config.APP.JWT_KEY,
  algorithm: 'RS256'
}).unless({
  path: [/^\/static|css|js|img|fonts|favicon|manifest/]
}))

// API (Protected)
app.use(api.routes())
    .use(api.allowedMethods())
app.use(nghtml5())
app.listen(config.PORT)
module.exports = function () {
  const routesDir = __dirname // 如果不传参数,扫描目录默认为'routes'
  const router = require('koa-router')({prefix: `/api/${System.API_version}`})
  router.use(koaJWT({
    secret: System.JWT_secret
  }).unless({
    path: [/^\/api\/v1\/(user|admin|wx|upload|protocol|excel|everyday)\/(signin|auth|signature|image|new|base64|wx|order|type)/,
      '/api/v1/area',
      '/api/v1/banner',
      '/api/v1/district',
      // '/api/v1/specialty',
      // /^\/api\/v1\/specialty\/\d+/,
      '/api/v1/cuisine',
      '/api/v1/scene',
      '/api/v1/other'
      // '/api/v1/user',
    ]}))
  addRoutes(router, routesDir)
  return router.routes()
}
// routes
const router = new koaRouter();
loadRoutes(router);

if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'development_docker') {
  const corsOptions = {
    credentials: true,
    origin: '*',
  };
  app.use(cors(corsOptions));
}

app
  .use(bodyParser())
  .use(
    jwt({
      secret: process.env.JWT_KEY,
    }).unless({
      path: ['/', '/login'],
    }),
  )
  .use(logger())
  .use(router.routes())
  .use(
    router.allowedMethods({
      throw: true,
      notImplemented: () => new Boom.notImplemented(),
      methodNotAllowed: () => new Boom.methodNotAllowed(),
    }),
  )
  .use(async context => {
    context.body = 'INSIDE API';
import bodyParser from 'koa-bodyparser';
import passport from './passport';

const app = new Koa();

if (process.env.NODE_ENV === 'development') {
  app.use(logger());
}
app.use(convert(cors({ credentials: true })));
app.use(bodyParser());
app.use(passport.initialize());

// Parse Authorization Header for JWT tokens, and set ctx.state.user if token is
// valid. Passthrough to middleware to make decisions on whether or not their
// routes require users. See src/middleware/validate-user.js
app.use(jwt({ secret: process.env.APP_SECRET, passthrough: true }));

// Custom API modules that define their own routes.
const modules = require('./modules');
modules(app);

export default app;
log('Couldn\'t load user', err)
  }

  if (!user) {
    this.status = 400
    this.body = {
      error: 'User doesn\'t exist'
    }
    return
  }

  // Compare password with the one within the DB
  const isMatch = user.tryPassword(body.password)

  if (isMatch) {
    const token = jwt.sign(body, process.env.SESSION_SECRET, {
      expiresIn: 300
    })

    this.body = {
      token
    }

    return
  }

  this.status = 400

  this.body = {
    error: 'Wrong password'
  }
if (userInfo != null) { // 如果查无此用户会返回 null
    if (userInfo.password != data.password) {
      if (!bcrypt.compareSync(data.password, userInfo.password)) {
        this.body = { // 返回给前端的数据
          success: false,
          info: '密码错误!'
        }
      }
    } else { // 密码正确
      const userToken = {
        id: userInfo.id,
        name: userInfo.user_name,
        originExp: Date.now() + 60 * 60 * 1000, // 设置过期时间(毫秒)为 1 小时
      }
      const secret = 'vue-koa-demo'; // 指定密钥,这是之后用来判断 token 合法性的标志
      const token = jwt.sign(userToken, secret); // 签发 token
      this.body = {
        success: true,
        token: token
      }
    }
  } else {
    this.body = {
      success: false,
      info: '用户不存在!'
    }
  }
}
if (!user) {
    ctx.status = 400

    ctx.body = {
      error: 'User doesn\'t exist'
    }

    return
  }

  // Compare password with the one within the DB
  const isMatch = user.tryPassword(body.password)

  if (isMatch) {
    const token = jwt.sign(body, process.env.SESSION_SECRET, {
      expiresIn: 300
    })

    ctx.body = { token }
    return
  }

  ctx.status = 400

  ctx.body = {
    error: 'Wrong password'
  }

  await next()
})

Is your System Free of Underlying Vulnerabilities?
Find Out Now