<commit_before>ActiveDirectory = Npm.require('activedirectory');
Future = Npm.require('fibers/future')
assert = Npm.require('assert')

console.log 'Doing ldap stuff'

class UserQuery
  constructor: (username) -> 
    if !Meteor.settings.ldap
      throw new Error('LDAP settings missing.')

    @ad = ActiveDirectory({
      url: Meteor.settings.ldap.url,
      baseDN: Meteor.settings.ldap.baseDn,
      username: Meteor.settings.ldap.bindCn,
      password: <PASSWORD>Password
      attributes: {
        user: Meteor.settings.ldap.autopublishFields,
        }
       });
    @username = @sanitize_for_search(username)

  sanitize_for_search: (s) ->
    # Escape search string for LDAP according to RFC4515
    s = s.replace('\\', '\\5C')
    s = s.replace('\0', '\\00')
    s = s.replace('*','\\2A' )
    s = s.replace('(','\\28' )
    s = s.replace(')','\\29' )
    return s

  findUser: () -> 
    userFuture = new Future
    username = @username

    @ad.findUser @username, (err, userObj) ->
      if err
        console.log 'ERROR: ' + JSON.stringify(err)
        userFuture.return false
        return
      if !userObj
        console.log 'User: ' + username + ' not found.'
        userFuture.return false
      else
        console.log JSON.stringify(userObj)
        userFuture.return userObj

    userObj = userFuture.wait()
    if not userObj
      throw new (Meteor.Error)(403, 'Invalid username') 
    
    @userObj = userObj
  
  authenticate: (password) ->
    authenticateFuture = new Future
    @ad.authenticate @userObj.dn, password, (err, auth) ->
      if err
        console.log 'ERROR: ' + JSON.stringify(err)
        authenticateFuture.return false
        return
      if auth
        console.log 'Authenticated!'
        authenticateFuture.return true
      else
        console.log 'Authentication failed!'
        authenticateFuture.return false 
      return
    success = authenticateFuture.wait() 
    if not success or password == ''
      throw new (Meteor.Error)(403, 'Invalid credentials')
    @autenticated = success
    return success

  getGroupMembershipForUser: () ->
    groupsFuture = new Future
    @ad.getGroupMembershipForUser @userObj.dn, (err, groups) ->
      if err
        console.log('ERROR: ' +JSON.stringify(err));
        groupsFuture.return false
        return 
      if not groups
        console.log('User: ' + @userObj.dn + ' not found.')
        groupsFuture.return false
      else 
        console.log(JSON.stringify(groups))
        groupsFuture.return groups
      return
    return groupsFuture.wait()

  isUserMemberOf: (groupName) ->
    isMemberFuture = new Future
    @ad.isUserMemberOf @userObj.dn, groupName, (err, isMember) ->
      if err
        console.log 'ERROR: ' + JSON.stringify(err)
        isMemberFuture.return false
        return
      console.log @userObj.displayName + ' isMemberOf ' + groupName + ': ' + isMember
      isMemberFuture.return isMember
      return
    return isMemberFuture.wait()

  queryMembershipAndAddToMeteor: (callback) ->
    if !Meteor.settings.ldap
      throw new Error('LDAP settings missing.')

    for groupName in Meteor.settings.ldap.groupMembership
        ad = @ad
        userObj = @userObj
        do (groupName) ->
          ad.isUserMemberOf userObj.dn, groupName, (err, isMember) ->
            do (groupName) ->
              if err
                console.log 'ERROR: ' + JSON.stringify(err)
              else
                console.log(groupName, 'isMemberOf', isMember)
                callback(groupName,isMember)
          # console.log @userObj.dn + ' isMemberOf ' + groupName + ': ' + isMember


Accounts.registerLoginHandler 'ldap', (request) ->
  console.log 'Setting up LDAP connection'
  if !Meteor.settings.ldap
    throw new Error('LDAP settings missing.')

  # 1. create query
  user_query = new UserQuery(request.username)

  console.log 'LDAP authentication for ' + request.username

  user_query.findUser() # Allows both sAMAccountName and email
  # 2. authenticate user
  authenticated = user_query.authenticate(request.password)
  
  console.log('* AUTENTICATED:',authenticated)

  # 3. update database
  userId = undefined
  userObj = user_query.userObj
  user = Meteor.users.findOne(dn: userObj.dn)
  if user
    userId = user._id<commit_msg>Update ldap_server.coffee<commit_after>ActiveDirectory = Npm.require('activedirectory');
Future = Npm.require('fibers/future')
assert = Npm.require('assert')

console.log 'Doing ldap stuff'

class UserQuery
  constructor: (username) -> 
    if !Meteor.settings.ldap
      throw new Error('LDAP settings missing.')

    @ad = ActiveDirectory({
      url: Meteor.settings.ldap.url,
      baseDN: Meteor.settings.ldap.baseDn,
      username: Meteor.settings.ldap.bindCn,
      password: <PASSWORD>
      attributes: {
        user: Meteor.settings.ldap.autopublishFields,
        }
       });
    @username = @sanitize_for_search(username)

  sanitize_for_search: (s) ->
    # Escape search string for LDAP according to RFC4515
    s = s.replace('\\', '\\5C')
    s = s.replace('\0', '\\00')
    s = s.replace('*','\\2A' )
    s = s.replace('(','\\28' )
    s = s.replace(')','\\29' )
    return s

  findUser: () -> 
    userFuture = new Future
    username = @username

    @ad.findUser @username, (err, userObj) ->
      if err
        console.log 'ERROR: ' + JSON.stringify(err)
        userFuture.return false
        return
      if !userObj
        console.log 'User: ' + username + ' not found.'
        userFuture.return false
      else
        console.log JSON.stringify(userObj)
        userFuture.return userObj

    userObj = userFuture.wait()
    if not userObj
      throw new (Meteor.Error)(403, 'Invalid username') 
    
    @userObj = userObj
  
  authenticate: (password) ->
    authenticateFuture = new Future
    @ad.authenticate @userObj.dn, password, (err, auth) ->
      if err
        console.log 'ERROR: ' + JSON.stringify(err)
        authenticateFuture.return false
        return
      if auth
        console.log 'Authenticated!'
        authenticateFuture.return true
      else
        console.log 'Authentication failed!'
        authenticateFuture.return false 
      return
    success = authenticateFuture.wait() 
    if not success or password == ''
      throw new (Meteor.Error)(403, 'Invalid credentials')
    @autenticated = success
    return success

  getGroupMembershipForUser: () ->
    groupsFuture = new Future
    @ad.getGroupMembershipForUser @userObj.dn, (err, groups) ->
      if err
        console.log('ERROR: ' +JSON.stringify(err));
        groupsFuture.return false
        return 
      if not groups
        console.log('User: ' + @userObj.dn + ' not found.')
        groupsFuture.return false
      else 
        console.log(JSON.stringify(groups))
        groupsFuture.return groups
      return
    return groupsFuture.wait()

  isUserMemberOf: (groupName) ->
    isMemberFuture = new Future
    @ad.isUserMemberOf @userObj.dn, groupName, (err, isMember) ->
      if err
        console.log 'ERROR: ' + JSON.stringify(err)
        isMemberFuture.return false
        return
      console.log @userObj.displayName + ' isMemberOf ' + groupName + ': ' + isMember
      isMemberFuture.return isMember
      return
    return isMemberFuture.wait()

  queryMembershipAndAddToMeteor: (callback) ->
    if !Meteor.settings.ldap
      throw new Error('LDAP settings missing.')

    for groupName in Meteor.settings.ldap.groupMembership
        ad = @ad
        userObj = @userObj
        do (groupName) ->
          ad.isUserMemberOf userObj.dn, groupName, (err, isMember) ->
            do (groupName) ->
              if err
                console.log 'ERROR: ' + JSON.stringify(err)
              else
                console.log(groupName, 'isMemberOf', isMember)
                callback(groupName,isMember)
          # console.log @userObj.dn + ' isMemberOf ' + groupName + ': ' + isMember


Accounts.registerLoginHandler 'ldap', (request) ->
  return undefined if !request.ldap
  console.log 'Setting up LDAP connection'
  if !Meteor.settings.ldap
    throw new Error('LDAP settings missing.')

  # 1. create query
  user_query = new UserQuery(request.username)

  console.log 'LDAP authentication for ' + request.username

  user_query.findUser() # Allows both sAMAccountName and email
  # 2. authenticate user
  authenticated = user_query.authenticate(request.password)
  
  console.log('* AUTENTICATED:',authenticated)

  # 3. update database
  userId = undefined
  userObj = user_query.userObj
  user = Meteor.users.findOne(dn: userObj.dn)
  if user
    userId = user._id
{'fraction_non_alphanumeric': 0.11138154844691701, 'fraction_numerical': 0.005099675475197033, 'mean_word_length': 2.5134364820846904, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3260960', 'n_tokens_mistral': 2694, 'n_tokens_neox': 2570, 'n_words': 612}