Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Security.Principal
Imports System.Net
Imports System.ServiceModel.Activation

Imports System.Data.SqlClient
Imports System.Data

' NOTE: You can use the "Rename" command on the context menu to change the class name "LDAPService" in code, svc and config file together.

<HashHeaderInspection> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.PerSession)> _
Public Class LDAPService
    Implements ILDAPService

    Private curr_user As LoginResponse

    Public Sub New()
        curr_user = New LoginResponse
        curr_user.authtoken = "00000000-0000-0000-0000-000000000000"
        curr_user.username = "Unknown"
    End Sub

    Public Shared Sub Configure(config As ServiceConfiguration)
        DAL.Instance.InitConnectionsStr(
            ConfigurationManager.ConnectionStrings("DB_ConnectStr").ConnectionString,
            ConfigurationManager.ConnectionStrings("SecDB_ConnectStr").ConnectionString,
            30)
    End Sub

    Public Function Login(username As String, password As String) As LoginResponse Implements ILDAPService.Login
        Dim user As New LoginResponse
        user.status = False
        Log.Instance.Info("User Login: " + username)
#If Not Debug Then
        If Not DAL.Instance.AuthenticatedLDAP(username, password) Then  ' authentifcate with LDAP
            Log.Instance.Info("Authenticated LDAP Failed: " + username)
            user.failedlogonattempt = 1
            Return user
        End If
#End If
        Log.Instance.Info("Authenticated LDAP: " + username)

        Try
            Dim dt As DataTable = DAL.Instance.GetUserInfo(username)
            If dt.Rows.Count > 0 Then
                Dim dbuser As String = dt.Rows(0).Item("LoginId").ToString.Trim

                If String.Equals(dbuser, username, StringComparison.CurrentCultureIgnoreCase) Then
                    user.username = username
                    user.lastlogontime = Date.Now.ToTimestamp
                    user.lastrequesttime = user.lastlogontime
                    user.userrole = dt.Rows(0).Item("UserRole").ToString
                    user.viewgroupid = dt.Rows(0).Item("ViewGroupID").ToString
                    user.accttypelist = dt.Rows(0).Item("AcctTypeList").ToString
                    user.functionid = Convert.ToInt32(dt.Rows(0).Item("FuncId"))
                    user.authtoken = DAL.Instance.InsertSession(user)
                    user.ip_address = ""    ' NLB presense, no need for IP/WorkstationId
                    user.workstation = ""   ' NLB presense, no need for IP/WorkstationId
                    'DAL.Instance.GetClientIpAddress(user.ip_address)
                    'DAL.Instance.GetWorkStationId(user.ip_address, user.workstation)
                    DAL.Instance.GetAppSetting("location", user.location)

                    Log.Instance.Info(String.Format("User Verified: {0}@{1} from [{2}]", username, user.ip_address, user.workstation))

                    If user.authtoken.Length > 0 Then
                        ' get acct viewgroup info
                        user.accviewgroup = New List(Of AcctViewGroupContract)()
                        Dim vgdt As DataTable = DAL.Instance.GetAccViewGroup()
                        For Each row In vgdt.Rows
                            Dim accvg As New AcctViewGroupContract
                            accvg.type = row("AcctType")
                            accvg.numlength = Integer.Parse(row("AcctNumLength"))
                            accvg.sortorder = Integer.Parse(row("SortOrder"))

                            If user.accttypelist.Contains(accvg.type) Then
                                user.accviewgroup.Add(accvg)
                                user.accttypesortedlist += accvg.type + ","
                            End If
                        Next
                        If user.accttypesortedlist.Length > 0 Then
                            user.accttypesortedlist = user.accttypesortedlist.Substring(0, user.accttypesortedlist.LastIndexOf(","))
                        End If

                        HttpContext.Current.Session("SessionStarted") = True
                        Log.Instance.Info(String.Format("User session created: {0} with token [{1}]", username, user.authtoken))
                        user.status = True
                    End If
                End If
            Else
                Log.Instance.Info("Unable to get userinfo for: " + username)
            End If
        Catch ex As Exception
            Log.Instance.Error(ex.Message)
            Log.Instance.Error("Exception Logging in: " + username)
        End Try
        Return user
    End Function

    Public Function GetLogin() As LoginResponse Implements ILDAPService.GetLogin
        Dim user As New LoginResponse
        Try
            user.username = ServiceSecurityContext.Current.WindowsIdentity.Name
            DAL.Instance.GetAppSetting("location", user.location)
        Catch ex As Exception
            Log.Instance.Error("Error getting Windows UserId")
            Log.Instance.Error(ex.Message)
        End Try
        Return user
    End Function

    Public Function VerifyOverride(sessionid As String, type As String, number As String, username As String, password As String) As String Implements ILDAPService.VerifyOverride
        Dim ret As String = ReturnCode.OK
        If Not CheckSessionId(sessionid, ret) Then
            Log.Instance.Info(ret + ": User: " + curr_user.username + " SID: " + sessionid)
            Return ret
        End If

        If Not username.Contains("\") Then
            username = String.Format("{0}\{1}", DAL.Instance.GetDomainId(curr_user.username), username)
        End If

        Log.Instance.Info("VerifyOverride: " + username)

#If Not Debug Then
        If Not DAL.Instance.AuthenticatedLDAP(username, password) Then  ' authentifcate with LDAP
            Log.Instance.Info("Authenticated LDAP Failed: " + username)
            Return ReturnCode.INVALID_USER
        End If
#End If

        If username.Equals(curr_user.username, StringComparison.CurrentCultureIgnoreCase) Then
            Log.Instance.Info("VerifyOverride cannot authenticate self: " + username)
            Return ReturnCode.NOACCESS
        End If

        Log.Instance.Info("VerifyOverride Authenticated LDAP: " + username)

        Dim dt As DataTable = DAL.Instance.GetUserInfo(username)
        If dt.Rows.Count > 0 Then
            Dim funcid As Integer = Convert.ToInt32(dt.Rows(0).Item("FuncId"))

            Log.Instance.Info("User Privelege" + funcid.ToString)

            If funcid = UserPrivilage.SUPERVISOR Then
                DAL.Instance.LogView(type, number, username,
                    curr_user.workstation, curr_user.ip_address, curr_user.idteller, "Supervisor override")
                Return ReturnCode.OK
            End If
        End If

        Log.Instance.Info("VerifyOverride user NoAccess: " + username)
        Return ReturnCode.NOACCESS
    End Function