auth.lua

Verified
Added by iNTERFACEWARE

A module that does basic authentication for incoming web requests

Source Code
function string.___split(Input,sep)
   local fields = {}
   local pattern = string.format("([^%s]*%s?)", sep,sep)
   for match in Input:gmatch(pattern) do
      local lastchar = match:sub(-1)
      if (lastchar == sep) then 
         fields[#fields+1] = match:sub(0,-2)
      elseif (#lastchar > 0) then
         fields[#fields+1] = match
      end
   end
   --This part handles the case where if a delimiter
   --ends a string, it should be considered a new entry
   --e.g. 123| should be 2 fields: ['123','']
   if Input:sub(-1) == sep then
      fields[#fields+1] = ''
   end
   return fields
end

--------------------------
-- local module functions
--------------------------

local function ExtractPassword(R)
   if R.headers.Authorization == nil then
      return nil, nil
   end
   local P = filter.base64.dec(
      R.headers.Authorization:split(" ")[2])
   R = P:split(':')
   return R[1], R[2]
end

local Body = [[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<HTML>
  <HEAD>
    <TITLE>Error</TITLE>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
  </HEAD>
  <BODY><H1>401 Unauthorized.</H1></BODY>
</HTML>]]

local function RequirePassword(R)
   net.http.respond{code=401, body=Body, 
   headers={['WWW-Authenticate']='Basic realm="Secure Webservice"'}}
end

--------------------
-- Module Interface
--------------------

local auth = {}

function auth.BasicAuthentication(R)
   local User, Password = ExtractPassword(R)
   if User ~= 'admin' or Password ~= 'password' then
      RequirePassword(R)
      return false
   else
      return true
   end
end

return auth
Description
A module that does basic authentication for incoming web requests
Usage Details

This module performs basic authentication for incoming HTTP web requests.

How to use auth.lua:

  • Add it to your shared modules in a From HTTP component
  • Use  local auth = require 'auth' at the top of your script
  • Parse the incoming HTTP request using net.http.parseRequest{}
  • Use the auth.BasicAuthentication() function to authenticate

Note: For more information see Using basic authentication and Patient Demographics that both use this module.