koa 只允许手机浏览器访问

const koa = require('koa');
const session = require('koa-session');
const app = new koa();
const mobileAgents = ['iphone', 'ipod', 'android', 'samsung', 'htc', 'mobile', 'nokia', 'sony', 'blackberry', 'opera mini', 'windows phone'];

app.keys = ['123456']

const CONFIG = {
    key: 'sessionId',
    maxAge: null,
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: false
};

app.use(session(CONFIG, app));

app.use(async (ctx, next) => {
    do{
        if(ctx.session.isMobile!==undefined  && !ctx.session.isMobile) {
            break; 
        }
        const userAgent = ctx.request.header['user-agent'].toLowerCase();
        console.log(userAgent, ctx.request.header);
        const isMobile = mobileAgents.some(agent => userAgent.indexOf(agent) !== -1);
      
        ctx.session.isMobile = isMobile;
        if(!isMobile) {
          break;
        }
      
        await next();
        return;
    }while(0);

    ctx.status = 403;
});

app.use(async (ctx, next) => {
  ctx.body = 'Hello World';
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

 

posted @ 2024-04-11 17:21  Please Call me 小强  阅读(9)  评论(0编辑  收藏  举报