Function Oiwizard_API(@API)
/***********************************************************************************************************************

    This program is proprietary and is not to be used by or disclosed to others, nor is it to be copied without written
    permission from SRP Computer Solutions, Inc.

    Name        :   Oiwizard_API

    Description :   API logic for the Oiwizard resource.

    Notes       :   All web APIs should include the API_SETUP insert. This will provide several useful variables:

                        HTTPMethod              - The HTTP Method (Verb) submitted by the client (e.g., GET, POST, etc.)
                        APIURL                  - The URL for the API entry point (e.g., api.mysite.com/v1).
                        FullEndpointURL         - The URL submitted by the client, including query params.
                        FullEndpointURLNoQuery  - The URL submitted by the client, excluding query params.
                        EndpointSegment         - The URL endpoint segment.
                        ParentURL               - The URL path preceeding the current endpoint.
                        CurrentAPI              - The name of this stored procedure.

    Parameters  :
        API             [in] -- Web API to process. Format is [APIPattern].[HTTPMethod]:
                                    - APIPattern must follow this structure Oiwizard[.ID.[<Property>]]
                                    - HTTPMethod can be any valid HTTP method, e.g., GET, POST, PUT, DELETE, etc.
                                Examples:
                                    - Oiwizard.POST
                                    - Oiwizard.ID.PUT
                                    - Oiwizard.ID.firstName.GET
        Response       [out] -- Response to be sent back to the Controller (HTTP_MCP) or requesting procedure. Web API
                                services do not rely upon anything being returned in the response. This is what the
                                various services like SetResponseBody and SetResponseStatus services are for. A response
                                value is only helpful if the developers want to use it for debug purposes.

    History     :   (Date, Initials, Notes)
        06/22/22    xxx     Original programmer.

***********************************************************************************************************************/

#pragma precomp SRP_PreCompiler

$insert APP_INSERTS
$insert API_SETUP
$insert HTTP_INSERTS

Declare function   Security_Services, OI_Wizard_Services, Utility_DotNet, Datetime, Active_Directory_Services
Declare subroutine OI_Wizard_Services

GoToAPI else
	// The specific resource endpoint doesn't have a API handler yet.
	HTTP_Services('SetResponseStatus', 204, 'This is a valid endpoint but a web API handler has not yet been created.')
end

Return Response OR ''


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Endpoint Handlers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


API oiwizard.POST
	
	// Check to see if a cookie is set
	OIWizardID = ''
	Cookies    = HTTP_Services('GetHTTPCookie')
	For each Cookie in Cookies using ';'
		Key = Field(Cookie, '=', 1)
		If Key EQ 'sessionID' then
			OIWizardID = Field(Cookie, '=', 2)
		end
	Next Cookie
	
	ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)
	
	If ValidSession EQ True$ then
		// Check to see if logout value was sent in the body
		Body    = HTTP_Services('GetHTTPPostString')
		If Body NE '' then
			// The POST string will have been encoded so use percent (URL) decoding
			WizardJSON    = HTTP_Services('DecodePercentString', Body)
			ParseResponse = SRP_JSON(hWizardJSON, 'PARSE', WizardJSON)
			If (ParseResponse EQ '') then
				Logout        = SRP_JSON(hWizardJSON, 'GetValue', 'logout')
				SRP_JSON(hWizardJSON, 'Release')
				If Logout EQ True$ then
					// Set session as terminated and clear cookies
					OI_Wizard_Services('TerminateSession', OIWizardID)
					If Error_Services('NoError') then
						Expiry  = Utility_DotNet('TIMEZONE', Datetime(), -1)
						HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'sessionID="" ;Expires=':Expiry)
						HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'userID="" ;Expires=':Expiry, True$)
						HTTP_Services('SetResponseHeaderField', 'Expires', Expiry, True$)
						Message = 'Session ended.'
					end
				end
				StatusCode = 200
				GoSub CreateHALItem
			end else
				HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
			end
		end else
			// Logout message not sent, so just send back a 200 to inform the front end the session is still valid.
			Expiry    = Xlate('OI_WIZARD', OIWizardID, 'EXPIRY_UTC', 'X')
			LSLUserID = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
			HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'sessionID=':OIWizardID:' ;Expires=':Expiry)
			HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'userID=':LSLUserID:' ;Expires=':Expiry, True$)
			HTTP_Services('SetResponseHeaderField', 'Expires', Expiry)
			StatusCode = 200
			GoSub CreateHALItem
		end
	end else
		// See if credentials were passed in and create a new session
		Body    = HTTP_Services('GetHTTPPostString')
		If Body NE '' then
			// The POST string will have been encoded so use percent (URL) decoding
			WizardJSON    = HTTP_Services('DecodePercentString', Body)
			ParseResponse = SRP_JSON(hWizardJSON, 'PARSE', WizardJSON)
			If (ParseResponse EQ '') then
				// Validate credentials and create a new session
				UserID     = SRP_JSON(hWizardJSON, 'GetValue', 'userID')
				Password   = SRP_JSON(hWizardJSON, 'GetValue', 'password')
				ADUsername = SRP_JSON(hWizardJSON, 'GetValue', 'adUsername')
				SRP_JSON(hWizardJSON, 'Release')
				Domain     = 'Infineon'
				Begin Case
				    Case ( (UserID NE '') and (Password NE '') )
				        Authenticated = Active_Directory_Services('AuthenticateUser', UserID, Password, Domain)
				        Authorized    = Active_Directory_Services('AuthorizeUser', UserID, Domain)
				    Case (ADUsername NE '')
				        Authenticated = True$
				        Authorized    = Active_Directory_Services('AuthorizeUser', ADUsername, Domain)
				        If Authorized then UserId = ADUsername
				    Case Otherwise$
				        Authenticated = False$
				        Authorized    = False$
				End Case
				If Authenticated and Authorized then
					LSLUserID = Security_Services('GetLSLUser', UserID)
					If LSLUserID NE '' then
						OIWizardID = OI_Wizard_Services('CreateWizardID', LSLUserID)
						If Error_Services('NoError') then
							Expiry     = Xlate('OI_WIZARD', OIWizardID, 'EXPIRY_UTC', 'X')
							HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'sessionID=':OIWizardID:' ;Expires=':Expiry)
							HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'userID=':LSLUserID:' ;Expires=':Expiry, True$)
							HTTP_Services('SetResponseHeaderField', 'Expires', Expiry)
							StatusCode = 201
							GoSub CreateHALItem
						end else
							Message = Error_Services('GetMessage')
							HTTP_Services('SetResponseStatus', 500, Message)
						end
					end else
						Message = 'Error in Security_Services("GetLSLUser") service. No LSLUserID found for user ':UserID:'.'
						HTTP_Services('SetResponseStatus', 500, Message)
					end
				end else
					HTTP_Services('SetResponseStatus', 401, Error_Services('GetMessage'))
				end
			end else
				HTTP_Services('SetResponseStatus', 400, 'Unable to parse the JSON data from the request.')
			end
		end else
			// No credentials passed in, so inform the front end that the sesion is invalid
			HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
		end
	end
	
end api


API oiwizard.HEAD
API oiwizard.GET
	
	// Check to see if a cookie is set
	OIWizardID = ''
	Cookies    = HTTP_Services('GetHTTPCookie')
	For each Cookie in Cookies using ';'
		Key = Field(Cookie, '=', 1)
		If Key EQ 'sessionID' then
			OIWizardID = Field(Cookie, '=', 2)
		end
	Next Cookie
	
	ValidSession = OI_Wizard_Services('ValidateSession', OIWizardID)
	
	If ValidSession EQ True$ then
		Expiry     = Xlate('OI_WIZARD', OIWizardID, 'EXPIRY_UTC', 'X')
		LSLUserID  = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
		HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'sessionID=':OIWizardID:' ;Expires=':Expiry)
		HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'userID=':LSLUserID:' ;Expires=':Expiry, True$)
		HTTP_Services('SetResponseHeaderField', 'Expires', Expiry)
		Message    = 'Valid session. Expiry updated'
		StatusCode = 200
		GoSub CreateHALItem
	end else
		HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
	end
	
end api
	
	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Internal GoSubs
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//----------------------------------------------------------------------------------------------------------------------
// CreateHALItem
//
// Creates a HAL+JSON object based on the OpenInsight data row representation of the scan.
//----------------------------------------------------------------------------------------------------------------------
CreateHALItem:
	
	HTTP_Services('SetResponseHeaderField', 'Content-Location', FullEndpointURL)
	If Assigned(Message) then
		HTTP_Services('SetResponseStatus', StatusCode, Message)
	end else
		HTTP_Services('SetResponseStatus', StatusCode)
	end
	
return

API oiwizard.checkidleoisessionvalid.HEAD
API oiwizard.checkidleoisessionvalid.GET

    OIWizardID = ''
	Cookies    = HTTP_Services('GetHTTPCookie')
	For each Cookie in Cookies using ';'
		Key = Field(Cookie, '=', 1)
		If Key EQ 'sessionID' then
			OIWizardID = Field(Cookie, '=', 2)
		end
	Next Cookie
	
	ValidSession = OI_Wizard_Services('ValidateSessionIdle', OIWizardID)
	
	If ValidSession EQ True$ then
		Expiry     = Xlate('OI_WIZARD', OIWizardID, 'EXPIRY_UTC', 'X')
		LSLUserID  = Xlate('OI_WIZARD', OIWizardID, 'EMPLOYEE_ID', 'X')
		HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'sessionID=':OIWizardID:' ;Expires=':Expiry)
		HTTP_Services('SetResponseHeaderField', 'Set-Cookie', 'userID=':LSLUserID:' ;Expires=':Expiry, True$)
		HTTP_Services('SetResponseHeaderField', 'Expires', Expiry)
		Message    = 'Valid session. Expiry updated'
		StatusCode = 200
		GoSub CreateHALItem
	end else
		HTTP_Services('SetResponseStatus', 401, 'Invalid session. Reauthentication required.')
	end

end api

