Skip to content
This repository has been archived by the owner on Jun 4, 2022. It is now read-only.

Backend fix #98

Merged
merged 33 commits into from
Mar 14, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
76ffccc
added cors module and fixed status code
kanade9 Feb 6, 2020
3d4cfe9
cors対応ムリ〜〜
kanade9 Feb 8, 2020
94206da
arrowAll
Feb 8, 2020
0cd617b
updated_by,made_byをedited_byに統一(授業,コメント両方)
kanade9 Feb 10, 2020
875fffb
[WIP] frontにtokenトークン表示
kanade9 Feb 10, 2020
dec9f23
index.ts バックエンド 1つのインスタンスに修正
kanade9 Feb 10, 2020
76111c4
frontend uid取り出そうとして色々試行錯誤したやつ消しました
kanade9 Feb 11, 2020
6ef7dc2
エンドポイント直してなかったの修正
kanade9 Feb 11, 2020
e7c23f8
一通りの修正完了!!
kanade9 Feb 20, 2020
2a409c2
[WIP] tryとcatchのネスト除去などのコードレビュー箇所の修正。uidをバックエンドでよしなにやるところの作業中。
kanade9 Feb 21, 2020
82aa73e
[WIP] コードリファクタリング
kanade9 Feb 23, 2020
cbd51ed
[WIP] GET class_dataの実装完了
kanade9 Feb 25, 2020
c505de1
[WIP] GET,POST comment まで完了。残りはdeleteのみ
kanade9 Feb 28, 2020
ba2552f
api.ts: api仕様通りの修正完了 swagger: subjectとかいう謎のものがあったので消した。残作業:細かいリファクタリング
kanade9 Feb 28, 2020
0e67989
リファクタリングの完了
kanade9 Mar 1, 2020
e989147
[WIP] いろいろ修正
Mar 2, 2020
5ec6597
[WIP]
Mar 4, 2020
609879e
多分デプロイ出来た
Mar 4, 2020
4e74168
これでこそ本当にデプロイ出来た
Mar 4, 2020
ad5b6c2
fix README
Mar 4, 2020
12f378a
色々書いた
Mar 4, 2020
1bf7b78
optionsメソッドの考慮など
kanade9 Mar 6, 2020
6b13b89
Update swagger.yaml
kanade9 Mar 8, 2020
fd5ef9e
にゃn
reud Mar 8, 2020
5f505f6
change scheme
reud Mar 8, 2020
4942529
add
Mar 8, 2020
e087793
Merge branch 'refactor_backend_fix' of https://github.com/gekko-org/p…
Mar 8, 2020
18c9cfa
修正ミスの修正(語彙力)
Mar 10, 2020
8bbcf40
ファイルの切り分け、許可ヘッダの追加
Mar 10, 2020
7efbd41
tokenの切り出し方の修正
Mar 10, 2020
75c2b1f
レスポンスヘッダのエラーの修正
kanade9 Mar 14, 2020
98ce96b
レスポンスヘッダのエラーの修正 再
kanade9 Mar 14, 2020
72ccc2c
Merge pull request #101 from gekko-org/refactor_backend_fix
kanade9 Mar 14, 2020
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
189 changes: 189 additions & 0 deletions backend/functions/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import * as functions from 'firebase-functions';
import * as express from 'express';


const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const bodyParser = require('body-parser');
const moment = require('moment');
const db = admin.database();
const fdb = admin.firestore();
const ref = db.ref('server/account-data/');
const app = express();

app.use(bodyParser.json());

async function Verification(req: express.Request, resp: express.Response, next: () => void) {
// req.headers.authorization のオブジェクトが未定義となるためにts-ignore
// @ts-ignore
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここのコメント消しておいてください (ts-ignore使われていた行は消えましたよね?)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いや、最終的には消えませんでした。ので残しています

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここのts-ignoreはどこにかかっているのです?
image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ああ、21行目か・・・空行消しておいて欲しいかなぁ・・・

// AuthorizationヘッダーはBearer <id_token>の形式のため、id_tokenを取り出すために7文字目以降の文字列を切り出している
const tokenstr = req.headers.authorization.toString().slice(7);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

iine

console.log(tokenstr);
const token = await admin.auth().verifyIdToken(tokenstr);
const uid=token.uid;
console.log(uid);
ref.child('users/' + uid).once("value", (snapshot: { exists: () => any; }) => {
if (snapshot.exists()) {
next();
} else {
console.log('Error: Id token does not match \'query uid\' ');
resp.status(401).send('Unauthorized');
}
});
}

app.use(Verification);

export const RegisterLog = functions.auth.user().onCreate((user) => {
console.log('Hello ' + user.displayName + ' logged in' + 'called by TS');

// データベースに書き込む。一意に定まるユーザのuidを主キーとして設定し、メアドと名前を格納する。
ref.child('users/' + user.uid).set({
mail: user.email,
name: user.displayName
});
return 0;
});

export const UnRegisterLog = functions.auth.user().onDelete((user) => {
console.log('Hello ' + user.displayName + ' account deleted ' + 'called by TS');

ref.child('users/' + user.uid).remove();

return 0;
});

// build multiple CRUD interfaces:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメント内容と表す行合ってない様な・・・

app.get('/class_data', async (req: functions.Request, resp: express.Response) => {
console.log('subject_query= ' + req.query['class_name']);
const err = "";
const db_data = await fdb.collection('ClassSummary').doc(req.query['class_name']).get();
const record = db_data.data();
if (err !== "") {
console.log('class not found probably wrong or empty query');
resp.status(404).send('Not Found');
} else {
resp.send(JSON.stringify(record));
}
});


app.post('/class_data', async (req: functions.Request, resp: express.Response) => {
console.log('json received');
const body = req.body;

// Check the validity of the token

const uid = admin.auth.decodedToken(body.token).uid;
if (!uid) {
resp.status(401).send('Unauthorized');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この辺もreturn 入れ忘れてない?

return 0;
} else {
console.log(uid);
}

const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
const class_created_time = doc.data().created_at || moment().add(9, 'h').format();

const data = {
'name': body.name,
'faculty': body.faculty,
'department': body.department,
'fav_amount': 0,
'grade': body.grade,
'professor': body.professor,
'is_random': body.is_random,
'rating': 0,
'term': body.term,
'edited_by': body.edited_by,
'created_at': class_created_time,
'updated_at': moment().add(9, 'h').format(),
};
let err = "";
await fdb.collection('ClassSummary').doc(body.name).set(data).catch((e: string) => err = e);

if (err !== "") {
console.log('An error occurred. Class data cannot add in database' + err);
resp.status(500).send('Internal Server Error');
return 0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kanade9
ふと思ったんですけど、ここ何故0返しているんですか?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

voidの認識なので return;で良いかと。原因の切り分けにもなるので変更お願いします

} else {
console.log(data);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

early returnしているのでここのelseはいらないと思う!

resp.status(200).send(JSON.stringify({'status': 'OK'}));
return 0;
}
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

memo

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kanade9 この辺見てるけど変更箇所として見る部分は合ってる?

参考サイトの記事読みました。documentのデータはjson型なのに、エラーでstring型を指定しているところに原因があるかもしれません。

これresponse送るところ(resp.status(500).send('Internal Server Error');)について原因があるのではないかっていう予想で合ってる?
見た感じ変更前と変更後で変わってない様な・・・・


app.get('/comment', async (req: functions.Request, resp: express.Response) => {
console.log('subject_query= ' + req.query['class_name'] + ' uid=' + req.query['uid']);
let err = "";
const qss = await fdb.collection('ClassSummary')
.doc(req.query['class_name'])
.collection('comment')
.doc(req.query['uid']).get().catch((e: string) => err = e);

if (err !== "") {
console.log('class not found probably wrong or empty query');
resp.status(404).send('Not Found');
return 0;
} else if (!qss.data()) {
console.log('No comment were found match with ' + req.query['class_name'] + ' and this uid');
resp.status(404).send('Not Found');
return 0;

} else {
resp.status(200).send(JSON.stringify(qss.data()));
return 0;
}
});

app.post('/comment', async (req: functions.Request, resp: express.Response) => {
console.log('json received');
const body = req.body;
const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
const created_time = doc.data().created_at || moment().add(9, 'h').format();
const data = {
// nameは授業名です。titleはコメントのタイトル ex. 神授業です!!等
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いいね

'name': body.name,
'title': body.title,
'comment': body.comment,
'created_at': created_time,
'updated_at': moment().add(9, 'h').format(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

'edited_by': body.edited_by,
'image': body.image,
'is_recommend': body.is_recommend
};
// IDでなくユーザのuidを用いてデータベースに格納する
let err = "";
await fdb.collection('ClassSummary')
.doc(body.name).collection('comment')
.doc(body.made_by).set(data).data().catch((e: string) => err = e);

if (err !== "") {
console.log('An error occurred. Comment cannot add in database');
resp.status(500).send('Internal Server Error');

} else {
console.log(data);
resp.status(200).send(JSON.stringify({'status': 'OK'}));
}
});


app.delete('/comment', async (req: functions.Request, resp: express.Response) => {
console.log(req.query['class_name'], '+', req.query['uid']);
let err = "";
await fdb.collection('ClassSummary')
.doc(req.query['class_name'])
.collection('comment')
.doc(req.query['uid']).delete().catch((e: string) => err = e);

if (err !== "") {
console.log('An error occurred. Comment cannot delete from database');
resp.status(500).send('Internal Server Error');
} else {
resp.status(200);
}
});

exports.api = functions.https.onRequest(app);
184 changes: 1 addition & 183 deletions backend/functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,183 +1 @@
import * as functions from 'firebase-functions';
import * as express from 'express';

const bodyParser = require('body-parser');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const db = admin.database();
const fdb = admin.firestore();

const ref = db.ref('server/account-data/');

const app = express();
// const commentData = express();
const moment = require('moment');

app.use(bodyParser.json());

async function Verification(req: express.Request, resp: express.Response, next: () => void) {
// req.headers.authorization のオブジェクトが未定義となるためにts-ignore
// @ts-ignore

// AuthorizationヘッダーはBearer <id_token>の形式のため、id_tokenを取り出すために7文字目以降の文字列を切り出している
const tokenstr = req.headers.authorization.toString().slice(7);

try {
const token = await admin.auth().verifyIdToken(tokenstr);

if (token.uid === req.query['uid']) {
next();
} else {
console.log('Error: Id token does not match \'query uid\' ');
resp.status(401).send('Unauthorized');
}
} catch (exception) {
console.log('Error: Firebase ID token has kid claim which does not correspond to a known public key. so get a fresh token from your client app and try again');
resp.status(401).send('Unauthorized');
}
}

app.use(Verification);

export const WelcomeLog = functions.auth.user().onCreate((user) => {
console.log('Hello ' + user.displayName + ' logged in' + 'called by TS');

// データベースに書き込む。一意に定まるユーザのuidを主キーとして設定し、メアドと名前を格納する。
ref.child('users/' + user.uid).set({
mail: user.email,
name: user.displayName
});
return 0;
});

export const DeleteLog = functions.auth.user().onDelete((user) => {
console.log('Hello ' + user.displayName + ' account deleted ' + 'called by TS');

ref.child('users/' + user.uid).remove();

return 0;
});

// build multiple CRUD interfaces:
app.get('/class_data', async (req: functions.Request, resp: express.Response) => {
console.log('subject_query= ' + req.query['class_name']);
try {
const documentSnapshot = await fdb.collection('ClassSummary').doc(req.query['class_name']).get();
const record = documentSnapshot.data();
if (!record) {
console.log('class not found probably wrong or empty query');
resp.status(404).send('Not Found');
}
resp.send(JSON.stringify(record));
} catch (exception) {
console.log('class not found probably wrong or empty query');
resp.status(404).send('Not Found');
}
});

app.post('/class_data', async (req: functions.Request, resp: express.Response) => {
console.log('json received');
const body = req.body;

// Check the validity of the token
const uid = admin.auth.decodedToken(body.token).uid;
if (!uid) {
resp.status(401).send('Unauthorized');
} else {
console.log(uid);
}

let class_created_time = null;
const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
if (doc.exists) {
class_created_time = doc.data().created_at;
} else {
class_created_time = moment().add(9, 'h').format();
}
const data = {
'name': body.name,
'faculty': body.faculty,
'department': body.department,
'fav_amount': body.fav_amount,
'grade': body.grade,
'professor': body.professor,
'is_random': body.is_random,
'rating': body.rating,
'term': body.term,
'edited_by': body.edited_by,
'created_at': class_created_time,
'updated_at': moment().add(9, 'h').format(),
};
try {
await fdb.collection('ClassSummary').doc(body.name).set(data);
console.log(data);
resp.status(200).send(JSON.stringify({'status': 'OK'}));
} catch (exception) {
console.log('An error occurred. Class data cannot add in database');
resp.status(500).send('Internal Server Error');
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

メモ

});

app.get('/comment', async (req: functions.Request, resp: express.Response) => {
console.log('subject_query= ' + req.query['class_name'] + ' uid=' + req.query['uid']);
try {
const qss = await fdb.collection('ClassSummary').doc(req.query['class_name']).collection('comment').doc(req.query['uid']).get();
if (!qss.data()) {
console.log('No comment were found match with ' + req.query['class_name'] + ' and this uid');
resp.status(404).send('Not Found');
}
resp.status(200).send(JSON.stringify(qss.data()));
} catch (exception) {
console.log('class not found probably wrong or empty query');
resp.status(404).send('Not Found');
}
});

app.post('/comment', async (req: functions.Request, resp: express.Response) => {
console.log('json received');
const body = req.body;
let created_time = null;
const doc = await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).get();
if (doc.exists) {
created_time = doc.data().created_at;
} else {
created_time = moment().add(9, 'h').format();
}

const data = {
'name': body.name,
'title': body.title,
'comment': body.comment,
'created_at': created_time,
'updated_at': moment().add(9, 'h').format(),
'edited_by': body.edited_by,
'image': body.image,
'is_recommend': body.is_recommend
};
// IDでなくユーザのuidを用いてデータベースに格納する
try {
await fdb.collection('ClassSummary').doc(body.name).collection('comment').doc(body.made_by).set(data);
console.log(data);
resp.status(200).send(JSON.stringify({'status': 'OK'}));
} catch (exception) {
console.log('An error occurred. Comment cannot add in database');
resp.status(500).send('Internal Server Error');
}
});


app.delete('/comment', async (req: functions.Request, resp: express.Response) => {
console.log(req.query['class_name'], '+', req.query['uid']);
try {
await fdb.collection('ClassSummary').doc(req.query['class_name']).collection('comment').doc(req.query['uid']).delete();
resp.status(200);
} catch (exception) {
console.log('An error occurred. Comment cannot delete from database');
resp.status(500).send('Internal Server Error');
}
});

// Expose Express API as a single Cloud Function:
exports.app = functions.https.onRequest(app);
export * from "./api"
4 changes: 4 additions & 0 deletions swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,12 @@ definitions:
properties:
name:
type: "string"
example:
"dummy class1"
title:
type: "string"
example:
"You should take this class!!"
image:
type: "string"
edited_by:
Expand Down