//登录接口exportdefaultclassAuthController{staticasynclogin(req,res){try{const{name,password}=req.body;if(!name||typeofname!=="string"){res.status(400).json(resultFail("Badnameformat,expectedstring."));返回;}if(!password||typeofpassword!=="string"){res.status(400).json(resultFail("Badpasswordformat,expectedstring."));返回;}让userFromDB=awaitAuthDAO.getUser(name);if(!userFromDB){res.status(401).json(resultFail("确保你的名字是正确的。"));返回;}constuser=newAuthUser(userFromDB);if(!(awaituser.comparePassword(password))){res.status(401).json(resultFail("请确保您的密码正确。"));返回;}user.encoded().then((token)=>{letoption={token:token,使用rName:userFromDB.name,角色:userFromDB.privilege}userManager.setCurrentCacheToken(option);res.send(resultSuccess({auth_token:token,...user.toJson()}))});}catch(e){res.status(400).json(resultFail(e));}}}//权限分配对应接口import{token}from'morgan';import{ADMIN,NORMAL,ANONYMOUS}from'./common/constants';import{resultFail}from'./common/utils';importpathfrom"path";//不同权限的APIconstapi4anonymous=["/api/devices/","/api/devices/get-device","/sys/health-check","/sys/access-log","/auth/login"]constapi4normal=["/api/devices/","/api/devices/get-device","/sys/health-check","/sys/access-log","/auth/login"]constapi4admin=["all"]constrolePermission=newMap([[ADMIN,api4admin],[NORMAL,api4normal],[匿名,api4normal],]);classUserManager{#cacheToken;#apiPermissionMap;constructor(){this.#cacheToken={token:'',role:ANONYMOUS,userName:''};this.#apiPermissionMap=rolePermission;}setCurrentCacheToken(option){//token为空表示角色是匿名的if(option.token!==''){if(typeof(option.token)=='string'){this.#cacheToken.token=option.令牌;}if(typeof(option.role)=='number'){this.#cacheToken.role=option.role;}if(typeof(option.userName)=='string'){this.#cacheToken.userName=option.userName;}}}getCurrentCacheToken(){返回这个。#cacheToken;}verifyApiPermission(reqUrl){letrole=this.#cacheToken['role'];如果(this.#cacheToken.token===''){role=ANONYMOUS;}if(this.#apiPermissionMap.has(role)){//管理员可以做任何事情if(role===ADMIN){returntrue;}if(this.#apiPermissionMap.get(role).indexOf(reqUrl)!==-1){返回真;}}返回假;}};functionreqPermissionHandler(req,res,next){constreqUrl=path.join(req.baseUrl,req.url);lettoken=req.get("授权");如果(!token){token='';}else{token=token.slice("Bearer".length);}if(token!=userManager.getCurrentCacheToken().token&&token!==''){res.status(401).json(resultFail(('tokenerror')));返回;}if(userManager.verifyApiPermission(reqUrl)){next();}else{res.status(403).json(resultFail(('NoPermission')));返回;}}让用户Manager=newUserManager();functionuserName(){returnuserManager.getCurrentCacheToken().userName;}export{reqPermissionHandler,userManager,userName};
