Node JS

TIP: Node JS PUG Conditionals

Recently I was working on a tiny project in which I need to make text field as READONLY when it’s backfilled by query and FREE TEXT if empty. Yes, as you guessed I use PowerShell a lot at my workplace. Having said that, let me show case the demo using PowerShell and Node JS

Scenario

Query Active Directory for a given sAMAccountName. If user has mobile number display on web page in a text box as READ ONLY and if null make it free text!

Solution (Conditional Pug – Logic)

if !Mobile
    label(for='uMobile') Mobile Number
    input#uPhone(type='text', name='uMobileNumber', readonly=false, value=Mobile)
else
    label(for='uMobile') Mobile Number
    input#uPhone(type='text', name='uMobileNumber', readonly=true, value=Mobile)

Query AD User

#Using ADSI
param (
    $sAMAccountName
)
try {
    $adsi = New-Object adsisearcher
    $adsi.Filter = "(&(ObjectCategory=User)(samaccountname=$sAMAccountName))"
    $PropsToLoad = @('givenname' , 'sn' , 'mail' , 'cn' , 'mobile')
    $adsi.PropertiesToLoad.AddRange($PropsToLoad)
    if ($adsi.FindOne()) {
        $UserProperties = $adsi.FindOne().Properties 
        [pscustomobject]@{
            sAMAccountName = $UserProperties['cn'] -as [string]
            FirstName      = $UserProperties['givenname'] -as [string]
            LastName       = $UserProperties['sn'] -as [string]
            Email          = $UserProperties['mail'] -as [string]
            Mobile         = $UserProperties['mobile'] -as [string]
        } | ConvertTo-Json -Compress
    }
}
catch {
    $_.Exception 
}

Server JS (Route)

app.get('/searchADUser', function (request, response) {
    response.render('searchADUser')
})
app.post("/adUserInformation", function (request, response) {
    child = spawn('powershell.exe',
        [ "C:\\Projects\\Events-2018-2019\\BITPro-AUG-04-2018\\scripts\\GetADUser.ps1 -sAMAccountName " +
            request.body.sAMAccountName ])
    child.stdout.on('data', function (data) {
        var results = JSON.parse(data.toString());
        //console.log(results);
        response.render('adUserInformation', {
            sAMAccountName: results[ 'sAMAccountName' ],
            FirstName: results[ 'FirstName' ],
            LastName: results[ 'LastName' ],
            Email: results[ 'Email' ],
            EmployeeNumber: results[ 'EmployeeNumber' ],
            NewPassword: results[ 'NewPassword' ]
        })
    })
})

Documentation for Reference!

Leave a Reply

Your email address will not be published. Required fields are marked *