]>
git.r.bdr.sh - rbdr/dasein/blob - lib/handlers/auth.js
3 const Co
= require('co');
4 const JsonWebToken
= require('jsonwebtoken');
5 const Pify
= require('pify');
6 const TwitterHelper
= require('../twitter_helper');
10 internals
.kRedirectUrl
= 'https://api.twitter.com/oauth/authenticate?oauth_token=';
11 internals
.kLoginRedirect
= '/login';
13 internals
.signJsonWebToken
= Pify(JsonWebToken
.sign
);
16 * Handles the HTTP requests for auth related operations.
19 * @param {Dasein.tConfiguration} config The configuration to
22 module
.exports
= internals
.AuthHandler
= class AuthHandler
{
26 this._twitterHelper
= new TwitterHelper(config
.twitter
);
27 this._jwtConfig
= config
.jwt
;
31 * Triggers the twitter login flow. Redirects to twitter's oauth
35 * @memberof AuthHandler
37 * @return {generator} a koa compatible handler generator function
41 const twitterHelper
= this._twitterHelper
;
43 return function *handleLogin() {
45 const requestToken
= yield twitterHelper
.getRequestToken();
46 const loginUrl
= `${internals.kRedirectUrl}${requestToken.oAuthToken}`;
48 this.body
= { loginUrl
};
53 * Handles twitter's callback. Fetches the oAuth Verifier, attempts to
54 * obtain a user object and responds with the JWT
57 * @memberof AuthHandler
59 * @return {generator} a koa compatible handler generator function
65 return function *handleCallback() {
67 if (this.request
.query
.denied
) {
68 return this.throw(401);
71 const oAuthToken
= this.request
.body
.oAuthToken
;
72 const oAuthVerifier
= this.request
.body
.oAuthVerifier
;
76 const accessToken
= yield self
._twitterHelper
.getAccessToken(oAuthToken
, oAuthVerifier
);
77 user
= yield self
._twitterHelper
.getUser(accessToken
.oAuthAccessToken
, accessToken
.oAuthAccessTokenSecret
);
80 console
.error(err
.stack
|| err
.message
|| err
);
81 return this.throw(401);
84 const expiresAt
= Date
.now() + self
._jwtConfig
.duration
* 1000;
86 const token
= yield self
._getToken(user
);
98 // Generates a JSON Web Token
104 return Co(function * () {
106 const token
= yield internals
.signJsonWebToken(payload
, self
._jwtConfig
.secret
, {
107 expiresIn: self
._jwtConfig
.duration