PROGRAMING/FULL STACK

[Auth] Protecting endpoints using auth-tokens

donghunl 2024. 3. 26. 09:54
반응형

적절한 사용자가 접속했는지 여부를 판단하기 위해서는 Axios를 통해 페이지를 요청하는것 이외에 auth-token을 통해 자격증명을 확인해야 합니다. 그럼 Front  End에서 오는 요청이 적절한 auth-token을 포함하고 있는지 확인하는 작업을 Firebase admin package를 통해 하겠습니다. Express 미들웨어를 통해 request.body을 정보를 받은것처럼 auth-token을 처리하기 위해 미들웨어 추가(app.use)를 통해 처리합니다.

또한 페이지를 불러올때에는 사용자의 로그인 여부는 상관이 없이 보여줘야 하나 이전에 좋아요를 눌렀는지 확인을 하기 위해 Get 요청페이지에 사용자 좋아요에 관한 정보도 같이 로드하요 요청시 그 정보도 함께 Front End를 응답하는 처리도 같이 합니다.

그렇게 작업한 코드는 다음과 같습니다.

server.js

import fs from 'fs';
import admin from 'firebase-admin';
import express from 'express';
import { db, connectToDb } from './db.js';

const credentials = JSON.parse(
    fs.readFileSync('../credentials.json')
);
admin.initializeApp({
    credential: admin.credential.cert(credentials),
});

const app = express();
app.use(express.json());

app.use(async (req, res, next) => {
    const { authtoken } = req.headers;
    if (authtoken) {
        try {
            req.user = await admin.auth().verfiyIdToekn(authtoken);
        } catch (e) {
            res.sendStatus(400);
        }
    }

    next();
});

app.get('/api/articles/:name', async (req, res) => {
    const { name } = req.params;
    const { uid } = req.user;

    const article = await db.collection('articles').findOne({ name });

    if (article) {
        const upvoteIds = article.upvoteIds || [];
        article.canUpvote = uid && !upvoteIds.include(uid);
        res.json(article);
    } else {
        res.sendStatus(404);
    }
});

app.put('/api/articles/:name/upvote', async (req, res) => {
    const { name } = req.params;

    await db.collection('articles').updateOne({ name }, {
        $inc: { upvotes: 1 },
    });
    const article = await db.collection('articles').findOne({ name });

    if (article) {
        res.json(article);
    } else {
        res.send('That article doesn\'t exist');
    }
});

app.post('/api/articles/:name/comments', async (req, res) => {
    const { name } = req.params;
    const { postedBy, text } = req.body;

    await db.collection('articles').updateOne({ name }, {
        $push: { comments: { postedBy, text } },
    });
    const article = await db.collection('articles').findOne({ name });

    if (article) {
        res.json(article);
    } else {
        res.send('That article doesn\'t exist!');
    }
});

connectToDb(() => {
    console.log('Successfully connected to database!');
    app.listen(8000, () => {
        console.log('Server is listening on port 8000');
    });
})
반응형