Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:TeamSparker/Spark-Server into fe…
Browse files Browse the repository at this point in the history
…ature/#10
  • Loading branch information
xxeol2 committed Jan 11, 2022
2 parents e9b4d09 + c6a1f0e commit 7a7fabe
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 15 deletions.
30 changes: 30 additions & 0 deletions functions/api/routes/auth/authTestGET.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const util = require('../../../lib/util');
const statusCode = require('../../../constants/statusCode');
const responseMessage = require('../../../constants/responseMessage');
const db = require('../../../db/db');
const { userDB } = require('../../../db');
const jwtHandlers = require('../../../lib/jwtHandlers');


module.exports = async (req, res) => {
const user = req.user;
console.log(user);
if (!user) return res.status(statusCode.BAD_REQUEST).send(util.fail(statusCode.BAD_REQUEST, responseMessage.NO_USER));

let client;

try {
client = await db.connect();

res.status(statusCode.OK).send(util.success(statusCode.OK, "token -> user 활용법", user));
} catch (error) {
console.log(error);
functions.logger.error(`[ERROR] [${req.method.toUpperCase()}] ${req.originalUrl}`, `[CONTENT] ${error}`);

res.status(statusCode.INTERNAL_SERVER_ERROR).send(util.fail(statusCode.INTERNAL_SERVER_ERROR, responseMessage.INTERNAL_SERVER_ERROR));
} finally {
client.release();
}
};
3 changes: 3 additions & 0 deletions functions/api/routes/auth/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const express = require('express');
const router = express.Router();
const uploadImage = require('../../../middlewares/uploadImage');
const { checkUser } = require('../../../middlewares/auth');

router.post('/signup',uploadImage, require('./authSignupPOST'));
// router.get('/test', checkUser, require('./authTestGET'));
router.get('/test', checkUser, require('./authTestGET'));

module.exports = router;
14 changes: 13 additions & 1 deletion functions/db/user.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
const _ = require('lodash');
const convertSnakeToCamel = require('../lib/convertSnakeToCamel');

const getUserById = async (client, userId) => {
const { rows } = await client.query(
`
SELECT * FROM spark.user u
WHERE user_id = $1
AND is_deleted = FALSE
`,
[userId],
);
return convertSnakeToCamel.keysToCamel(rows[0]);
}

const getUserBySocialId = async (client, socialId) => {
const { rows } = await client.query(
`
Expand All @@ -27,4 +39,4 @@ const addUser = async (client, socialId, nickname, profileImg) => {
return convertSnakeToCamel.keysToCamel(rows[0]);
};

module.exports = { getUserBySocialId, addUser };
module.exports = { getUserById, getUserBySocialId, addUser };
21 changes: 7 additions & 14 deletions functions/lib/jwtHandlers.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,48 @@
const functions = require('firebase-functions');
const jwt = require('jsonwebtoken');
const { TOKEN_INVALID, TOKEN_EXPIRED } = require('../constants/jwt');

// JWT를 발급/인증할 떄 필요한 secretKey를 설정합니다. 값은 .env로부터 불러옵니다.
const secretKey = process.env.JWT_SECRET;
const options = {
algorithm: 'HS256',
expiresIn: '30d',
issuer: 'wesopt',
};

// id, email, name, idFirebase가 담긴 JWT를 발급합니다.
const sign = (user) => {
const payload = {
id: user.id,
email: user.email,
name: user.name || null,
idFirebase: user.idFirebase,
const payload = {
userId: user.userId
};

const result = {
accesstoken: jwt.sign(payload, secretKey, options),
// refreshToken: jwt.sign(payload, secretKey, refreshOptions),
};
return result;
};

// JWT를 해독하고, 해독한 JWT가 우리가 만든 JWT가 맞는지 확인합니다 (인증).
const verify = (token) => {
let decoded;
try {
// console.log("token:",token);
decoded = jwt.verify(token, secretKey);
} catch (err) {
if (err.message === 'jwt expired') {
console.log('expired token');
functions.logger.error('expired token');
return TOKEN_EXPIRED;
} else if (err.message === 'invalid token') {
console.log("decoded:", decoded);
console.log('invalid token');
functions.logger.error('invalid token');
console.log(TOKEN_INVALID);
return TOKEN_INVALID;
} else {
console.log('invalid token');
functions.logger.error('invalid token');
return TOKEN_INVALID;
}
}
// 해독 / 인증이 완료되면, 해독된 상태의 JWT를 반환합니다.
return decoded;
};

module.exports = {
sign,
verify,
};
};

0 comments on commit 7a7fabe

Please sign in to comment.