-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathGithubContext.js
More file actions
111 lines (93 loc) · 2.66 KB
/
GithubContext.js
File metadata and controls
111 lines (93 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import request from 'axios'
import NextGlobalClientStore from '../modules/NextGlobalClientStore'
const GITHUB_API_URL = process.env.GITHUB_API_URL || 'https://api.github.com'
const getGithubAccessToken = req => {
if (process.browser) {
return NextGlobalClientStore.get('githubAccessToken')
} else {
const accessTokenCookie = req.headers.cookie && req.headers.cookie
.split(';')
.map(c => c.trim())
.find(c => c.startsWith('githubAccessToken='))
if (accessTokenCookie) {
return accessTokenCookie.split('=').pop()
}
}
}
const getGithubUser = async githubAccessToken => {
if (!githubAccessToken) {
return
}
if (process.browser) {
return NextGlobalClientStore.get('githubUser')
}
const url = `${GITHUB_API_URL}/user`
const headers = { Authorization: `token ${githubAccessToken}` }
const options = { headers }
let result
try {
result = await request.get(url, options)
} catch (error) {
// If there's an invalid token here ignore and allow the user to
// go through normal auth flow
if (error.response.status !== 401) {
throw error
}
}
if (result) {
return result.data
}
}
const GithubContext = Page => {
return class GithubContextWrapper extends Component {
static propTypes = {
github: PropTypes.shape({
user: PropTypes.shape({
login: PropTypes.string.isRequired
}),
accessToken: PropTypes.string
})
}
static async getInitialProps (pageContext) {
const { req } = pageContext
const accessToken = getGithubAccessToken(req)
const user = await getGithubUser(accessToken)
const github = { accessToken, user }
const pageProps = Page.getInitialProps
? await Page.getInitialProps({ ...pageContext, github })
: {}
return { ...pageProps, github }
}
static childContextTypes = {
github: PropTypes.shape({
user: PropTypes.shape({
login: PropTypes.string
}),
accessToken: PropTypes.string,
clientId: PropTypes.string
})
}
getChildContext () {
const { github, env: { githubClientId } = {} } = this.props
return {
github: {
...github,
clientId: githubClientId
}
}
}
constructor (props) {
super(props)
if (process.browser) {
NextGlobalClientStore.set('githubUser', props.github.user)
NextGlobalClientStore.set('githubAccessToken', props.github.accessToken)
}
}
render () {
return <Page {...this.props} />
}
}
}
export default GithubContext