白嫖のCloudBase云函数第二章

2021-08-16 18:16:12 浏览数 (1)

白嫖のCloudbase云函数第二章

续接上章,本章搭建登陆,以及修改路由的一些问题,源码放在最下面了

修改文件

代码语言:txt复制
//app.js文件中有两个引入的路由文件
const index = require('./routes/index')
const users = require('./routes/users')
//目前只用到一个,所以删除 users 路由,以及删除routes文件夹下的users文件
//删除加载users路由
app.use(users.routes(), users.allowedMethods())
//删除public下的文件

修改routes/index.js

完整index.js文件

代码语言:txt复制
const router = require("koa-router")();

//路由前缀
router.get("/", async (ctx, next) => {
  await ctx.render("login");
});

router.get("/index", async (ctx, next) => {
await ctx.render("index");
});


router.get("/login",async (ctx,next) =>{
await ctx.render("login");
})

//退出
router.get("/logout",async (ctx,next) =>{
await ctx.render("login");
})

module.exports = router;

修改app.js

代码语言:txt复制
完整app.js
代码语言:txt复制
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')


//########## 基础个人信息管理 ##############
let username = "admin";   //账号
let password = "123456";  //密码
let open_url = ["login","logout","submit","style.css","login.js","vue.js","backage.jpg"]; //无权限可访问
//#########################################

//##### 自动更换访问了路径 start #####
const os = require('os');
let pathName = "/mini";
let systemName = os.type().toLocaleLowerCase();
console.log("系统类型:",systemName);
if(systemName.indexOf("windows") > -1){
    pathName = "";
}
//######## end #########



function localFilter(ctx){
  let url = ctx.originalUrl; //获取地址
  if(checkUrl(url)){
    setCookie(ctx,"");
    if(url.indexOf("submit") > -1){ //提交登陆校验
      login(ctx);
    }
  }else{
     //检测cookie
    let jession = ctx.cookies.get("jession");
    if(jession == null || jession == ""){
        ctx.response.redirect(pathName   "/login");//没检测到cookie
        return;
    }
    let encryption = compileStr(username  "," password);
    console.log("跳转-加密数据:", encryption);
      if(jession != encryption){
          setCookie(ctx,"");
          ctx.response.redirect( pathName  "/login");//没检测到cookie
          return;
      }
  }
}


//路径校验
function checkUrl(url){
  let open = false;
  open_url.forEach(parent =>{
      if(url.indexOf(parent) > -1){
        open = true;
      }
  });
  return open;
}

//登陆操作
function login (ctx){
  const parent  = ctx.request.body
  console.log("打印信息", ctx.request.body);
  if(parent.username == "" && parent.password == ""){
      ctx.response.redirect( pathName  "/login?msg=0");//0请填写账号密码
      return;
  }else if(parent.username == username && parent.password == password){
      let encryption =  compileStr(username   "," password);
      console.log("登陆-加密数据:", encryption);
      setCookie(ctx,encryption);//设置登陆
      ctx.response.redirect(pathName  "/index");
      return;
  }else{
      ctx.response.redirect(pathName "/login?msg=1");//1账号密码错误
      return;
  }
}

function setCookie(ctx,val){
  ctx.cookies.set('jession',val,{httpOnly:false})
}

//对字符串进行加密   
function compileStr(code){
  var c=String.fromCharCode(code.charCodeAt(0) code.length);  
  for(var i=1;i<code.length;i  ){        
      c =String.fromCharCode(code.charCodeAt(i) code.charCodeAt(i-1));  
  }     
  return escape(c);
}


const index = require('./routes/index')
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname   '/public'))

app.use(views(__dirname   '/views', {
  extension: 'html'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
//############# 拦截器 #############
app.use(async (ctx, next) => {
  localFilter(ctx);
  await next();
});
// routes
app.use(index.routes(), index.allowedMethods())


// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app

app.js写了几个小功能

  • 设置了登陆的账号密码
  • 增加了cookie拦截,根据前端提交的账号密码,对提交的密码进行加密,然后将自己设置的密码进行加密,然后比对,相同则通过!否则在login增加msg状态,登陆页面的js获取到msg数据则会展示不同的提示信息!通过则生成cookie信息,否则就跳回login
  • 增加拦截功能,检测跳转的页面是否带有cookie
  • 增加访问资源的校验,头部设置了无权限可访问资源
  • 增加访问地址变换,保证本地以及云函数地址访问也没问题

开始注入灵魂,写前端页面了

开始新建文件

public文件夹下新建了static文件夹,其余的css js plug文件夹都在下面

在views中新建了login.html

login.html

代码语言:txt复制
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>CloudBase登陆</title>
        <meta  name="viewport" content="width=device-width, initial-scale=1.0"/>
        <script  src="static/plug/vue/vue.js" type="text/javascript" charset="utf-8"></script>
        <link rel="stylesheet" href="static/css/style.css"/>
    </head>
    <body>
        <div id="app">
            <div class="box">
                <form action="koa/submit" class="login-form" method="post">
                    <h2 style="margin-bottom: 20px;">cloudBase管理系统</h2>
                    <input type="text"  name="username"  placeholder="用户名">
                    <input type="password"  name="password"  placeholder="密码">
                    <div style="color:red">{{error}}</div>
                    <button type="submit">登陆</button>
                </form>
            </div>
        </div>
        <script src="static/js/login.js"></script>
    </body>
</html>

login.js

代码语言:txt复制
var vm = new Vue({
    el:"#app",
    data: {
        error:"",
        username:"",
        password:""
    },
    methods: {
        errorMsg(){
            var url=window.location.search;
            if(url.indexOf("") > -1){
              const msg = url.split("msg=")[1];
                if(msg != null){
                    this.error = msg=="0"?"账号密码不能为空":msg == "1"?"账号或者密码错误":"";
                }

            }
        }
    },
    beforeMount(){
        this.errorMsg();
    }
})

style.css

代码语言:txt复制
* {
    margin: 0;
    padding: 0;
}

.box {
    display: flex;
    width: 100vw;
    height: 100vh;
    align-items: center;
    justify-content: center;
    background: url(img/backage.jpg) no-repeat fixed;
    background-size: cover;
}

.login-form {
    display: flex;
    position: relative;
    width: 240px;
    height: 220px;
    flex-direction: column;
    padding: 40px;
    text-align: center;
    z-index: 1;
    background: inherit;
    border-radius: 18px;
    overflow: hidden;
}

.login-form::before {
    content: '';
    position: absolute;
    top: -10px;
    left: -10px;
    width: calc(100%   20px);
    /*   两边各有一个空格  否则 无效*/
    height: calc(100%   20px);
    background: inherit;
    box-shadow: 0 0 0 200px rgba(255, 255, 255, .2) inset;
    z-index: -1;
    filter: blur(6px);
    overflow: hidden;
}

.login-form h2 {
    font-size: 18px;
    font-weight: 400;
    color: #3d5245;
}

.login-form input,
.login-form button {
    margin: 6px 0;
    height: 36px;
    background-color: rgba(255, 255, 255, .3);
    border: none;
    border-radius: 4px;
    padding: 0 14px;
    color: #3d5245;
}

.login-form input::placeholder {
    color: #3d5245;
}

.login-form button {
    position: relative;
    /* margin-top: 24px; */
    background-color: rgba(57, 88, 69, .4);
    color: #ffffff;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.4s;
}

.login-form button:hover {
    background-color: rgba(12, 88, 38, 0.67);
}

.login-form button::before,
.login-form button::after {
    content: '';
    display: block;
    width: 80px;
    height: 100%;
    background-color: rgba(179, 255, 210, .5);
    opacity: 0.5s;
    position: absolute;
    left: 0;
    top: 0;
    transform: skewX(-15deg);
    filter: blur(30px);
    overflow: hidden;
    transform: translateX(-100px);
}

.login-form button::after {
    width: 40px;
    background-color: rgba(179, 255, 210, .3);
    left: 60px;
    filter: blur(5px);
    opacity: 0;
}

.login-form button:hover::before {
    transition: all 1s;
    transform: translateX(320px);
    opacity: 0.7;
}

.login-form button:hover::after {
    transition: all 1s;
    transform: translateX(320px);
    opacity: 1;
}

访问public下的文件夹

可以访问public下的资源,因为app.js中写过这样的代码

代码语言:txt复制
//访问静态资源,连接到的地址为/public下面
app.use(require('koa-static')(__dirname   '/public'))

运行npm run dev, 账号:admin 密码:123456

源码

代码语言:txt复制
链接:https://pan.baidu.com/s/1bVlvTDLTJ2Ew0OQpkk9Lsg 
提取码:6f6p

0 人点赞