Skip to content

Commit

Permalink
Merge pull request #4 from GRI-G/develop
Browse files Browse the repository at this point in the history
update 1.0.4
  • Loading branch information
sunrabbit123 authored Apr 3, 2022
2 parents 2cd2cbe + 030c0c2 commit e0ecb0a
Show file tree
Hide file tree
Showing 11 changed files with 374 additions and 522 deletions.
75 changes: 4 additions & 71 deletions DTO/serverless.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,7 @@
"user strict";

export type eventType = {
body: { [k: string]: string } | string;
headers: {
Host: string;
Connection: string;
"sec-ch-ua": string;
"sec-ch-ua-mobile": string;
"Upgrade-Insecure-Requests": string;
"User-Agent": string;
Accept: string;
"Sec-Fetch-Site": string;
"Sec-Fetch-Mode": string;
"Sec-Fetch-Dest": string;
"Accept-Encoding": string;
"Accept-Language": string;
};
httpMethod: string;
isBase64Encoded: boolean;
multiValueHeaders: {
Host: Array<string>;
Connection: Array<string>;
"sec-ch-ua": Array<string>;
"sec-ch-ua-mobile": Array<string>;
"Upgrade-Insecure-Requests": Array<string>;
"User-Agent": Array<string>;
Accept: Array<string>;
"Sec-Fetch-Site": Array<string>;
"Sec-Fetch-Mode": Array<string>;
"Sec-Fetch-Dest": Array<string>;
"Accept-Encoding": Array<string>;
"Accept-Language": Array<string>;
};
multiValueQueryStringParameters: { [k: string]: string };
path: string;
pathParameters: { [k: string]: string };
queryStringParameters: { [k: string]: string };
requestContext: {
accountId: string;
apiId: string;
authorizer: { [k: string]: string };
domainName: string;
domainPrefix: string;
extendedRequestId: string;
httpMethod: string;
identity: {
accessKey: null;
accountId: string;
apiKey: string;
apiKeyId: string;
caller: string;
cognitoAuthenticationProvider: string;
cognitoAuthenticationType: string;
cognitoIdentityId: string;
cognitoIdentityPoolId: string;
principalOrgId: any;
sourceIp: string;
user: string;
userAgent: string;
userArn: string;
};
path: string;
protocol: string;
requestId: string;
requestTime: string;
requestTimeEpoch: BigInt;
resourceId: string;
resourcePath: string;
stage: string;
};
resource: string;
stageVariables: boolean;
export type Response = {
statusCode: number;
body: string;
headers: Object;
};
2 changes: 1 addition & 1 deletion app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ const apollo = new ApolloServer({
debug: DEBUG,
});

exports.graphqlHandler = apollo.createHandler({});
export const graphqlHandler = apollo.createHandler({});
93 changes: 41 additions & 52 deletions auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use strict";

import * as mongoose from "mongoose";
import { APIGatewayEvent } from "aws-lambda";

import { serverless_DTO } from "./DTO";

Expand All @@ -16,13 +16,15 @@ import {
createToken,
updateUserInformation,
findUserByNickname,
testIsGSMEmail,
} from "./util/user";
import { connectMongoDB } from "./src/util/db";

const createRes: Function = (
status: number,
body?: Object,
headers?: Object,
) => {
): serverless_DTO.Response => {
return {
statusCode: status,
body: JSON.stringify(body),
Expand All @@ -31,9 +33,9 @@ const createRes: Function = (
};

exports.authUserByOAuth = async (
event: serverless_DTO.eventType,
event: APIGatewayEvent,
_: any,
cb: Function,
__: Function,
) => {
const data = event.queryStringParameters;
const access_token = (await getAccessTokenByCode(data.code)).access_token;
Expand All @@ -42,7 +44,7 @@ exports.authUserByOAuth = async (

let page = "complete.html";
const user = await findUserByNickname(nickname);
if (!(user?.certified == true)) {
if (!user?.certified) {
if (!user) {
await createUser({
accessToken: access_token,
Expand All @@ -61,16 +63,12 @@ exports.authUserByOAuth = async (
);
};

exports.authEmail = async (
event: serverless_DTO.eventType,
_: any,
cb: Function,
) => {
exports.authEmail = async (event: APIGatewayEvent, _: any, __: Function) => {
const searchPrams = new URLSearchParams(event.body);
const code = searchPrams.get("code");
const email = searchPrams.get("email");

if (email?.slice(-10) !== "@gsm.hs.kr" || !email?.startsWith("s")) {
if (testIsGSMEmail(email)) {
return createRes(400, { detail: "GSM 학생 계정이어야합니다." });
}

Expand All @@ -84,49 +82,40 @@ exports.authEmail = async (
return createRes(204);
};

exports.authUserByEmail = async (event: serverless_DTO.eventType, _: any) => {
mongoose
.connect(process.env.MongoDBUrl ?? "", {
useFindAndModify: false,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then((): void => console.log("MongoDB connected"))
.catch((err: Error): void =>
console.log("Failed to connect MongoDB: ", err),
);
const dataId = event.pathParameters["token"];
const data = await CodeModel.findById(dataId);
exports.authUserByEmail = connectMongoDB(
async (event: APIGatewayEvent, _: any) => {
const dataId = event.pathParameters["token"];
const data = await CodeModel.findById(dataId);

const email: string = data.email;
const nickname: string = data.nickname;
const generation: number = /^(student\d{6}|s\d{5})@gsm.hs.kr$/.test(email)
? Number(email.replace(/[^0-9]/g, "").slice(0, 2)) - 16
: 0;
const email: string = data.email;
const nickname: string = data.nickname;
const generation: number = testIsGSMEmail(email)
? Number(email.replace(/[^0-9]/g, "").slice(0, 2)) - 16
: 0;

if (generation === 0) {
createRes(404, { message: "GSM 학생이 아닙니다." });
}
if (generation === 0) {
createRes(404, { message: "GSM 학생이 아닙니다." });
}

const user = await UserModel.findUserFromNickname(nickname);
try {
await user.updateGeneration(generation);
console.log("Success update Generation");
await user.setCertifiedTrue();
console.log("Success Set Certified True");
await updateUserInformation(user);
console.log("Update User Information");
} catch (e: any) {
console.error(e);
}
const user = await UserModel.findUserFromNickname(nickname);
try {
await user.updateGeneration(generation);
console.log("Success update Generation");
await user.setCertifiedTrue();
console.log("Success Set Certified True");
await updateUserInformation(user);
console.log("Update User Information");
} catch (e: any) {
console.error(e);
}

await CodeModel.findByIdAndDelete(dataId);
console.log("Success find By Id and delete data Id");
await CodeModel.findByIdAndDelete(dataId);
console.log("Success find By Id and delete data Id");

return createRes(
302,
{},
{ Location: `${process.env.AUTH_BASEURL}complete.html` },
);
};
return createRes(
302,
{},
{ Location: `${process.env.AUTH_BASEURL}complete.html` },
);
},
);
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "github-ranking-for-gsm",
"version": "1.0.2",
"version": "1.0.4",
"repository": "https://github.com/sunrabbit123/Github-Rangkin-for-GSM.git",
"author": "sunrabbit123 <qudwls185@naver.com>",
"license": "SPDX",
Expand All @@ -13,12 +13,12 @@
"dependencies": {
"@fxts/core": "^0.5.0",
"@typegoose/typegoose": "^8.1.1",
"apollo-server-lambda": "^3.0.0",
"apollo-server-lambda": "^3.6.7",
"axios": "^0.21.1",
"graphql": "^15.5.1",
"graphql": "^16.3.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.13.7",
"nexus": "^1.1.0",
"nexus": "^1.3.0",
"nodemailer": "^6.6.3"
},
"devDependencies": {
Expand All @@ -29,7 +29,7 @@
"@types/nodemailer": "^6.4.4",
"prettier": "^2.3.2",
"serverless-dotenv-plugin": "^3.9.0",
"serverless-offline": "^7.0.0",
"serverless-offline": "^8.5.0",
"serverless-plugin-typescript": "^1.1.9",
"ts-node": "^10.2.1",
"typescript": "^4.3.5"
Expand Down
2 changes: 1 addition & 1 deletion src/schema/types/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import * as q from "./queries";
export const Query = queryType({
definition(t) {
t.list.field("ranking", q.userRanking);
t.list.field("generations", q.hasGeneration);
t.list.field("generation", q.hasGeneration);
},
});
36 changes: 8 additions & 28 deletions src/schema/types/queries/Ranking.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { intArg, stringArg } from "nexus";
import * as mongoose from "mongoose";

import { INFORMATION_DTO } from "../../../DTO";
import { UserModel } from "../../../model/users";
import { getKindOfGenaration } from "../../../service/user";
import { connectMongoDB } from "../../../util/db";

import { sortBy } from "@fxts/core";

export const userRanking = {
Expand All @@ -14,35 +15,14 @@ export const userRanking = {
page: intArg(),
generation: intArg(),
},
resolve: async (_: any, args: INFORMATION_DTO.GetRankingInput, __: any) => {
mongoose
.connect(process.env.MongoDBUrl ?? "", {
useFindAndModify: false,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then((): void => console.log("MongoDB connected"))
.catch((err: Error): void =>
console.log("Failed to connect MongoDB: ", err),
);
return UserModel.getRanking(args);
},
resolve: (_: any, args: INFORMATION_DTO.GetRankingInput, __: any) =>
connectMongoDB(() => UserModel.getRanking(args))(),
};

export const hasGeneration = {
type: "Generation",
resolve: async (_: any, __: any, ___: any) => {
const db = await mongoose.connect(process.env.MongoDBUrl ?? "", {
useFindAndModify: false,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const result = await getKindOfGenaration();
if (result) {
db.disconnect();
return sortBy((r) => r._id, result);
}
},
resolve: async (_: any, __: any, ___: any) =>
await connectMongoDB(async () =>
sortBy((r) => r._id, await getKindOfGenaration()),
)(),
};
3 changes: 2 additions & 1 deletion src/service/user.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { UserModel } from "../model/users";

export const getKindOfGenaration: Function = async () => {
return await UserModel.aggregate([
const a = await UserModel.aggregate([
{ $match: { generation: { $exists: true } } },
// count grouping status
{ $group: { _id: "$generation", count: { $sum: 1 } } },
]);
return a;
};
17 changes: 17 additions & 0 deletions src/util/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as mongoose from "mongoose";

export const connectMongoDB: Function = (next: (...args: any[]) => any) => {
return async (...args: any[]) => {
const db = await mongoose.connect(process.env.MongoDBUrl ?? "", {
useFindAndModify: true,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const result = await next(...args);
if (result) {
db.disconnect();
}
return result;
};
};
26 changes: 10 additions & 16 deletions util/code.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import * as mongoose from "mongoose";
import { CodeModel } from "../src/model/code";
import { connectMongoDB } from "../src/util/db";

export const deleteRemainCode: Function = async (): Promise<void> => {
const db = await mongoose.connect(process.env.MongoDBUrl ?? "", {
useFindAndModify: true,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});

var dateTime = new Date();
dateTime.setMinutes(dateTime.getMinutes() - 5);
await CodeModel.deleteMany({ createdAt: { $lte: dateTime } });
console.log("사용되지않는 코드들 제거 완료");
db.disconnect();
return;
};
export const deleteRemainCode: Function = connectMongoDB(
async (): Promise<void> => {
var dateTime = new Date();
dateTime.setMinutes(dateTime.getMinutes() - 5);
await CodeModel.deleteMany({ createdAt: { $lte: dateTime } });
console.log("사용되지않는 코드들 제거 완료");
return;
},
);
Loading

0 comments on commit e0ecb0a

Please sign in to comment.