1
1
const request = require ( 'r2' ) ;
2
+ const uuid = require ( 'node-uuid' ) ;
3
+ const jwt = require ( 'jsonwebtoken' ) ;
2
4
const config = require ( './config' ) ;
3
5
4
6
const constructPayload = require ( './lib/construct-payload' ) ;
7
+ const getReadmeData = require ( './lib/get-readme-data' ) ;
5
8
6
9
// We're doing this to buffer up the response body
7
10
// so we can send it off to the metrics server
@@ -27,7 +30,7 @@ function patchResponse(res) {
27
30
} ;
28
31
}
29
32
30
- module . exports = ( apiKey , group , options = { } ) => {
33
+ module . exports . metrics = ( apiKey , group , options = { } ) => {
31
34
if ( ! apiKey ) throw new Error ( 'You must provide your ReadMe API key' ) ;
32
35
if ( ! group ) throw new Error ( 'You must provide a grouping function' ) ;
33
36
@@ -72,3 +75,43 @@ module.exports = (apiKey, group, options = {}) => {
72
75
return next ( ) ;
73
76
} ;
74
77
} ;
78
+
79
+ module . exports . login = ( apiKey , userFnc , options = { } ) => {
80
+ if ( ! apiKey ) throw new Error ( 'You must provide your ReadMe API key' ) ;
81
+ if ( ! userFnc ) throw new Error ( 'You must provide a function to get the user' ) ;
82
+ return async ( req , res ) => {
83
+ let u ;
84
+ try {
85
+ u = userFnc ( req ) ;
86
+ } catch ( e ) {
87
+ // User isn't logged in
88
+ }
89
+
90
+ if ( ! u ) {
91
+ const fullUrl = `${ req . protocol } ://${ req . get ( 'host' ) } ${ req . originalUrl } ` ;
92
+ return res . redirect ( `${ options . loginUrl } ?redirect=${ encodeURIComponent ( fullUrl ) } ` ) ;
93
+ }
94
+
95
+ const jwtUrl = await module . exports . magicLink ( apiKey , u , req . query . redirect ) ;
96
+ return res . redirect ( jwtUrl ) ;
97
+ } ;
98
+ } ;
99
+
100
+ module . exports . magicLink = async ( apiKey , user , redirectPath = '' ) => {
101
+ if ( ! apiKey ) throw new Error ( 'You must provide your ReadMe API key' ) ;
102
+ if ( ! user ) throw new Error ( 'You must provide a user object' ) ;
103
+
104
+ const readmeData = await getReadmeData ( apiKey ) ;
105
+ let baseUrl = redirectPath ;
106
+
107
+ if ( ! redirectPath . startsWith ( 'http' ) ) {
108
+ baseUrl = `${ readmeData . baseUrl } ${ redirectPath } ` ;
109
+ }
110
+
111
+ const jwtOptions = {
112
+ jwtid : uuid . v4 ( ) ,
113
+ } ;
114
+
115
+ const token = jwt . sign ( user , readmeData . jwtSecret , jwtOptions ) ;
116
+ return `${ baseUrl } ?auth_token=${ token } ` ;
117
+ } ;
0 commit comments