Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

백엔드 서버 구조 변경 #9

Merged
merged 4 commits into from
Aug 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
"description": "SSU IT Collage Locker system.",
"private": true,
"scripts": {
"build": "pnpm --filter=./packages/** --stream build",
"dev": "pnpm --filter=./packages/** --stream dev",
"delete": "pnpm delete --filter=client && pnpm delete --filter=server --stream",
"deploy": "pnpm deploy --filter=client && pnpm deploy --filter=server --stream"
"build": "pnpm run --filter=./packages/** --stream build",
"dev": "pnpm run --filter=./packages/** --stream dev",
"delete": "pnpm run delete --filter=client && pnpm delete --filter=server --stream",
"deploy": "pnpm run deploy --filter=client && pnpm deploy --filter=server --stream"
},
"repository": {
"type": "git",
Expand Down
51 changes: 51 additions & 0 deletions packages/server/src/auth/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { UpdateItemInput } from "aws-sdk/clients/dynamodb";
import { adminId, dynamoDB, TableName } from "../common";
import { UnauthorizedError } from "../error";

export const revokeToken = async function(
id: string,
token: string
): Promise<{ accessToken: string }> {
const req: UpdateItemInput = {
TableName,
Key: { id: { S: id } },
UpdateExpression: 'REMOVE accessToken',
ConditionExpression: 'accessToken = :token',
ExpressionAttributeValues: {
':token': { S: token }
},
ReturnValues: 'UPDATED_OLD'
};
const res = await dynamoDB.updateItem(req).promise();
if (res.Attributes.hasOwnProperty('accessToken')) {
return { accessToken: token };
} else {
throw new UnauthorizedError();
}
};

export const issueToken = async function(
id: string,
token: string
): Promise<{ id: string; expires: number }> {
const expires = Date.now() + 3600 * 1000;
const req: UpdateItemInput = {
TableName,
Key: { id: { S: id } },
UpdateExpression: 'SET accessToken = :token, expiresOn = :expiresOn',
ExpressionAttributeValues: {
':token': { S: token },
':expiresOn': { N: `${expires}` }
},
ReturnValues: 'UPDATED_NEW'
};
if (id !== adminId) {
req.ConditionExpression = 'attribute_exists(is_admin) OR attribute_exists(department)';
}
const res = await dynamoDB.updateItem(req).promise();
if (res.Attributes.hasOwnProperty('accessToken')) {
return { id, expires };
} else {
throw new UnauthorizedError('Unauthorized', { id, expires });
}
};
23 changes: 23 additions & 0 deletions packages/server/src/auth/handler/logout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { APIGatewayProxyHandler } from "aws-lambda";
import * as jwt from "jsonwebtoken";
import { JWT_SECRET } from "../../env";
import type { JwtPayload } from "jsonwebtoken";
import { revokeToken } from "../data";
import { createResponse } from "../../common";

export const logoutHandler: APIGatewayProxyHandler = async (event) => {
const token = (event.headers.Authorization ?? '').replace('Bearer ', '');
try {
const payload = jwt.verify(token, JWT_SECRET) as JwtPayload;
const res = await revokeToken(payload.aud as string, token);
return createResponse(200, { success: true, ...res });
} catch (err) {
const res = {
success: false,
token,
error: 401,
error_description: 'Unauthorized'
};
return createResponse(401, res);
}
};
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import https from 'https';
import { issueToken, revokeToken } from './db_client';
import type { APIGatewayProxyHandler } from 'aws-lambda';
import type { JwtPayload } from 'jsonwebtoken';
import * as jwt from 'jsonwebtoken';
import { JWT_SECRET } from './env';
import { createResponse } from './common';
import { ResponsibleError, UnauthorizedError } from './error';
import { JWT_SECRET } from '../../env';
import { createResponse } from '../../common';
import { ResponsibleError, UnauthorizedError } from '../../error';
import { issueToken } from "../data";

function requestBody(result: string): Promise<string> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -34,7 +33,7 @@ async function obtainId(result: string) {
return body.substring(body.indexOf('pseudonym_session_unique_id') + 36).split('"')[0];
}

export const callbackHandler: APIGatewayProxyHandler = async (event) => {
export const ssuLoginHandler: APIGatewayProxyHandler = async (event) => {
try {
const result = event?.queryStringParameters?.result;
if (result) {
Expand Down Expand Up @@ -68,20 +67,3 @@ export const callbackHandler: APIGatewayProxyHandler = async (event) => {
return e.response();
}
};

export const logoutHandler: APIGatewayProxyHandler = async (event) => {
const token = (event.headers.Authorization ?? '').replace('Bearer ', '');
try {
const payload = jwt.verify(token, JWT_SECRET) as JwtPayload;
const res = await revokeToken(payload.aud as string, token);
return createResponse(200, { success: true, ...res });
} catch (err) {
const res = {
success: false,
token,
error: 401,
error_description: 'Unauthorized'
};
return createResponse(401, res);
}
};
42 changes: 42 additions & 0 deletions packages/server/src/common.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
import type { APIGatewayProxyHandler, APIGatewayProxyResult } from 'aws-lambda';
import lockerData from './lockers.json';
import AWS from 'aws-sdk';
import type { ServiceConfigurationOptions } from 'aws-sdk/lib/service';
import type {
ClientApiVersions,
GetItemInput
} from 'aws-sdk/clients/dynamodb';
import { UnauthorizedError } from "./error";


const awsRegion = process.env.AWS_REGION ?? 'ap-southeast-2';
export const TableName = process.env.TABLE_NAME ?? 'LockerTable';
export const adminId = process.env.ADMIN_ID ?? '20211561';

const options: ServiceConfigurationOptions & ClientApiVersions = {
apiVersion: '2012-08-10',
region: awsRegion
};

if (process.env.AWS_SAM_LOCAL) {
options.endpoint = new AWS.Endpoint('http://dynamodb:8000');
}

export const dynamoDB = new AWS.DynamoDB(options);

export function createResponse(statusCode: number, body: string | object): APIGatewayProxyResult {
const stringifyBody = typeof body === 'string' ? body : JSON.stringify(body);
Expand Down Expand Up @@ -27,6 +50,25 @@ type LockerMap = {

export const lockers: LockerMap = lockerData as LockerMap;

export const assertAdmin = async function(modId: string, token: string) {
const authReq: GetItemInput = {
TableName,
Key: {
id: {
S: modId
}
}
};
const authRes = await dynamoDB.getItem(authReq).promise();
if (
authRes.Item.id.S !== modId ||
authRes.Item.accessToken?.S !== token ||
(authRes.Item.isAdmin?.BOOL !== true && modId !== adminId)
) {
throw new UnauthorizedError('Unauthorized');
}
};

export function isValidLocker(
lockerFloor: string,
lockerId: string,
Expand Down
Empty file.
13 changes: 13 additions & 0 deletions packages/server/src/config/handler/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { APIGatewayProxyHandler } from "aws-lambda";
import * as jwt from "jsonwebtoken";
import { JWT_SECRET } from "../../env";
import type { JwtPayload } from "jsonwebtoken";
import { createResponse } from "../../common";

export const getConfigHandler: APIGatewayProxyHandler = async (event) => {
const token = (event.headers.Authorization ?? '').replace('Bearer ', '');
const id = (jwt.verify(token, JWT_SECRET) as JwtPayload).aud as string;
return createResponse(200, {
success: true
});
};
13 changes: 13 additions & 0 deletions packages/server/src/config/handler/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { APIGatewayProxyHandler } from "aws-lambda";
import * as jwt from "jsonwebtoken";
import { JWT_SECRET } from "../../env";
import type { JwtPayload } from "jsonwebtoken";
import { createResponse } from "../../common";

export const updateConfigHandler: APIGatewayProxyHandler = async (event) => {
const token = (event.headers.Authorization ?? '').replace('Bearer ', '');
const id = (jwt.verify(token, JWT_SECRET) as JwtPayload).aud as string;
return createResponse(200, {
success: true
});
};
Loading