Authorization Token

Node. js를 이용해 로그인을 구현할 때, 스포티파이에서 제공하는 토큰 인증기능을 덧붙이고 싶었다.
가독성을 위해 메인파일 말고 별개의 js 파일로 분리해 라우터 폴더에 넣어주었다.
처음 작성한 코드는 이렇다.

'use strict';

// login
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const bodyParser = require('body-parser');
const request = require('request');
const CryptoJS = require('crypto-js');
const client_id = 'CLIENT_ID';
const redirect_uri = 'diggig-login://callback';

var app = express();
dotenv.config();

app.use(bodyParser.urlencoded({
    extended : true
}));
app.use(bodyParser.json());
app.use(cors({
    origin: true,
    credentials: true
}));

app.get('/login', function(req, res) {

    var state = generateRandomString(16);
    var scope = 'user-read-private user-read-email';

    res.redirect('https://accounts.spotify.com/authorize?' +
        querystring.stringify({
            response_type: 'code',
            client_id: client_id,
            scope: scope,
            redirect_uri: redirect_uri,
            state: state
        }));
});

//token
app.post('/api/token', token);

var token = app.get('/callback', function(req, res) {

    var code = req.query.code || null;
    var state = req.query.state || null;

    if (state === null) {
        res.redirect('/#' +
        querystring.stringify({
            error: 'state_mismatch'
        }));
    } else {
        var authOptions = {
            url: 'https://accounts.spotify.com/api/token',
            form: {
                code: code,
                redirect_uri: redirect_uri,
                grant_type: 'authorization_code'
            },
            headers: {
                'Authorization': 'Basic ' + (new Buffer(client_id + ':'+
client_secret).toString('base64'))
            },
            json: true
        };
    }
});

//refresh token
app.get('/refresh_token', function(req, res) {

    var refresh_token = req.query.refresh_token;
    var authOptions = {
        url: 'https://accounts.spotify.com/api/token',
        headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + 
client_secret).toString('base64')) },
        form: {
            grant_type: 'refresh_token',
            refresh_token: refresh_token
        }, 
        json: true
    };

    request.post(authOptions, function(error, response, body) {
        if (!error && response.statusCode === 200) {
            var access_token = body.access_token;
            res.send({
                'access_token': access_token
            });
        }
    });
});
//마지막에 서버시작(아직 구현 x)

좋은 웹페이지 즐겨찾기