유희정

kakao login

Showing 53 changed files with 1958 additions and 6 deletions
......@@ -9,6 +9,7 @@ var index = require('./routes/index');
var users = require('./routes/users');
var calendar = require('./routes/calendar');
var events = require('./routes/events');
var login = require('./routes/login')
passport.serializeUser(function(user,done) {
console.log('serialized');
......@@ -44,6 +45,7 @@ app.use('/', index);
app.use('/users', users);
app.use('/calendar',calendar);
app.use('/events',events);
app.use('/login',login);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
......
{
"trailingComma": "es5",
"semi": false,
"singleQuote": true,
"arrowParens": "avoid",
"bracketSpacing": true,
"endOfLine": "auto",
"htmlWhitespaceSensitivity": "css",
"proseWrap": "preserve",
"quoteProps": "as-needed",
"tabWidth": 2
}
language: node_js
node_js:
- '0.10'
before_script:
- npm install -g jasmine-node
# passport-kakao
kakao oauth2 로그인과 passport 모듈 연결체.
## install
```sh
npm install passport-kakao
```
## how to use
- https://developers.kakao.com/ 에서 애플리케이션을 등록한다.
- 방금 추가한 애플리케이션의 설정 - 사용자 관리에 들어가서 사용을 ON으로 한 뒤 저장한다.
- 설정 - 일반에서, 플랫폼 추가를 누른 후 웹 플랫폼을 추가한다.
- 웹 플랫폼 설정의 사이트 도메인에 자신의 사이트 도메인을 추가한다. (ex : http://localhost:3000)
- 프로그램 상에서는 아래와 같이 사용한다.
> clientSecret을 활성화 한 경우 해당 파라메터를 같이 넘겨줘야한다.
```javascript
const passport = require('passport')
const KakaoStrategy = require('passport-kakao').Strategy
passport.use(new KakaoStrategy({
clientID : clientID,
clientSecret: clientSecret, // clientSecret을 사용하지 않는다면 넘기지 말거나 빈 스트링을 넘길 것
callbackURL : callbackURL
},
(accessToken, refreshToken, profile, done) => {
// 사용자의 정보는 profile에 들어있다.
User.findOrCreate(..., (err, user) => {
if (err) { return done(err) }
return done(null, user)
})
}
))
```
> 기본 callbackPath는 `/oauth` 이고 https://developers.kakao.com 에서 수정할 수 있다. 하지만 callbackURL은 `사이트 도메인/oauth` 로 설정하는 것을 권장함. (ex : http://myhomepage.com:3000/oauth )
##
## profile property
profile에는 아래의 property들이 설정되어 넘겨진다.
| key | value | 비고 |
| -------- | ------ | ------------------------------------------ |
| provider | String | kakao 고정 |
| id | Number | 사용자의 kakao id |
| \_raw | String | 사용자 정보 조회로 얻어진 json string |
| \_json | Object | 사용자 정보 조회로 얻어진 json 원본 데이터 |
## simple sample
### 설치 & 실행
1. `./sample/sample.js``appKey` 를 https://developers.kakao.com 에서 발급받은 JS appKey 값으로 셋팅.
2. command line 에서 아래의 커맨드 실행
3. 브라우져를 열고 `127.0.0.1:3000/login` 을 입력 후 이후 과정을 진행한다.
```
cd ./sample
npm install
node app
```
## mean.io 와 쉽게 연동하기
수정해야하는 파일들은 아래와 같다.
| file path | 설명 |
| -------------------------------- | ------------------------------ |
| server/config/env/development.js | 개발환경 설정파일 |
| server/config/env/production.js | 운영환경 설정파일 |
| server/config/models/user.js | 사용자 모델 |
| server/config/passport.js | passport script |
| server/routes/users.js | 사용자 로그인 관련 routes file |
| public/auth/views/index.html | 로그인 화면 |
(1) **mean.io app을 생성** 한다. (ex : mean init kakaoTest)
(2) 해당 모듈을 연동할 mean.io app에 설치한다.(npm install passport-kakao --save)
(3) **server/config/env/development.js****production.js** 에 kakao 관련 설정을 아래와 같이 추가한다.
```javascript
'use strict'
module.exports = {
db: 'mongodb',
app: {
name: 'passport-kakao',
},
// 그외 설정들....,
kakao: {
clientID: 'kakao app rest api key',
callbackURL: 'http://localhost:3000/oauth',
},
}
```
(4) **server/config/models/users.js** 의 사용자 스키마 정의에 **kakao: {}** 를 추가한다.
(5) **server/config/passport.js** 파일에 아래 구문을 추가한다.
```javascript
// 최상단 require되는 구문에 추가
var KakaoStrategy = require('passport-kakao').Strategy
passport.use(
new KakaoStrategy(
{
clientID: config.kakao.clientID,
callbackURL: config.kakao.callbackURL,
},
function(accessToken, refreshToken, profile, done) {
User.findOne(
{
'kakao.id': profile.id,
},
function(err, user) {
if (err) {
return done(err)
}
if (!user) {
user = new User({
name: profile.username,
username: profile.id,
roles: ['authenticated'],
provider: 'kakao',
kakao: profile._json,
})
user.save(function(err) {
if (err) {
console.log(err)
}
return done(err, user)
})
} else {
return done(err, user)
}
}
)
}
)
)
```
(6) **server/routes/users.js** 에 아래와 같은 구문을 추가한다.
```javascript
app.get(
'/auth/kakao',
passport.authenticate('kakao', {
failureRedirect: '#!/login',
}),
users.signin
)
app.get(
'/oauth',
passport.authenticate('kakao', {
failureRedirect: '#!/login',
}),
users.authCallback
)
```
(7) **public/auth/views/index.html** 에 kakao login을 연결한다.
```html
<!-- 아래는 예시 -->
<div>
<div class="row">
<div class="col-md-offset-1 col-md-5">
<a href="/auth/facebook">
<img src="/public/auth/assets/img/icons/facebook.png" />
</a>
<a href="/auth/twitter">
<img src="/public/auth/assets/img/icons/twitter.png" />
</a>
<!-- kakao login -->
<a href="/auth/kakao">
<img
src="https://developers.kakao.com/assets/img/about/logos/kakaolink/kakaolink_btn_medium.png"
/>
</a>
</div>
</div>
<div class="col-md-6">
<div ui-view></div>
</div>
</div>
```
(8) grunt로 mean.io app 실행 후, 실제 로그인 연동 테스트를 해본다.
## 기타
passport-oauth 모듈과 passport-facebook 모듈을 참고함.
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("util");
var passport_oauth2_1 = __importDefault(require("passport-oauth2"));
var DEFAULT_CLIENT_SECRET = 'kakao';
var OAUTH_HOST = 'https://kauth.kakao.com';
var USER_PROFILE_URL = 'https://kapi.kakao.com/v2/user/me';
exports.buildOptions = function (options) {
options.authorizationURL = OAUTH_HOST + "/oauth/authorize";
options.tokenURL = OAUTH_HOST + "/oauth/token";
if (!options.clientSecret) {
options.clientSecret = DEFAULT_CLIENT_SECRET;
}
options.scopeSeparator = options.scopeSeparator || ',';
options.customHeaders = options.customHeaders || {};
if (!options.customHeaders['User-Agent']) {
options.customHeaders['User-Agent'] = options.userAgent || 'passport-kakao';
}
return options;
};
/**
* KaKaoStrategy 생성자 함수.<br/>
* @param options.clientID 필수. kakao rest app key.
* @param options.callbackURL 필수. 로그인 처리 후 호출할 URL
* @param verify
* @constructor
*/
function Strategy(options, verify) {
if (options === void 0) { options = {}; }
passport_oauth2_1.default.call(this, exports.buildOptions(options), verify);
this.name = 'kakao';
this._userProfileURL = USER_PROFILE_URL;
}
/**
* `OAuth2Stragegy`를 상속 받는다.
*/
util_1.inherits(Strategy, passport_oauth2_1.default);
/**
* kakao 사용자 정보를 얻는다.<br/>
* 사용자 정보를 성공적으로 조회하면 아래의 object가 done 콜백함수 호출과 함꼐 넘어간다.
*
* - `provider` kakao 고정
* - `id` kakao user id number
* - `username` 사용자의 kakao nickname
* - `_raw` json string 원문
* _ `_json` json 원 데이터
*
* @param {String} accessToken
* @param {Function} done
*/
Strategy.prototype.userProfile = function (accessToken, done) {
this._oauth2.get(this._userProfileURL, accessToken, function (err, body) {
if (err) {
return done(err);
}
try {
var json = JSON.parse(body);
// 카카오톡이나 카카오스토리에 연동한 적이 없는 계정의 경우
// properties가 비어있다고 한다. 없을 경우의 처리
var properties = json.properties || {
nickname: '미연동 계정',
};
var profile = {
provider: 'kakao',
id: json.id,
username: properties.nickname,
displayName: properties.nickname,
_raw: body,
_json: json,
};
return done(null, profile);
}
catch (e) {
return done(e);
}
});
};
exports.default = Strategy;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Strategy_1 = __importDefault(require("./Strategy"));
exports.Strategy = Strategy_1.default;
exports.default = Strategy_1.default;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("util");
var passport_oauth2_1 = __importDefault(require("passport-oauth2"));
var DEFAULT_CLIENT_SECRET = 'kakao';
var OAUTH_HOST = 'https://kauth.kakao.com';
var USER_PROFILE_URL = 'https://kapi.kakao.com/v2/user/me';
exports.buildOptions = function (options) {
options.authorizationURL = OAUTH_HOST + "/oauth/authorize";
options.tokenURL = OAUTH_HOST + "/oauth/token";
if (!options.clientSecret) {
options.clientSecret = DEFAULT_CLIENT_SECRET;
}
options.scopeSeparator = options.scopeSeparator || ',';
options.customHeaders = options.customHeaders || {};
if (!options.customHeaders['User-Agent']) {
options.customHeaders['User-Agent'] = options.userAgent || 'passport-kakao';
}
return options;
};
/**
* KaKaoStrategy 생성자 함수.<br/>
* @param options.clientID 필수. kakao rest app key.
* @param options.callbackURL 필수. 로그인 처리 후 호출할 URL
* @param verify
* @constructor
*/
function Strategy(options, verify) {
if (options === void 0) { options = {}; }
passport_oauth2_1.default.call(this, exports.buildOptions(options), verify);
this.name = 'kakao';
this._userProfileURL = USER_PROFILE_URL;
}
/**
* `OAuth2Stragegy`를 상속 받는다.
*/
util_1.inherits(Strategy, passport_oauth2_1.default);
/**
* kakao 사용자 정보를 얻는다.<br/>
* 사용자 정보를 성공적으로 조회하면 아래의 object가 done 콜백함수 호출과 함꼐 넘어간다.
*
* - `provider` kakao 고정
* - `id` kakao user id number
* - `username` 사용자의 kakao nickname
* - `_raw` json string 원문
* _ `_json` json 원 데이터
*
* @param {String} accessToken
* @param {Function} done
*/
Strategy.prototype.userProfile = function (accessToken, done) {
this._oauth2.get(this._userProfileURL, accessToken, function (err, body) {
if (err) {
return done(err);
}
try {
var json = JSON.parse(body);
// 카카오톡이나 카카오스토리에 연동한 적이 없는 계정의 경우
// properties가 비어있다고 한다. 없을 경우의 처리
var properties = json.properties || {
nickname: '미연동 계정',
};
var profile = {
provider: 'kakao',
id: json.id,
username: properties.nickname,
displayName: properties.nickname,
_raw: body,
_json: json,
};
return done(null, profile);
}
catch (e) {
return done(e);
}
});
};
exports.default = Strategy;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Strategy_1 = __importDefault(require("./Strategy"));
exports.Strategy = Strategy_1.default;
exports.default = Strategy_1.default;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
describe('passport-kakao', function () {
it('passport-kakao 객체가 제대로 생성이 되어 있어야 한다.', function () {
var Strategy = require('../lib/passport-kakao');
expect(Strategy).not.toBeNull();
});
});
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var chai_1 = require("chai");
var Strategy_1 = __importStar(require("../src/Strategy"));
describe('passport-kakao', function () {
it('passport-kakao 객체가 제대로 생성이 되어 있어야 한다.', function () {
chai_1.expect(Strategy_1.default).to.not.equals(null);
});
it('Strategy option의 clientSecret 값이 없을 경우 default 값이 설정되어야 한다.', function () {
var options = Strategy_1.buildOptions({});
chai_1.expect(options).to.not.equals(null);
chai_1.expect(options.clientSecret).to.be.equals('kakao');
chai_1.expect(options.scopeSeparator).to.be.equals(',');
chai_1.expect(options.customHeaders['User-Agent']).to.be.equals('passport-kakao');
});
it('Strategy option의 User-Agent값이 있을 경우 customHeaders의 User-Agent가 해당 값으로 설정되어야 한다.', function () {
var options = Strategy_1.buildOptions({
customHeaders: {
'User-Agent': 'HELLO ROTO',
},
});
chai_1.expect(options.customHeaders['User-Agent']).to.be.equals('HELLO ROTO');
});
});
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
(The MIT License)
Copyright (c) 2011-2014 Jared Hanson
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# passport-oauth2
[![Build](https://travis-ci.org/jaredhanson/passport-oauth2.png)](https://travis-ci.org/jaredhanson/passport-oauth2)
[![Coverage](https://coveralls.io/repos/jaredhanson/passport-oauth2/badge.png)](https://coveralls.io/r/jaredhanson/passport-oauth2)
[![Quality](https://codeclimate.com/github/jaredhanson/passport-oauth2.png)](https://codeclimate.com/github/jaredhanson/passport-oauth2)
[![Dependencies](https://david-dm.org/jaredhanson/passport-oauth2.png)](https://david-dm.org/jaredhanson/passport-oauth2)
[![Tips](http://img.shields.io/gittip/jaredhanson.png)](https://www.gittip.com/jaredhanson/)
General-purpose OAuth 2.0 authentication strategy for [Passport](http://passportjs.org/).
This module lets you authenticate using OAuth 2.0 in your Node.js applications.
By plugging into Passport, OAuth 2.0 authentication can be easily and
unobtrusively integrated into any application or framework that supports
[Connect](http://www.senchalabs.org/connect/)-style middleware, including
[Express](http://expressjs.com/).
Note that this strategy provides generic OAuth 2.0 support. In many cases, a
provider-specific strategy can be used instead, which cuts down on unnecessary
configuration, and accommodates any provider-specific quirks. See the
[list](https://github.com/jaredhanson/passport/wiki/Strategies) for supported
providers.
Developers who need to implement authentication against an OAuth 2.0 provider
that is not already supported are encouraged to sub-class this strategy. If you
choose to open source the new provider-specific strategy, please add it to the
list so other people can find it.
## Install
$ npm install passport-oauth2
## Usage
#### Configure Strategy
The OAuth 2.0 authentication strategy authenticates users using a third-party
account and OAuth 2.0 tokens. The provider's OAuth 2.0 endpoints, as well as
the client identifer and secret, are specified as options. The strategy
requires a `verify` callback, which receives an access token and profile,
and calls `done` providing a user.
passport.use(new OAuth2Strategy({
authorizationURL: 'https://www.example.com/oauth2/authorize',
tokenURL: 'https://www.example.com/oauth2/token',
clientID: EXAMPLE_CLIENT_ID,
clientSecret: EXAMPLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/example/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ exampleId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
#### Authenticate Requests
Use `passport.authenticate()`, specifying the `'oauth2'` strategy, to
authenticate requests.
For example, as route middleware in an [Express](http://expressjs.com/)
application:
app.get('/auth/example',
passport.authenticate('oauth2'));
app.get('/auth/example/callback',
passport.authenticate('oauth2', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/');
});
## Related Modules
- [passport-oauth1](https://github.com/jaredhanson/passport-oauth1) — OAuth 1.0 authentication strategy
- [passport-http-bearer](https://github.com/jaredhanson/passport-http-bearer) — Bearer token authentication strategy for APIs
- [OAuth2orize](https://github.com/jaredhanson/oauth2orize) — OAuth 2.0 authorization server toolkit
## Tests
$ npm install
$ npm test
## Credits
- [Jared Hanson](http://github.com/jaredhanson)
## License
[The MIT License](http://opensource.org/licenses/MIT)
Copyright (c) 2011-2014 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)>
/**
* `AuthorizationError` error.
*
* AuthorizationError represents an error in response to an authorization
* request. For details, refer to RFC 6749, section 4.1.2.1.
*
* References:
* - [The OAuth 2.0 Authorization Framework](http://tools.ietf.org/html/rfc6749)
*
* @constructor
* @param {String} [message]
* @param {String} [code]
* @param {String} [uri]
* @param {Number} [status]
* @api public
*/
function AuthorizationError(message, code, uri, status) {
if (!status) {
switch (code) {
case 'access_denied': status = 403; break;
case 'server_error': status = 502; break;
case 'temporarily_unavailable': status = 503; break;
}
}
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'AuthorizationError';
this.message = message;
this.code = code || 'server_error';
this.uri = uri;
this.status = status || 500;
}
/**
* Inherit from `Error`.
*/
AuthorizationError.prototype.__proto__ = Error.prototype;
/**
* Expose `AuthorizationError`.
*/
module.exports = AuthorizationError;
/**
* `InternalOAuthError` error.
*
* InternalOAuthError wraps errors generated by node-oauth. By wrapping these
* objects, error messages can be formatted in a manner that aids in debugging
* OAuth issues.
*
* @constructor
* @param {String} [message]
* @param {Object|Error} [err]
* @api public
*/
function InternalOAuthError(message, err) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'InternalOAuthError';
this.message = message;
this.oauthError = err;
}
/**
* Inherit from `Error`.
*/
InternalOAuthError.prototype.__proto__ = Error.prototype;
/**
* Returns a string representing the error.
*
* @return {String}
* @api public
*/
InternalOAuthError.prototype.toString = function() {
var m = this.name;
if (this.message) { m += ': ' + this.message; }
if (this.oauthError) {
if (this.oauthError instanceof Error) {
m = this.oauthError.toString();
} else if (this.oauthError.statusCode && this.oauthError.data) {
m += ' (status: ' + this.oauthError.statusCode + ' data: ' + this.oauthError.data + ')';
}
}
return m;
};
/**
* Expose `InternalOAuthError`.
*/
module.exports = InternalOAuthError;
/**
* `TokenError` error.
*
* TokenError represents an error received from a token endpoint. For details,
* refer to RFC 6749, section 5.2.
*
* References:
* - [The OAuth 2.0 Authorization Framework](http://tools.ietf.org/html/rfc6749)
*
* @constructor
* @param {String} [message]
* @param {String} [code]
* @param {String} [uri]
* @param {Number} [status]
* @api public
*/
function TokenError(message, code, uri, status) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'TokenError';
this.message = message;
this.code = code || 'invalid_request';
this.uri = uri;
this.status = status || 500;
}
/**
* Inherit from `Error`.
*/
TokenError.prototype.__proto__ = Error.prototype;
/**
* Expose `TokenError`.
*/
module.exports = TokenError;
/**
* Module dependencies.
*/
var Strategy = require('./strategy')
, AuthorizationError = require('./errors/authorizationerror')
, TokenError = require('./errors/tokenerror')
, InternalOAuthError = require('./errors/internaloautherror');
/**
* Expose `Strategy` directly from package.
*/
exports = module.exports = Strategy;
/**
* Export constructors.
*/
exports.Strategy = Strategy;
/**
* Export errors.
*/
exports.AuthorizationError = AuthorizationError;
exports.TokenError = TokenError;
exports.InternalOAuthError = InternalOAuthError;
/**
* Reconstructs the original URL of the request.
*
* This function builds a URL that corresponds the original URL requested by the
* client, including the protocol (http or https) and host.
*
* If the request passed through any proxies that terminate SSL, the
* `X-Forwarded-Proto` header is used to detect if the request was encrypted to
* the proxy, assuming that the proxy has been flagged as trusted.
*
* @param {http.IncomingMessage} req
* @param {Object} [options]
* @return {String}
* @api private
*/
exports.originalURL = function(req, options) {
options = options || {};
var app = req.app;
if (app && app.get && app.get('trust proxy')) {
options.proxy = true;
}
var trustProxy = options.proxy;
var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
, tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
, host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host
, protocol = tls ? 'https' : 'http'
, path = req.url || '';
return protocol + '://' + host + path;
};
{
"_from": "passport-oauth2@~1.1.2",
"_id": "passport-oauth2@1.1.2",
"_inBundle": false,
"_integrity": "sha1-vXFjsbYJA3GGjcTvb58uHkzEuUg=",
"_location": "/passport-kakao/passport-oauth2",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "passport-oauth2@~1.1.2",
"name": "passport-oauth2",
"escapedName": "passport-oauth2",
"rawSpec": "~1.1.2",
"saveSpec": null,
"fetchSpec": "~1.1.2"
},
"_requiredBy": [
"/passport-kakao"
],
"_resolved": "https://registry.npmjs.org/passport-oauth2/-/passport-oauth2-1.1.2.tgz",
"_shasum": "bd7163b1b6090371868dc4ef6f9f2e1e4cc4b948",
"_spec": "passport-oauth2@~1.1.2",
"_where": "C:\\Users\\LG\\Desktop\\4-1\\Reminder-Talk\\node_modules\\passport-kakao",
"author": {
"name": "Jared Hanson",
"email": "jaredhanson@gmail.com",
"url": "http://www.jaredhanson.net/"
},
"bugs": {
"url": "http://github.com/jaredhanson/passport-oauth2/issues"
},
"bundleDependencies": false,
"dependencies": {
"oauth": "0.9.x",
"passport-strategy": "1.x.x",
"uid2": "0.0.x"
},
"deprecated": false,
"description": "OAuth 2.0 authentication strategy for Passport.",
"devDependencies": {
"chai": "1.x.x",
"chai-passport-strategy": "0.2.x",
"mocha": "1.x.x"
},
"engines": {
"node": ">= 0.4.0"
},
"homepage": "https://github.com/jaredhanson/passport-oauth2#readme",
"keywords": [
"passport",
"auth",
"authn",
"authentication",
"authz",
"authorization",
"oauth",
"oauth2"
],
"licenses": [
{
"type": "MIT",
"url": "http://www.opensource.org/licenses/MIT"
}
],
"main": "./lib",
"name": "passport-oauth2",
"repository": {
"type": "git",
"url": "git://github.com/jaredhanson/passport-oauth2.git"
},
"scripts": {
"test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js test/**/*.test.js"
},
"version": "1.1.2"
}
node_modules/
npm-debug.log
\ No newline at end of file
Copyright (c) 2010 Charlie Robbins.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\ No newline at end of file
# node-pkginfo
An easy way to expose properties on a module from a package.json
## Installation
### Installing npm (node package manager)
```
curl http://npmjs.org/install.sh | sh
```
### Installing pkginfo
```
[sudo] npm install pkginfo
```
## Motivation
How often when writing node.js modules have you written the following line(s) of code?
* Hard code your version string into your code
``` js
exports.version = '0.1.0';
```
* Programmatically expose the version from the package.json
``` js
exports.version = require('/path/to/package.json').version;
```
In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!**
## Usage
Using `pkginfo` is idiot-proof, just require and invoke it.
``` js
var pkginfo = require('pkginfo')(module);
console.dir(module.exports);
```
By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`).
Here's a sample of the output:
```
{ name: 'simple-app',
description: 'A test fixture for pkginfo',
version: '0.1.0',
author: 'Charlie Robbins <charlie.robbins@gmail.com>',
keywords: [ 'test', 'fixture' ],
main: './index.js',
scripts: { test: 'vows test/*-test.js --spec' },
engines: { node: '>= 0.4.0' } }
```
### Expose specific properties
If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function:
``` js
var pkginfo = require('pkginfo')(module, 'version', 'author');
console.dir(module.exports);
```
```
{ version: '0.1.0',
author: 'Charlie Robbins <charlie.robbins@gmail.com>' }
```
If you're looking for further usage see the [examples][0] included in this repository.
## Run Tests
Tests are written in [vows][1] and give complete coverage of all APIs.
```
vows test/*-test.js --spec
```
[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples
[1]: http://vowsjs.org
#### Author: [Charlie Robbins](http://nodejitsu.com)
#### License: MIT
/*--------------------- Layout and Typography ----------------------------*/
body {
font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif;
font-size: 15px;
line-height: 22px;
color: #252519;
margin: 0; padding: 0;
}
a {
color: #261a3b;
}
a:visited {
color: #261a3b;
}
p {
margin: 0 0 15px 0;
}
h4, h5, h6 {
color: #333;
margin: 6px 0 6px 0;
font-size: 13px;
}
h2, h3 {
margin-bottom: 0;
color: #000;
}
h1 {
margin-top: 40px;
margin-bottom: 15px;
color: #000;
}
#container {
position: relative;
}
#background {
position: fixed;
top: 0; left: 525px; right: 0; bottom: 0;
background: #f5f5ff;
border-left: 1px solid #e5e5ee;
z-index: -1;
}
#jump_to, #jump_page {
background: white;
-webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777;
-webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px;
font: 10px Arial;
text-transform: uppercase;
cursor: pointer;
text-align: right;
}
#jump_to, #jump_wrapper {
position: fixed;
right: 0; top: 0;
padding: 5px 10px;
}
#jump_wrapper {
padding: 0;
display: none;
}
#jump_to:hover #jump_wrapper {
display: block;
}
#jump_page {
padding: 5px 0 3px;
margin: 0 0 25px 25px;
}
#jump_page .source {
display: block;
padding: 5px 10px;
text-decoration: none;
border-top: 1px solid #eee;
}
#jump_page .source:hover {
background: #f5f5ff;
}
#jump_page .source:first-child {
}
table td {
border: 0;
outline: 0;
}
td.docs, th.docs {
max-width: 450px;
min-width: 450px;
min-height: 5px;
padding: 10px 25px 1px 50px;
overflow-x: hidden;
vertical-align: top;
text-align: left;
}
.docs pre {
margin: 15px 0 15px;
padding-left: 15px;
}
.docs p tt, .docs p code {
background: #f8f8ff;
border: 1px solid #dedede;
font-size: 12px;
padding: 0 0.2em;
}
.pilwrap {
position: relative;
}
.pilcrow {
font: 12px Arial;
text-decoration: none;
color: #454545;
position: absolute;
top: 3px; left: -20px;
padding: 1px 2px;
opacity: 0;
-webkit-transition: opacity 0.2s linear;
}
td.docs:hover .pilcrow {
opacity: 1;
}
td.code, th.code {
padding: 14px 15px 16px 25px;
width: 100%;
vertical-align: top;
background: #f5f5ff;
border-left: 1px solid #e5e5ee;
}
pre, tt, code {
font-size: 12px; line-height: 18px;
font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace;
margin: 0; padding: 0;
}
/*---------------------- Syntax Highlighting -----------------------------*/
td.linenos { background-color: #f0f0f0; padding-right: 10px; }
span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }
body .hll { background-color: #ffffcc }
body .c { color: #408080; font-style: italic } /* Comment */
body .err { border: 1px solid #FF0000 } /* Error */
body .k { color: #954121 } /* Keyword */
body .o { color: #666666 } /* Operator */
body .cm { color: #408080; font-style: italic } /* Comment.Multiline */
body .cp { color: #BC7A00 } /* Comment.Preproc */
body .c1 { color: #408080; font-style: italic } /* Comment.Single */
body .cs { color: #408080; font-style: italic } /* Comment.Special */
body .gd { color: #A00000 } /* Generic.Deleted */
body .ge { font-style: italic } /* Generic.Emph */
body .gr { color: #FF0000 } /* Generic.Error */
body .gh { color: #000080; font-weight: bold } /* Generic.Heading */
body .gi { color: #00A000 } /* Generic.Inserted */
body .go { color: #808080 } /* Generic.Output */
body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
body .gs { font-weight: bold } /* Generic.Strong */
body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
body .gt { color: #0040D0 } /* Generic.Traceback */
body .kc { color: #954121 } /* Keyword.Constant */
body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */
body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */
body .kp { color: #954121 } /* Keyword.Pseudo */
body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */
body .kt { color: #B00040 } /* Keyword.Type */
body .m { color: #666666 } /* Literal.Number */
body .s { color: #219161 } /* Literal.String */
body .na { color: #7D9029 } /* Name.Attribute */
body .nb { color: #954121 } /* Name.Builtin */
body .nc { color: #0000FF; font-weight: bold } /* Name.Class */
body .no { color: #880000 } /* Name.Constant */
body .nd { color: #AA22FF } /* Name.Decorator */
body .ni { color: #999999; font-weight: bold } /* Name.Entity */
body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
body .nf { color: #0000FF } /* Name.Function */
body .nl { color: #A0A000 } /* Name.Label */
body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
body .nt { color: #954121; font-weight: bold } /* Name.Tag */
body .nv { color: #19469D } /* Name.Variable */
body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
body .w { color: #bbbbbb } /* Text.Whitespace */
body .mf { color: #666666 } /* Literal.Number.Float */
body .mh { color: #666666 } /* Literal.Number.Hex */
body .mi { color: #666666 } /* Literal.Number.Integer */
body .mo { color: #666666 } /* Literal.Number.Oct */
body .sb { color: #219161 } /* Literal.String.Backtick */
body .sc { color: #219161 } /* Literal.String.Char */
body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */
body .s2 { color: #219161 } /* Literal.String.Double */
body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
body .sh { color: #219161 } /* Literal.String.Heredoc */
body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
body .sx { color: #954121 } /* Literal.String.Other */
body .sr { color: #BB6688 } /* Literal.String.Regex */
body .s1 { color: #219161 } /* Literal.String.Single */
body .ss { color: #19469D } /* Literal.String.Symbol */
body .bp { color: #954121 } /* Name.Builtin.Pseudo */
body .vc { color: #19469D } /* Name.Variable.Class */
body .vg { color: #19469D } /* Name.Variable.Global */
body .vi { color: #19469D } /* Name.Variable.Instance */
body .il { color: #666666 } /* Literal.Number.Integer.Long */
\ No newline at end of file
/*
* all-properties.js: Sample of including all properties from a package.json file
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
pkginfo = require('../lib/pkginfo')(module);
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports));
\ No newline at end of file
/*
* array-argument.js: Sample of including specific properties from a package.json file
* using Array argument syntax.
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
pkginfo = require('../lib/pkginfo')(module, ['version', 'author']);
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports));
\ No newline at end of file
/*
* multiple-properties.js: Sample of including multiple properties from a package.json file
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
pkginfo = require('../lib/pkginfo')(module, 'version', 'author');
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports));
\ No newline at end of file
/*
* object-argument.js: Sample of including specific properties from a package.json file
* using Object argument syntax.
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
pkginfo = require('../lib/pkginfo')(module, {
include: ['version', 'author']
});
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports));
\ No newline at end of file
{
"name": "simple-app",
"description": "A test fixture for pkginfo",
"version": "0.1.0",
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
"keywords": ["test", "fixture"],
"main": "./index.js",
"scripts": { "test": "vows test/*-test.js --spec" },
"engines": { "node": ">= 0.4.0" }
}
/*
* single-property.js: Sample of including a single specific properties from a package.json file
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
pkginfo = require('../lib/pkginfo')(module, 'version');
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports));
\ No newline at end of file
{
"name": "simple-app-subdir",
"description": "A test fixture for pkginfo",
"version": "0.1.0",
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
"keywords": ["test", "fixture"],
"main": "./index.js",
"scripts": { "test": "vows test/*-test.js --spec" },
"engines": { "node": ">= 0.4.0" },
"subdironly": "true"
}
/*
* multiple-properties.js: Sample of including multiple properties from a package.json file
*
* (C) 2011, Charlie Robbins
*
*/
var util = require('util'),
path = require('path'),
pkginfo = require('../lib/pkginfo')(module, { dir: path.resolve(__dirname, 'subdir' )});
exports.someFunction = function () {
console.log('some of your custom logic here');
};
console.log('Inspecting module:');
console.dir(module.exports);
console.log('\nAll exports exposed:');
console.error(Object.keys(module.exports));
\ No newline at end of file
/*
* pkginfo.js: Top-level include for the pkginfo module
*
* (C) 2011, Charlie Robbins
*
*/
var fs = require('fs'),
path = require('path');
//
// ### function pkginfo ([options, 'property', 'property' ..])
// #### @pmodule {Module} Parent module to read from.
// #### @options {Object|Array|string} **Optional** Options used when exposing properties.
// #### @arguments {string...} **Optional** Specified properties to expose.
// Exposes properties from the package.json file for the parent module on
// it's exports. Valid usage:
//
// `require('pkginfo')()`
//
// `require('pkginfo')('version', 'author');`
//
// `require('pkginfo')(['version', 'author']);`
//
// `require('pkginfo')({ include: ['version', 'author'] });`
//
var pkginfo = module.exports = function (pmodule, options) {
var args = [].slice.call(arguments, 2).filter(function (arg) {
return typeof arg === 'string';
});
//
// **Parse variable arguments**
//
if (Array.isArray(options)) {
//
// If the options passed in is an Array assume that
// it is the Array of properties to expose from the
// on the package.json file on the parent module.
//
options = { include: options };
}
else if (typeof options === 'string') {
//
// Otherwise if the first argument is a string, then
// assume that it is the first property to expose from
// the package.json file on the parent module.
//
options = { include: [options] };
}
//
// **Setup default options**
//
options = options || {};
// ensure that includes have been defined
options.include = options.include || [];
if (args.length > 0) {
//
// If additional string arguments have been passed in
// then add them to the properties to expose on the
// parent module.
//
options.include = options.include.concat(args);
}
var pkg = pkginfo.read(pmodule, options.dir).package;
Object.keys(pkg).forEach(function (key) {
if (options.include.length > 0 && !~options.include.indexOf(key)) {
return;
}
if (!pmodule.exports[key]) {
pmodule.exports[key] = pkg[key];
}
});
return pkginfo;
};
//
// ### function find (dir)
// #### @pmodule {Module} Parent module to read from.
// #### @dir {string} **Optional** Directory to start search from.
// Searches up the directory tree from `dir` until it finds a directory
// which contains a `package.json` file.
//
pkginfo.find = function (pmodule, dir) {
if (! dir) {
dir = path.dirname(pmodule.filename);
}
var files = fs.readdirSync(dir);
if (~files.indexOf('package.json')) {
return path.join(dir, 'package.json');
}
if (dir === '/') {
throw new Error('Could not find package.json up from: ' + dir);
}
else if (!dir || dir === '.') {
throw new Error('Cannot find package.json from unspecified directory');
}
return pkginfo.find(pmodule, path.dirname(dir));
};
//
// ### function read (pmodule, dir)
// #### @pmodule {Module} Parent module to read from.
// #### @dir {string} **Optional** Directory to start search from.
// Searches up the directory tree from `dir` until it finds a directory
// which contains a `package.json` file and returns the package information.
//
pkginfo.read = function (pmodule, dir) {
dir = pkginfo.find(pmodule, dir);
var data = fs.readFileSync(dir).toString();
return {
dir: dir,
package: JSON.parse(data)
};
};
//
// Call `pkginfo` on this module and expose version.
//
pkginfo(module, {
dir: __dirname,
include: ['version'],
target: pkginfo
});
\ No newline at end of file
{
"_from": "pkginfo@~0.3.0",
"_id": "pkginfo@0.3.1",
"_inBundle": false,
"_integrity": "sha1-Wyn2qB9wcXFC4J52W76rl7T4HiE=",
"_location": "/passport-kakao/pkginfo",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "pkginfo@~0.3.0",
"name": "pkginfo",
"escapedName": "pkginfo",
"rawSpec": "~0.3.0",
"saveSpec": null,
"fetchSpec": "~0.3.0"
},
"_requiredBy": [
"/passport-kakao"
],
"_resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz",
"_shasum": "5b29f6a81f70717142e09e765bbeab97b4f81e21",
"_spec": "pkginfo@~0.3.0",
"_where": "C:\\Users\\LG\\Desktop\\4-1\\Reminder-Talk\\node_modules\\passport-kakao",
"author": {
"name": "Charlie Robbins",
"email": "charlie.robbins@gmail.com"
},
"bugs": {
"url": "https://github.com/indexzero/node-pkginfo/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "An easy way to expose properties on a module from a package.json",
"devDependencies": {
"vows": "0.7.x"
},
"engines": {
"node": ">= 0.4.0"
},
"homepage": "https://github.com/indexzero/node-pkginfo#readme",
"keywords": [
"info",
"tools",
"package.json"
],
"license": "MIT",
"main": "./lib/pkginfo.js",
"name": "pkginfo",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/indexzero/node-pkginfo.git"
},
"scripts": {
"test": "vows test/*-test.js --spec"
},
"version": "0.3.1"
}
/*
* pkginfo-test.js: Tests for the pkginfo module.
*
* (C) 2011, Charlie Robbins
*
*/
var assert = require('assert'),
exec = require('child_process').exec,
fs = require('fs'),
path = require('path'),
vows = require('vows'),
pkginfo = require('../lib/pkginfo');
function assertProperties (source, target) {
assert.lengthOf(source, target.length + 1);
target.forEach(function (prop) {
assert.isTrue(!!~source.indexOf(prop));
});
}
function compareWithExample(targetPath) {
var examplePaths = ['package.json'];
if (targetPath) {
examplePaths.unshift(targetPath);
}
return function(exposed) {
var pkg = fs.readFileSync(path.join.apply(null, [__dirname, '..', 'examples'].concat(examplePaths))).toString(),
keys = Object.keys(JSON.parse(pkg));
assertProperties(exposed, keys);
};
}
function testExposes (options) {
return {
topic: function () {
exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback);
},
"should expose that property correctly": function (err, stdout, stderr) {
assert.isNull(err);
var exposed = stderr.match(/'(\w+)'/ig).map(function (p) {
return p.substring(1, p.length - 1);
});
return !options.assert
? assertProperties(exposed, options.properties)
: options.assert(exposed);
}
}
}
vows.describe('pkginfo').addBatch({
"When using the pkginfo module": {
"and passed a single `string` argument": testExposes({
script: 'single-property.js',
properties: ['version']
}),
"and passed multiple `string` arguments": testExposes({
script: 'multiple-properties.js',
properties: ['version', 'author']
}),
"and passed an `object` argument": testExposes({
script: 'object-argument.js',
properties: ['version', 'author']
}),
"and passed an `array` argument": testExposes({
script: 'array-argument.js',
properties: ['version', 'author']
}),
"and read from a specified directory": testExposes({
script: 'target-dir.js',
assert: compareWithExample('subdir')
}),
"and passed no arguments": testExposes({
script: 'all-properties.js',
assert: compareWithExample()
})
}
}).export(module);
{
"_from": "passport-kakao",
"_id": "passport-kakao@1.0.0",
"_inBundle": false,
"_integrity": "sha512-rOR3+8g1bev/p9ChZLDKQan9oBmSSA2hmb7yQKdBOsjyF1mijx7fgR05pTWPz3g5r0kHZ2Y44sT2Ys6wJQq0xQ==",
"_location": "/passport-kakao",
"_phantomChildren": {
"oauth": "0.9.15",
"passport-strategy": "1.0.0",
"uid2": "0.0.3"
},
"_requested": {
"type": "tag",
"registry": true,
"raw": "passport-kakao",
"name": "passport-kakao",
"escapedName": "passport-kakao",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/passport-kakao/-/passport-kakao-1.0.0.tgz",
"_shasum": "11924fb3a5c9f174e3d9a6b8c75d729066ef388d",
"_spec": "passport-kakao",
"_where": "C:\\Users\\LG\\Desktop\\4-1\\Reminder-Talk",
"author": {
"name": "rotoshine@gmail.com"
},
"bugs": {
"url": "https://github.com/rotoshine/passport-kakao/issues"
},
"bundleDependencies": false,
"dependencies": {
"passport-oauth2": "~1.1.2",
"pkginfo": "~0.3.0"
},
"deprecated": false,
"description": "kakao oauth2 login module",
"devDependencies": {
"@types/chai": "^4.2.3",
"@types/mocha": "^5.2.7",
"@types/node": "^12.7.11",
"chai": "^4.2.0",
"mocha": "^6.2.1",
"ts-node": "^8.4.1",
"tslint": "^5.20.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.6.3"
},
"homepage": "https://github.com/rotoshine/passport-kakao#readme",
"keywords": [
"passport",
"kakao",
"kakaotalk",
"oauth2"
],
"license": "MIT",
"main": "./dist/passport-kakao",
"name": "passport-kakao",
"repository": {
"type": "git",
"url": "git://github.com/rotoshine/passport-kakao.git"
},
"scripts": {
"build": "npx tsc",
"lint": "tslint --project .",
"test": "mocha -r node_modules/ts-node/register ./tests/**/*.spec.ts"
},
"version": "1.0.0"
}
This diff is collapsed. Click to expand it.
{
"name": "passport-kakao-sample",
"repository": {
"type": "git",
"url": "git://github.com/rotoshine/passport-kakao.git"
},
"dependencies": {
"passport": ">= 0.0.0",
"express": ">= 4.4.5"
}
}
const passport = require('passport')
const express = require('express')
const KakaoStrategy = require('../dist/passport-kakao.js').Strategy
const appKey = 'YOUR_APP_REST_API_KEY'
const appSecret = 'YOUR_APP_CLIENT_SECRET_KEY'
// passport 에 Kakao Oauth 추가
passport.use(
new KakaoStrategy(
{
clientID: appKey,
clientSecret: appSecret,
callbackURL: 'http://localhost:3000/oauth',
},
function(accessToken, refreshToken, params, profile, done) {
// authorization 에 성공했을때의 액션
console.log(`accessToken : ${accessToken}`)
console.log(`사용자 profile: ${JSON.stringify(profile._json)}`)
save(accessToken, refreshToken, profile)
return done(null, profile._json)
}
)
)
passport.serializeUser(function(user, done) {
done(null, user)
})
passport.deserializeUser(function(obj, done) {
done(null, obj)
})
// express 앱 설정
var app = express()
app.use(passport.initialize())
app.get('/login', passport.authenticate('kakao', { state: 'myStateValue' }))
app.get('/oauth', passport.authenticate('kakao'), function(req, res) {
// 로그인 시작시 state 값을 받을 수 있음
res.send('state :' + req.query.state)
})
app.listen(3000)
// 사용자 구현 부분
function save() {
//save 로직 구현
}
import { inherits } from 'util'
import OAuth2Strategy from 'passport-oauth2'
import { StrategyOptions, Profile } from './types/models'
const DEFAULT_CLIENT_SECRET = 'kakao'
const OAUTH_HOST = 'https://kauth.kakao.com'
const USER_PROFILE_URL = 'https://kapi.kakao.com/v2/user/me'
export const buildOptions = (options: StrategyOptions) => {
options.authorizationURL = `${OAUTH_HOST}/oauth/authorize`
options.tokenURL = `${OAUTH_HOST}/oauth/token`
if (!options.clientSecret) {
options.clientSecret = DEFAULT_CLIENT_SECRET
}
options.scopeSeparator = options.scopeSeparator || ','
options.customHeaders = options.customHeaders || {}
if (!options.customHeaders['User-Agent']) {
options.customHeaders['User-Agent'] = options.userAgent || 'passport-kakao'
}
return options
}
/**
* KaKaoStrategy 생성자 함수.<br/>
* @param options.clientID 필수. kakao rest app key.
* @param options.callbackURL 필수. 로그인 처리 후 호출할 URL
* @param verify
* @constructor
*/
function Strategy(options: StrategyOptions = {}, verify: any) {
OAuth2Strategy.call(this, buildOptions(options), verify)
this.name = 'kakao'
this._userProfileURL = USER_PROFILE_URL
}
/**
* `OAuth2Stragegy`를 상속 받는다.
*/
inherits(Strategy, OAuth2Strategy)
/**
* kakao 사용자 정보를 얻는다.<br/>
* 사용자 정보를 성공적으로 조회하면 아래의 object가 done 콜백함수 호출과 함꼐 넘어간다.
*
* - `provider` kakao 고정
* - `id` kakao user id number
* - `username` 사용자의 kakao nickname
* - `_raw` json string 원문
* _ `_json` json 원 데이터
*
* @param {String} accessToken
* @param {Function} done
*/
Strategy.prototype.userProfile = function(
accessToken: string,
done: (error: Error, profile?: Profile) => void
) {
this._oauth2.get(
this._userProfileURL,
accessToken,
(err: Error, body: string) => {
if (err) {
return done(err)
}
try {
const json = JSON.parse(body)
// 카카오톡이나 카카오스토리에 연동한 적이 없는 계정의 경우
// properties가 비어있다고 한다. 없을 경우의 처리
const properties = json.properties || {
nickname: '미연동 계정',
}
const profile: Profile = {
provider: 'kakao',
id: json.id,
username: properties.nickname,
displayName: properties.nickname,
_raw: body,
_json: json,
}
return done(null, profile)
} catch (e) {
return done(e)
}
}
)
}
export default Strategy
import Strategy from './Strategy'
export default Strategy
export { Strategy }
export interface StrategyOptions {
authorizationURL?: string
tokenURL?: string
clientSecret?: string
scopeSeparator?: string
customHeaders?: {
'User-Agent'?: string
}
userAgent?: string
}
export interface Profile {
provider: 'kakao'
id?: string | number
username?: string
displayName?: string
_raw: string
_json: string
}
import { expect } from 'chai'
import KakaoStrategy, { buildOptions } from '../src/Strategy'
describe('passport-kakao', () => {
it('passport-kakao 객체가 제대로 생성이 되어 있어야 한다.', () => {
expect(KakaoStrategy).to.not.equals(null)
})
it('Strategy option의 clientSecret 값이 없을 경우 default 값이 설정되어야 한다.', () => {
const options = buildOptions({})
expect(options).to.not.equals(null)
expect(options.clientSecret).to.be.equals('kakao')
expect(options.scopeSeparator).to.be.equals(',')
expect(options.customHeaders['User-Agent']).to.be.equals('passport-kakao')
})
it('Strategy option의 User-Agent값이 있을 경우 customHeaders의 User-Agent가 해당 값으로 설정되어야 한다.', () => {
const options = buildOptions({
customHeaders: {
'User-Agent': 'HELLO ROTO',
},
})
expect(options.customHeaders['User-Agent']).to.be.equals('HELLO ROTO')
})
})
{
"include": ["./src"],
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": false /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
{
"defaultSeverity": "error",
"extends": ["tslint:latest", "tslint-config-prettier"],
"jsRules": {},
"rules": {
"interface-name": false,
"semicolon": [true, "never"],
"member-access": [false],
"ordered-imports": [false],
"object-literal-sort-keys": [false],
"no-console": [false],
"quotemark": [true, "single", "jsx-double"],
"jsx-no-lambda": [false],
"no-submodule-imports": [false],
"jsx-boolean-value": [false],
"no-implicit-dependencies": [true, "dev"],
"no-empty-interface": [false],
"no-var-requires": [false]
},
"rulesDirectory": []
}
......@@ -1180,6 +1180,32 @@
"passport-oauth2": "1.x.x"
}
},
"passport-kakao": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/passport-kakao/-/passport-kakao-1.0.0.tgz",
"integrity": "sha512-rOR3+8g1bev/p9ChZLDKQan9oBmSSA2hmb7yQKdBOsjyF1mijx7fgR05pTWPz3g5r0kHZ2Y44sT2Ys6wJQq0xQ==",
"requires": {
"passport-oauth2": "~1.1.2",
"pkginfo": "~0.3.0"
},
"dependencies": {
"passport-oauth2": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/passport-oauth2/-/passport-oauth2-1.1.2.tgz",
"integrity": "sha1-vXFjsbYJA3GGjcTvb58uHkzEuUg=",
"requires": {
"oauth": "0.9.x",
"passport-strategy": "1.x.x",
"uid2": "0.0.x"
}
},
"pkginfo": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz",
"integrity": "sha1-Wyn2qB9wcXFC4J52W76rl7T4HiE="
}
}
},
"passport-oauth": {
"version": "0.1.15",
"resolved": "https://registry.npmjs.org/passport-oauth/-/passport-oauth-0.1.15.tgz",
......
......@@ -25,6 +25,7 @@
"needle": "^2.4.0",
"passport": "^0.4.0",
"passport-google-oauth": "^2.0.0",
"passport-google-oauth20": "^1.0.0"
"passport-google-oauth20": "^1.0.0",
"passport-kakao": "^1.0.0"
}
}
......
var express = require('express');
var router = express.Router();
var gcal = require('google-calendar');
var accessToken;
var id;
var accessToken;
var id;
router.get('/', function(req, res, next) {
console.log(accessToken);
......@@ -88,7 +88,6 @@ var timestamp = function (date) {
+ ":" + pad(Math.abs(offset) % 60, 2);
}
module.exports = router;
//timestamp(new Date(1983, 4, 9, 11, 5, 17));
\ No newline at end of file
......
......@@ -4,14 +4,15 @@ const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const bodyParser = require('body-parser');
const KakaoStrategy = require("passport-kakao").Strategy;
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var gcal = require('google-calendar');
passport.use(new GoogleStrategy({
clientID:'978869138601-u3euf0c04sbdor68r30m599gilvjn91e.apps.googleusercontent.com',
clientSecret:'N7Uh_oVQZt-almzA4DkM4bm_',
clientID:CLIENTID,
clientSecret:CLIENTSECRET,
callbackURL:'http://localhost:3000/auth/google/callback',
scope:['openid','email','https://www.googleapis.com/auth/calendar.readonly',
'https://www.googleapis.com/auth/calendar',
......@@ -30,6 +31,27 @@ router.get('/auth/google/callback',passport.authenticate('google',{
res.redirect('/calendar');
});
const kakaoKey = {
clientID: KAKAO_API_KEY,
callbackURL: "/oauth/callback"
};
passport.use(
"kakao-login",
new KakaoStrategy(kakaoKey, (accessToken, refreshToken, profile, done) => {
console.log(profile);
return done(null,profile);
})
);
router.get("/kakao", passport.authenticate("kakao-login"));
router.get(
"/oauth/callback",
passport.authenticate("kakao-login",{failureRedirect:'/'}),function(req, res) {
req.session.access_token = req.user.accessToken;
res.redirect('/');
});
calList = new Array();
Calendars = new Array();
......
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
console.log("accepted");
});
module.exports = router;
......@@ -11,5 +11,7 @@
<form action='/auth/google' method='GET'>
<input type="submit" name='submit' value='로그인'/>
</form>
<form action='/kakao' method='GET'>
<input type="submit" name='submit' value='로그인'/>
</body>
</html>
\ No newline at end of file
......