import pymongo
from chalicelib.util import database, errors, util

def get_users(user):
  if not util.has_permission(user, 'root'): raise errors.Forbidden('Not allowed')
  db = database.get_db()
  users = list(db.users.find({}, {'firstName': 1, 'lastName': 1, 'email': 1, 'createdAt': 1, 'lastSeenAt': 1}).sort('lastSeenAt', -1).limit(50))
  idps = list(db.idps.find({'user': {'$in': list(map(lambda u: u['_id'], users))}}, {'user': 1, 'code': 1, 'name': 1, 'createdAt': 1}))
  for u in users:
    u['idps'] = []
    for i in idps:
      if i['user'] == u['_id']: u['idps'].append(i)
  return {'users': users}