shorten code

This commit is contained in:
monoid 2021-01-10 17:28:17 +09:00
parent eb7e2783ec
commit fa68bc1685
2 changed files with 41 additions and 33 deletions

View File

@ -8,7 +8,21 @@ import { request } from 'http';
import { get_setting } from './setting'; import { get_setting } from './setting';
import { IUser } from './model/mod'; import { IUser } from './model/mod';
const loginTokenName = 'access_token' type PayloadInfo = {
username:string,
permission:string[]
}
export type UserState = {
user?:PayloadInfo
};
const isUserState = (obj:object|string):obj is PayloadInfo =>{
if(typeof obj ==="string") return false;
return 'username' in obj && 'permission' in obj && (obj as {permission:unknown}).permission instanceof Array;
}
export const loginTokenName = 'access_token'
export const getAdminCookieValue = ()=>{ export const getAdminCookieValue = ()=>{
const setting = get_setting(); const setting = get_setting();
@ -26,27 +40,22 @@ export const createLoginMiddleware = (knex: Knex)=>{
const secretKey = setting.jwt_secretkey; const secretKey = setting.jwt_secretkey;
const body = ctx.request.body; const body = ctx.request.body;
if(!('username' in body)||!('password' in body)){ if(!('username' in body)||!('password' in body)){
sendError(400,"invalid form : username or password is not found in query."); return sendError(400,"invalid form : username or password is not found in query.");
return;
} }
const username = body['username']; const username = body['username'];
const password = body['password']; const password = body['password'];
if(typeof username !== "string" || typeof password !== "string"){ if(typeof username !== "string" || typeof password !== "string"){
sendError(400,"invalid form : username or password is not string") return sendError(400,"invalid form : username or password is not string")
return;
} }
if(setting.forbid_remote_admin_login && username === "admin"){ if(setting.forbid_remote_admin_login && username === "admin"){
sendError(403,"forbid remote admin login"); return sendError(403,"forbid remote admin login");
return;
} }
const user = await userController.findUser(username); const user = await userController.findUser(username);
if(user === undefined){ if(user === undefined){
sendError(401,"not authorized"); return sendError(401,"not authorized");
return;
} }
if(!user.password.check_password(password)){ if(!user.password.check_password(password)){
sendError(401,"not authorized"); return sendError(401,"not authorized");
return;
} }
const userPermission = await user.get_permissions(); const userPermission = await user.get_permissions();
const payload = sign({ const payload = sign({
@ -64,15 +73,21 @@ export const LogoutMiddleware = (ctx:Koa.Context,next:Koa.Next)=>{
ctx.body = {ok:true}; ctx.body = {ok:true};
return; return;
} }
export const UserMiddleWare = async (ctx:Koa.Context,next:Koa.Next)=>{ export const UserMiddleWare = async (ctx:Koa.ParameterizedContext<UserState>,next:Koa.Next)=>{
const secretKey = get_setting().jwt_secretkey; const secretKey = get_setting().jwt_secretkey;
const payload = ctx.cookies.get(loginTokenName); const payload = ctx.cookies.get(loginTokenName);
if(payload == undefined){ if(payload == undefined){
ctx.state['user'] = undefined; ctx.state['user'] = undefined;
return await next(); return await next();
} }
ctx.state['user'] = verify(payload,secretKey); const o = verify(payload,secretKey);
await next(); if(isUserState(o)){
ctx.state.user = o;
return await next();
}
else{
console.error("invalid token detected");
}
} }
export const getAdmin = async(knex : Knex)=>{ export const getAdmin = async(knex : Knex)=>{

View File

@ -12,8 +12,7 @@ const ContentIDHandler = (controller: ContentAccessor) => async (ctx: Context,ne
const num = Number.parseInt(ctx.params['num']); const num = Number.parseInt(ctx.params['num']);
let content = await controller.findById(num,true); let content = await controller.findById(num,true);
if (content == undefined){ if (content == undefined){
sendError(404,"content does not exist."); return sendError(404,"content does not exist.");
return;
} }
ctx.body = content; ctx.body = content;
ctx.type = 'json'; ctx.type = 'json';
@ -23,8 +22,7 @@ const ContentTagIDHandler = (controller: ContentAccessor) => async (ctx: Context
const num = Number.parseInt(ctx.params['num']); const num = Number.parseInt(ctx.params['num']);
let content = await controller.findById(num,true); let content = await controller.findById(num,true);
if (content == undefined){ if (content == undefined){
sendError(404,"content does not exist."); return sendError(404,"content does not exist.");
return;
} }
ctx.body = content.tags || []; ctx.body = content.tags || [];
ctx.type = 'json'; ctx.type = 'json';
@ -36,13 +34,12 @@ const ContentQueryHandler = (controller : ContentAccessor) => async (ctx: Contex
const content_type:string|undefined = ctx.query['content_type']; const content_type:string|undefined = ctx.query['content_type'];
const offset = ParseQueryNumber(ctx.query['offset']); const offset = ParseQueryNumber(ctx.query['offset']);
if(limit === NaN || cursor === NaN || offset === NaN){ if(limit === NaN || cursor === NaN || offset === NaN){
sendError(400,"parameter limit, cursor or offset is not a number"); return sendError(400,"parameter limit, cursor or offset is not a number");
} }
const allow_tag = ParseQueryArray(ctx.query['allow_tag[]']); const allow_tag = ParseQueryArray(ctx.query['allow_tag[]']);
let [ok,use_offset] = ParseQueryBoolean(ctx.query['use_offset']); let [ok,use_offset] = ParseQueryBoolean(ctx.query['use_offset']);
if(!ok){ if(!ok){
sendError(400,"use_offset must be true or false."); return sendError(400,"use_offset must be true or false.");
return;
} }
const option :QueryListOption = { const option :QueryListOption = {
limit: limit, limit: limit,
@ -61,10 +58,10 @@ const ContentQueryHandler = (controller : ContentAccessor) => async (ctx: Contex
const UpdateContentHandler = (controller : ContentAccessor) => async (ctx: Context, next: Next) => { const UpdateContentHandler = (controller : ContentAccessor) => async (ctx: Context, next: Next) => {
const num = Number.parseInt(ctx.params['num']); const num = Number.parseInt(ctx.params['num']);
if(ctx.request.type !== 'json'){ if(ctx.request.type !== 'json'){
sendError(400,"update fail. invalid content type: it is not json."); return sendError(400,"update fail. invalid content type: it is not json.");
} }
if(typeof ctx.request.body !== "object"){ if(typeof ctx.request.body !== "object"){
sendError(400,"update fail. invalid argument: not"); return sendError(400,"update fail. invalid argument: not");
} }
const content_desc: Partial<Content> & {id: number} = { const content_desc: Partial<Content> & {id: number} = {
id:num,...ctx.request.body id:num,...ctx.request.body
@ -76,8 +73,7 @@ const UpdateContentHandler = (controller : ContentAccessor) => async (ctx: Conte
const CreateContentHandler = (controller : ContentAccessor) => async (ctx: Context, next: Next) => { const CreateContentHandler = (controller : ContentAccessor) => async (ctx: Context, next: Next) => {
const content_desc = ctx.request.body; const content_desc = ctx.request.body;
if(!isContentContent(content_desc)){ if(!isContentContent(content_desc)){
sendError(400,"it is not a valid format"); return sendError(400,"it is not a valid format");
return;
} }
const id = await controller.add(content_desc); const id = await controller.add(content_desc);
ctx.body = JSON.stringify(id); ctx.body = JSON.stringify(id);
@ -87,13 +83,12 @@ const AddTagHandler = (controller: ContentAccessor)=>async (ctx: Context, next:
let tag_name = ctx.params['tag']; let tag_name = ctx.params['tag'];
const num = Number.parseInt(ctx.params['num']); const num = Number.parseInt(ctx.params['num']);
if(typeof tag_name === undefined){ if(typeof tag_name === undefined){
sendError(400,"??? Unreachable"); return sendError(400,"??? Unreachable");
} }
tag_name = String(tag_name); tag_name = String(tag_name);
const c = await controller.findById(num); const c = await controller.findById(num);
if(c === undefined){ if(c === undefined){
sendError(404); return sendError(404);
return;
} }
const r = await controller.addTag(c,tag_name); const r = await controller.addTag(c,tag_name);
ctx.body = JSON.stringify(r); ctx.body = JSON.stringify(r);
@ -103,13 +98,12 @@ const DelTagHandler = (controller: ContentAccessor)=>async (ctx: Context, next:
let tag_name = ctx.params['tag']; let tag_name = ctx.params['tag'];
const num = Number.parseInt(ctx.params['num']); const num = Number.parseInt(ctx.params['num']);
if(typeof tag_name === undefined){ if(typeof tag_name === undefined){
sendError(400,"?? Unreachable"); return sendError(400,"?? Unreachable");
} }
tag_name = String(tag_name); tag_name = String(tag_name);
const c = await controller.findById(num); const c = await controller.findById(num);
if(c === undefined){ if(c === undefined){
sendError(404); return sendError(404);
return;
} }
const r = await controller.delTag(c,tag_name); const r = await controller.delTag(c,tag_name);
ctx.body = JSON.stringify(r); ctx.body = JSON.stringify(r);
@ -125,8 +119,7 @@ const ContentHandler = (controller : ContentAccessor) => async (ctx:Context, nex
const num = Number.parseInt(ctx.params['num']); const num = Number.parseInt(ctx.params['num']);
let content = await controller.findById(num,true); let content = await controller.findById(num,true);
if (content == undefined){ if (content == undefined){
sendError(404,"content does not exist."); return sendError(404,"content does not exist.");
return;
} }
const path = join(content.basepath,content.filename); const path = join(content.basepath,content.filename);
ctx.state['content'] = createContentReferrer(content.content_type,path,content.additional); ctx.state['content'] = createContentReferrer(content.content_type,path,content.additional);