其他分享
首页 > 其他分享> > Deno 登录退出和session应用

Deno 登录退出和session应用

作者:互联网

视频演示:https://www.bilibili.com/video/BV1BT4y1E7Nh/?p=13

一起来完成以下步骤:

  1. 先来看我们要达到的效果————不登录将不能访问/home首页.
  2. 登录和退出功能已经提前写好
  3. 添加session,登录成功后把员工信息放到session中.退出时,要清空session
  4. 添加authMiddlewares,在session有效的情况下才能访问/home页面,否则调转到登录页面
  5. 运行命令: deno run --allow-net --allow-read main.ts

#controllers/controller.ts

//引入后台REDIRECT
import { Context, REDIRECT_BACK } from "https://deno.land/x/oak/mod.ts";
//解析Form
import { multiParser } from 'https://raw.githubusercontent.com/deligenius/multiparser/master/mod.ts'
//引入员工列表
import employees from "../models/employees.ts";
//获取工程目录
const { cwd } = Deno;

class Controller {

    //默认登录页面
    static async login(ctx: any) {
        ctx.render(`${cwd()}/views/login.ejs`, {
            msg: ""
        });
    }

    //提交登录Action
    static async logon(ctx: any) {
        //获取员工登录信息
        const strLoginEmployee = JSON.stringify(await multiParser(ctx.request.serverRequest));
        const jsonLoginEmployee = JSON.parse(strLoginEmployee);
        //检查登录员工是否存在
        const hadEmployee = employees.find(employee => {
            return employee.username === jsonLoginEmployee.username && employee.password === jsonLoginEmployee.password;
        });

        //如果存在
        if (hadEmployee) {
            //把员工set到session里面
            await ctx.state.session.set("EMPLOYEE_SESSION", hadEmployee);
            ctx.response.redirect(REDIRECT_BACK, "/home");
        } else {
            //如果不存在,将在登录页面显示错误信息
            ctx.render(`${cwd()}/views/login.ejs`, {
                msg: "用户名或密码错误"
            });
        }

    }

    //登录成功后跳转到首页
    static async home(ctx: any) {
        let sessionName: string = " is null";
        //获取session
        const hadEmployee = await ctx.state.session.get("EMPLOYEE_SESSION");
        //session 是否存在员工信息
        if (hadEmployee !== undefined) {
            sessionName = hadEmployee.username;
        }
        //再首页显示员工名称
        ctx.render(`${cwd()}/views/home.ejs`, {
            usersession: sessionName
        });
    }

    //退出登录
    static async logout(ctx: any) {
        //这里清空session
        await ctx.state.session.set("EMPLOYEE_SESSION", undefined);
        ctx.response.redirect(REDIRECT_BACK, "/");
    }

}

export default Controller;

#middlewares/authMiddleware.ts


import { Context,REDIRECT_BACK } from "https://deno.land/x/oak/mod.ts";

//定义 authMiddleware 检查session有效性
const authMiddleware = async (ctx: any, next: any) => {
   
    //检查session 是否存在
    const hadEmployee = await ctx.state.session.get("EMPLOYEE_SESSION");
    if(hadEmployee  !== undefined){
        await next();
        return;
    }
    //否则调到login页面
    ctx.response.redirect(REDIRECT_BACK, "/");
}

export default authMiddleware;

#models/employee.ts

//定义interface
export interface Employee{
    id: string,
    username: string,
    password: string
}

//初始化员工列表
const employees: Array<Employee> =[
    { 
        id: "1",
        username: "admin",
        password: "123456"
    },
    {
        id: "2",
        username: "alex",
        password: "654321"
    }
]
//导出
export default employees;

#routers/router.ts

import { Router } from "https://deno.land/x/oak/mod.ts";
import Controller from "../controllers/Controller.ts";
import authMiddleware from "../middlewares/authMiddleware.ts";


const router = new Router();

//默认登录页面
router.get("/",Controller.login);

//点击登录按钮
router.post("/logon",Controller.logon);

//登录成功跳转到首页,如果session不存在,将跳转到登录页面
router.get("/home",authMiddleware,Controller.home);

//退出登录
router.get("/logout",Controller.logout);

export default router;

#main.ts


//引入Application,send组件
import { Application, send } from "https://deno.land/x/oak/mod.ts"
//显示页面,必须引入这3个功能
import { viewEngine, engineFactory, adapterFactory } from "https://deno.land/x/view_engine/mod.ts";
import router from "./routers/router.ts";
import { Session } from "https://deno.land/x/session/mod.ts";

//获取页面模板引擎,这里是ejs
const ejsEngine = engineFactory.getEjsEngine();
//获取oak适配器 oakAdapter
const oakAdapter = adapterFactory.getOakAdapter();

//创建app
const app = new Application();

//我们工程使用的是oak
const session = new Session({ framework: "oak" });
//初始化session
await session.init();
//引用session
app.use(session.use()(session));

//创建viewEngine并应用到app
app.use(viewEngine(oakAdapter, ejsEngine));
app.use(router.routes());
app.use(router.allowedMethods());

//必须加上静态文件所有在目录,例如static
app.use(async ctx => {
    await send(ctx, ctx.request.url.pathname, {
        root: `${Deno.cwd()}/static`
    });
});

console.log("Server Port 8000");
//端口
await app.listen({ port: 8000 })


#views/login.ejs


<form action="/logon" enctype="multipart/form-data" method="POST">
    <div class="input-group mb-3">
        <input type="text" class="form-control" name="username" placeholder="username">
        <div class="input-group-append">
            <div class="input-group-text">
                <span class="fas fa-envelope"></span>
            </div>
        </div>
    </div>
    <div class="input-group mb-3">
        <input type="password" class="form-control" name="password" placeholder="Password">
        <div class="input-group-append">
            <div class="input-group-text">
                <span class="fas fa-lock"></span>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-8">
            <div class="icheck-primary">

            </div>
        </div>
        <!-- /.col -->
        <div class="col-4">
            <button type="submit" class="btn btn-primary btn-block">Sign In</button>
        </div>
        <!-- /.col -->
    </div>
</form>

标签:const,登录,ctx,ts,session,Deno,import
来源: https://www.cnblogs.com/JavaWeiBianCheng/p/13161224.html