|
| 1 | +local http = require("resty.http") |
| 2 | +local httpc = http.new() |
| 3 | +local cjson = require("cjson") |
| 4 | + |
| 5 | + |
| 6 | +local function get_access_token() |
| 7 | + local endpoint = "https://" .. ngx.var.auth0_tenant_domain .. "/oauth/token" |
| 8 | + local headers = { |
| 9 | + ["Content-Type"] = "application/x-www-form-urlencoded" |
| 10 | + } |
| 11 | + |
| 12 | + local body = { |
| 13 | + client_id = ngx.var.auth0_client_id, |
| 14 | + client_secret = ngx.var.auth0_client_secret, |
| 15 | + audience = "https://" .. ngx.var.auth0_tenant_domain .. "/api/v2/", |
| 16 | + grant_type = "client_credentials" |
| 17 | + } |
| 18 | + |
| 19 | + local res, err = httpc:request_uri(endpoint, { |
| 20 | + method = "POST", |
| 21 | + body = ngx.encode_args(body), |
| 22 | + headers = headers, |
| 23 | + }) |
| 24 | + ngx.log(ngx.NOTICE, ngx.var.auth0_tenant_domain) |
| 25 | + if not res then |
| 26 | + ngx.log(ngx.NOTICE, err) |
| 27 | + return false, nil, err |
| 28 | + else |
| 29 | + return true, cjson.decode(res.body).access_token, nil |
| 30 | + end |
| 31 | +end |
| 32 | + |
| 33 | +local function get_user_info(access_token) |
| 34 | + local user_endpoint = "https://" .. ngx.var.auth0_tenant_domain .. "/api/v2/users" |
| 35 | + local user_info_headers = { |
| 36 | + ["Content-Type"] = "application/json", |
| 37 | + ["Authorization"] = "Bearer " .. access_token |
| 38 | + } |
| 39 | + |
| 40 | + local search_params = { |
| 41 | + q = "nickname: " .. ngx.var.username, |
| 42 | + search_engine = "v2" |
| 43 | + } |
| 44 | + |
| 45 | + local user_res, err = httpc:request_uri(user_endpoint, { |
| 46 | + method = "GET", |
| 47 | + query = search_params, |
| 48 | + headers = user_info_headers, |
| 49 | + }) |
| 50 | + |
| 51 | + local found_user = cjson.decode(user_res.body)[1] |
| 52 | + if not found_user then |
| 53 | + return '{"error": 404, "message": "Not found"}' |
| 54 | + else |
| 55 | + return cjson.encode(found_user) |
| 56 | + end |
| 57 | +end |
| 58 | + |
| 59 | +-- Main entry |
| 60 | +local succeeded, access_token, err = get_access_token() |
| 61 | + |
| 62 | +if succeeded then |
| 63 | + ngx.say(get_user_info(access_token)) |
| 64 | +else |
| 65 | + ngx.status = 400 |
| 66 | + ngx.say(err) |
| 67 | +end |
0 commit comments