一起来完成以下步骤:
- 先来看我们要达到的效果————不登录将不能访问/home首页.
- 登录和退出功能已经提前写好
- 添加session,登录成功后把员工信息放到session中.退出时,要清空session
- 添加authMiddlewares,在session有效的情况下才能访问/home页面,否则调转到登录页面
- 运行命令: deno run --allow-net --allow-read main.ts
#controllers/controller.ts
import { Context, REDIRECT_BACK } from "https://deno.land/x/oak/mod.ts";
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: ""
});
}
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) {
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";
const hadEmployee = await ctx.state.session.get("EMPLOYEE_SESSION");
if (hadEmployee !== undefined) {
sessionName = hadEmployee.username;
}
ctx.render(`${cwd()}/views/home.ejs`, {
usersession: sessionName
});
}
static async logout(ctx: any) {
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";
const authMiddleware = async (ctx: any, next: any) => {
const hadEmployee = await ctx.state.session.get("EMPLOYEE_SESSION");
if(hadEmployee !== undefined){
await next();
return;
}
ctx.response.redirect(REDIRECT_BACK, "/");
}
export default authMiddleware;
#models/employee.ts
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);
router.get("/home",authMiddleware,Controller.home);
router.get("/logout",Controller.logout);
export default router;
#main.ts
import { Application, send } from "https://deno.land/x/oak/mod.ts"
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";
const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();
const app = new Application();
const session = new Session({ framework: "oak" });
await session.init();
app.use(session.use()(session));
app.use(viewEngine(oakAdapter, ejsEngine));
app.use(router.routes());
app.use(router.allowedMethods());
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>
<div class="col-4">
<button type="submit" class="btn btn-primary btn-block">Sign In</button>
</div>
</div>
</form>