1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2016 Alexandre Terrasa <alexandre@moz-code.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Authentification handlers.
19 # For now, only Github OAuth is provided.
21 # See https://developer.github.com/v3/oauth/.
23 # This module provide 4 base classes that can be used together to implement a
24 # Github OAuth handshake.
26 # Here an example of application using the Github Auth as login mechanism.
28 # There is 4 available routes:
29 # * `/login`: redirects the user to the Github OAuth login page (see `GithubLogin`)
30 # * `/profile`: shows the currently logged in user (see `Profile Handler`)
31 # * `/logout`: logs out the user by destroying the entry from the session (see `GithubLogout`)
32 # * `/oauth`: callback url for Github service after player login (see `GithubOAuthCallBack`)
34 # Routes redirection are handled at the OAuth service registration. Please see
35 # https://developer.github.com/v3/oauth/#redirect-urls for more niformation on how
36 # to configure your service to provide smouth redirections beween your routes.
40 # import popcorn::pop_auth
42 # class ProfileHandler
45 # redef fun get(req, res) do
46 # var session = req.session
47 # if session == null then
48 # res.send "No session :("
51 # var user = session.user
52 # if user == null then
53 # res.send "Not logged in"
56 # res.send "<h1>Hello {user.login}</h1>"
60 # var client_id = "github client id"
61 # var client_secret = "github client secret"
64 # app.use("/*", new SessionInit)
65 # app.use("/login", new GithubLogin(client_id))
66 # app.use("/oauth", new GithubOAuthCallBack(client_id, client_secret))
67 # app.use("/logout", new GithubLogout)
68 # app.use("/profile", new ProfileHandler)
69 # app.listen("localhost", 3000)
72 # Optionaly, you can use the `GithubUser` handler to provide access to the
73 # Github user stored in session:
76 # app.use("/api/user", new GithubUser)
84 # Github OAuth login handler.
86 # See https://developer.github.com/v3/oauth/.
90 # Client ID delivered by GitHub for your application.
92 # See https://github.com/settings/applications/new.
93 var client_id
: String is writable
95 # The URL in your application where users will be sent after authorization.
97 # If `null`, the URL used in application registration will be used.
99 # See https://developer.github.com/v3/oauth/#redirect-urls.
100 var redirect_uri
: nullable String = null is writable
102 # A space delimited list of scopes.
104 # See https://developer.github.com/v3/oauth/#scopes.
105 var scope
: nullable String = null is writable
107 # An optional and unguessable random string.
109 # It is used to protect against cross-site request forgery attacks.
110 var state
: nullable String = null is writable
112 # Allow signup at login.
114 # Whether or not unauthenticated users will be offered an option to sign up
115 # for GitHub during the OAuth flow. The default is true.
117 # Use false in the case that a policy prohibits signups.
118 var allow_signup
= true is writable
120 # Github OAuth login URL.
121 var auth_url
= "https://github.com/login/oauth/authorize" is writable
123 # Build Github URL to OAuth service.
124 fun build_auth_redirect
: String do
125 var url
= "{auth_url}?client_id={client_id}&allow_signup={allow_signup}"
126 var redirect_uri
= self.redirect_uri
127 if redirect_uri
!= null then url
= "{url}&redirect_uri={redirect_uri}"
128 var scope
= self.scope
129 if scope
!= null then url
= "{url}&scope={scope}"
130 var state
= self.state
131 if state
!= null then url
= "{url}&state={state}"
135 redef fun get
(req
, res
) do res
.redirect build_auth_redirect
138 # Get the authentification code and translate it to an access token.
139 class GithubOAuthCallBack
142 # The client ID delivered by GitHub for your application.
144 # See https://github.com/settings/applications/new.
145 var client_id
: String is writable
147 # The client secret you received from Github when your registered your application.
148 var client_secret
: String is writable
150 # The URL in your application where users will be sent after authorization.
152 # If `null`, the URL used in application registration will be used.
154 # See https://developer.github.com/v3/oauth/#redirect-urls.
155 var redirect_uri
: nullable String is writable
157 # An optional and unguessable random string.
159 # It is used to protect against cross-site request forgery attacks.
160 var state
: nullable String is writable
162 # Github OAuth token URL.
163 var token_url
= "https://github.com/login/oauth/access_token" is writable
165 # Header map sent with the OAuth token request.
166 var headers
: HeaderMap do
167 var map
= new HeaderMap
168 map
["Accept"] = "application/json"
172 # Build the OAuth post data.
173 fun build_auth_body
(code
: String): HeaderMap do
174 var map
= new HeaderMap
175 map
["client_id"] = client_id
176 map
["client_secret"] = client_secret
178 var redirect_uri
= self.redirect_uri
179 if redirect_uri
!= null then map
["redirect_uri"] = redirect_uri
180 var state
= self.state
181 if state
!= null then map
["state"] = state
185 redef fun get
(req
, res
) do
187 var code
= req
.string_arg
("code")
193 # Exchange it for an access token
194 var access_token
= request_access_token
(code
)
195 if access_token
== null then
201 var gh_api
= new GithubAPI(access_token
)
202 var user
= gh_api
.load_auth_user
207 # Set session and redirect to user page
208 var session
= req
.session
209 if session
== null then
214 res
.redirect redirect_uri
or else "/"
217 # Request an access token from an access `code`.
218 private fun request_access_token
(code
: String): nullable String do
219 var request
= new CurlHTTPRequest(token_url
)
220 request
.headers
= headers
221 request
.data
= build_auth_body
(code
)
222 var response
= request
.execute
223 return parse_token_response
(response
)
226 # Parse the Github access_token response and extract the access_token.
227 private fun parse_token_response
(response
: CurlResponse): nullable String do
228 if response
isa CurlResponseFailed then
229 print
"Request to Github OAuth failed"
230 print
"Requested URI: {token_url}"
231 print
"Error code: {response.error_code}"
232 print
"Error msg: {response.error_msg}"
234 else if response
isa CurlResponseSuccess then
235 var obj
= response
.body_str
.parse_json
236 if not obj
isa JsonObject then
237 print
"Error: Cannot parse json response"
238 print response
.body_str
241 var access_token
= obj
.get_or_null
("access_token")
242 if not access_token
isa String then
243 print
"Error: No `access_token` key in response"
253 # Destroy user session and redirect to homepage.
257 # The URL in your application where users will be sent after logout.
259 # If `null`, the root uri `/` will be used.
260 var redirect_uri
: nullable String is writable
262 redef fun get
(req
, res
) do
263 var session
= req
.session
264 if session
!= null then
267 res
.redirect redirect_uri
or else "/"
271 # AuthHandler allows access to session user
273 # Inherit this handler to access to session user from your custom handler.
275 # For example, you need a profile handler that checks if the user is logged
276 # before returning it in json format.
278 # import popcorn::pop_auth
280 # class ProfileHandler
283 # redef fun get(req, res) do
284 # var user = check_session_user(req, res)
285 # if user == null then return
291 # By using `check_session_user`, we delegate to the `AuthHandler` the responsability
292 # to set the HTTP 403 error.
293 # We then check is the user is not null before pursuing.
294 abstract class AuthHandler
297 # Returns `user` from `req.session` or null if no user is authenticated.
298 fun session_user
(req
: HttpRequest): nullable User do
299 var session
= req
.session
300 if session
== null then return null
301 var user
= session
.user
305 # Check the session for user and return it.
307 # If no `user` can be found in session, set res as a HTTP 403 error and return `null`.
308 fun check_session_user
(req
: HttpRequest, res
: HttpResponse): nullable User do
309 var user
= session_user
(req
)
317 # Get the currently logged in user from session.
321 redef fun get
(req
, res
) do
322 var user
= check_session_user
(req
, res
)
323 if user
== null then return
330 # Github user if logged in.
331 var user
: nullable User = null is writable