-- This file is part of the it-crafts software and is subject to copyright protection.
-- (C) 2022, All rights reserved by Steffen Anders, Elsteraue - Germany
-- Visit also https://www.it-crafts.de.
--

---------------------------------------------------------------------------------------------------------
IF 0 < (SELECT count(*) from [sysobjects] where [xtype] = 'P'   and [name] = 'itcproc_web_Login')
  DROP PROCEDURE [dbo].[itcproc_web_Login]
GO
CREATE PROCEDURE [dbo].[itcproc_web_Login]
  @Parm_Knr char(20)
 ,@Parm_Uid char(30)
 ,@Parm_Pwd char(30)
 ,@Parm_IPAddress char(20)
AS
  DECLARE @mPwHash  integer = dbo.itcfunc_StringHash(@Parm_Pwd)
  DECLARE @mPwHash2 integer
  DECLARE @mSessionId varchar(40)
  DECLARE @mDateAndTime char(16)
  DECLARE @mDate datetime
  DECLARE @mTime char(5)

  IF rtrim(@Parm_Knr) = '' OR rtrim(@Parm_Uid) = '' OR rtrim(@Parm_Pwd) = '' BEGIN
	SELECT 'Kundennummer, Benutzername und Passwort müssen angeben werden.' as error
	RETURN
  END

  IF rtrim(@Parm_IPAddress) = '' BEGIN
	SELECT 'Es wurde keine IP-Adresse angegeben.' as error
	RETURN
  END

  -- check credentials
  SELECT @mPwHash2 = ISNULL([PwHash], -1) FROM [dbo].[ut_WebUser] WITH(INDEX(Ik_Key00))  WHERE [Knr] = @Parm_Knr AND [Uid] = @Parm_Uid
  IF @mPwHash <> @mPwHash2 BEGIN
	SELECT 'Die Anmeldedaten sind fehlerhaft.' as error
	RETURN
  END

  -- add new Session
  SET @mSessionId = UPPER('{' + convert(varchar(38),NEWID()) + '}')
  SET @mDateAndTime = convert(char(16),GETDATE(),120)
  SET @mDate = convert(datetime,LEFT(@mDateAndTime,10),120)
  SET @mTime = RIGHT(@mDateAndTime,5)

  DELETE FROM [dbo].[ut_WebUserSession] WHERE [Knr] = @Parm_Knr AND [Uid] = @Parm_Uid AND [IPAddress] = @Parm_IPAddress

  INSERT [dbo].[ut_WebUserSession] ([RecId],[Knr],[Uid],[SessionId],[IPAddress],[LoginDate],[LoginTime],[UsingDate],[UsingTime])
        VALUES( ISNULL((SELECT MAX(RecId) FROM [dbo].[ut_WebUserSession]),0) + 1
  			 ,@Parm_Knr,@Parm_Uid,@mSessionId,@Parm_IPAddress,@mDate,@mTime,@mDate,@mTime)

  EXECUTE [dbo].[itcproc_WebLog_write] @Parm_Knr, @Parm_Uid, 'dbo.itcproc_web_Login', @mSessionId, @Parm_IPAddress , 1
  SELECT @mSessionId AS SessionId, '' AS Roule
GO
