-
-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
--------- | ||
-- Proxy script for OAuth 2.0. | ||
|
||
local config = require 'ngx-oauth.config' | ||
local Cookies = require 'ngx-oauth.Cookies' | ||
local ethr = require 'ngx-oauth.either' | ||
local nginx = require 'ngx-oauth.nginx' | ||
local oauth = require 'ngx-oauth.oauth2' | ||
|
||
local either = ethr.either | ||
|
||
local function write_auth_header (access_token) | ||
ngx.req.set_header('Authorization', 'Bearer '..access_token) | ||
end | ||
|
||
|
||
local conf, errs = config.load() | ||
if errs then | ||
return nginx.fail(500, 'OAuth proxy error: %s', errs) | ||
end | ||
|
||
local cookies = Cookies(conf) | ||
local access_token = cookies.get_access_token() | ||
|
||
-- Cookie with access token found; set Authorization header and we're done. | ||
if access_token then | ||
write_auth_header(access_token) | ||
|
||
-- Cookie with refresh token found; refresh token and set Authorization header. | ||
elseif cookies.get_refresh_token() then | ||
nginx.log(ngx.INFO, 'refreshing token for user: %s', cookies.get_username()) | ||
|
||
either ( | ||
function(err) | ||
nginx.fail(503, 'Authorization server error: %s', err) | ||
end, | ||
function(token) | ||
cookies.add_token(token) | ||
write_auth_header(token.access_token) | ||
end, | ||
oauth.request_token('refresh_token', conf, cookies.get_refresh_token()) | ||
) | ||
|
||
-- Neither access token nor refresh token found; bad luck, return HTTP 401. | ||
else | ||
nginx.fail(401, 'No access token found.') | ||
end |