Ejemplo n.º 1
0
def login():
    """ Login view """
    try:
        lf = request.get_json(force=True)
        login_id = lf.get("login_id")
        plain_pass = lf.get("password")
        logging.debug("Received login request for user {}".format(login_id))

        u = User.get_or_none(User.login_id == login_id)
        valid = False
        if u:
            if u.is_locked == True:
                return _error_json("User is locked! Please contact admin.")
            logging.info("Got user: {0}, {1}".format(u.login_id, u.first_name))
            valid = pbkdf2_sha256.verify(plain_pass, u.password)

        if not valid:
            return _error_json("Invalid user/password.")
        else:
            user_obj = {"id": u.id, "login_id": login_id,
                        "name": "{0} {1}".format(u.first_name, u.last_name), "role_name": u.get_role_label(), "role": u.role}
            session['user'] = user_obj
            nav = _make_nav(u.role)
            return _ok_json({"user": user_obj, "nav": nav})
    except Exception as ex:
        msg = "Error when authenticating."
        logging.exception(msg)
        return _error_json(msg)
Ejemplo n.º 2
0
def kface_find():
    """ View to find a known face """
    try:
        fd = request.get_json(force=True)
        pg_no = int(fd.get('pg_no', 1))
        query = KnownFace.select().join(User)
        if fd.get("first_name"):
            query = query.where(User.first_name.contains(fd.get("first_name")))
        if fd.get("login_id"):
            query = query.where(User.login_id.contains(fd.get("login_id")))

        faces = query.order_by(KnownFace.id).paginate(pg_no, PAGE_SIZE)
        serialized = [
            model_to_dict(r, exclude=[KnownFace.user.password]) for r in faces
        ]

        has_next = len(faces) >= PAGE_SIZE
        res = {
            "faces": serialized,
            "pg_no": pg_no,
            "pg_size": PAGE_SIZE,
            "has_next": has_next
        }
        return _ok_json(res)

    except Exception as ex:
        msg = "Error when finding known faces."
        logging.exception(msg)
        return _error_json(msg)
Ejemplo n.º 3
0
def users_upload():
    """ View to upload users """
    try:
        # Only a superuser can add new users
        if not _is_user_in_role("SU"):
            return _error_json("Operation not allowed. Insufficient privileges!")

        users_file = request.files['users_file']
        if users_file.filename == '':
            return _error_json("No file supplied!")
        filename = secure_filename(users_file.filename)
        file_path = os.path.join(_get_upload_folder(), filename)
        users_file.save(file_path)

        with db.atomic() as txn:
            # TODO: Use a better/efficient strategy to add users in DB
            with open(file_path, newline='') as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    login_id = row["LOGIN_ID"]
                    fname = row["FIRST_NAME"]
                    lname = row["LAST_NAME"]
                    email = row["EMAIL"]
                    u = User(login_id=login_id, first_name=fname,
                             last_name=lname, email=email,
                             password=pbkdf2_sha256.hash(random_str(10)))
                    _save_entity(u)
            txn.commit()

        return _ok_json("Users added successfully!")

    except Exception as ex:
        msg = "Error when handling users upload request."
        logging.exception(msg)
        return _error_json(msg)
Ejemplo n.º 4
0
def current_user():
    """ Current User view """
    if "user" in session:
        u = session['user']
        nav = _make_nav(u["role"])
        return _ok_json({"user": u, "nav": nav})
    else:
        return _error_json("User not logged in.")
Ejemplo n.º 5
0
def all_attendance():
    """ View to view all attendances """
    try:
        att = Attendance.select()
        return _ok_json([{"first_name": a.user.first_name,
                         "last_name": a.user.last_name,
                         "marked_on": a.insert_timestamp} for a in att])
    except Exception as ex:
        msg = "Error when fetching attendance."
        logging.exception(msg)
        return _error_json(msg)
Ejemplo n.º 6
0
def kface_view(id=None):
    """ View to view a known face """
    try:
        kf = KnownFace.get_by_id(id)
        if kf:
            obj = model_to_dict(kf, exclude=[KnownFace.user.password])
            return _ok_json(obj)
        else:
            return _error_json("Record not found for ID {}".format(id))
    except Exception as ex:
        msg = "Error when fetching known face."
        logging.exception(msg)
        return _error_json("{0}: {1}".format(msg, ex))
Ejemplo n.º 7
0
def kface_delete():
    """ View to delete a known face """
    try:
        fd = request.get_json(force=True)
        ids = fd.get("ids")
        rc = 0
        if ids:
            rc = KnownFace.delete().where(KnownFace.id << ids).execute()
        return _ok_json("Deleted {} records.".format(rc))
    except Exception as ex:
        msg = "Error occurred when deleting faces."
        logging.exception(msg)
        return _error_json(msg)
Ejemplo n.º 8
0
def kface_bulk_add():
    """ View to to bulk add known faces """
    try:
        zipf = request.files['zip_file']
        if zipf.filename == '':
            return _error_json("No file supplied!")
        filename = secure_filename(zipf.filename)
        file_path = os.path.join(_get_upload_folder(), filename)
        zipf.save(file_path)
        recs = _process_photos_zip(file_path)
        return _ok_json("Saved {0} photos from file {1}.".format(
            recs, filename))
    except Exception as ex:
        msg = "Error when handling ZIP file."
        logging.exception(msg)
        return _error_json("{0}: {1}".format(msg, ex))
Ejemplo n.º 9
0
def signup():
    """ Signup view """
    error = None
    try:
        if request.method == 'POST':
            pw_hashed = pbkdf2_sha256.hash(request.form.get('password'))
            u = User(login_id=request.form.get('login_id'),
                     email=request.form.get('email'),
                     first_name=request.form.get('first_name'),
                     last_name=request.form.get('last_name'),
                     password=pw_hashed)
            # TODO: Validate user
            u.save()
            return _ok_json("User created. Please login with your credentials.")
        else:
            return _error_json("GET not supported.")

    except Exception as ex:
        logging.exception("Error occurred when signing up.")
        return _error_json(str(ex))
Ejemplo n.º 10
0
def mark_attendance():
    """ View to mark attendance """
    try:
        grp_ph = request.files['group_photo']
        if grp_ph.filename == '':
            return _error_json("No file supplied!")
        filename = secure_filename(grp_ph.filename)
        file_path = os.path.join(_get_upload_folder(), filename)
        grp_ph.save(file_path)
        result = fapi.find_persons_in_photo(
            file_path, _fetch_known_faces_encodings())
        present = result["names_found"]
        for pp in present:
            u = User.get(User.first_name == pp)
            ua = Attendance(user=u, status="Present")
            _save_entity(ua)
        result.pop("names_missing")
        return _ok_json(result)

    except Exception as ex:
        msg = "Error when handling attendance marking request."
        logging.exception(msg)
        return _error_json("{0}: {1}".format(msg, ex))
Ejemplo n.º 11
0
def kface_save():
    """ View to to save a known face """
    try:
        fd = request.get_json(force=True)
        logging.info("Saving kface: {}".format(fd))
        sid = int(fd.get("id") or 0)
        face_enc = None
        if fd.get("photo"):
            ph = fd.get("photo")
            # REmoved exception to make test work
            photo_b64 = ph[len(B64_HDR):]
            face_enc = fapi.get_face_encoding_b64(photo_b64)
        else:
            logging.debug("No photo supplied.")

        kf = KnownFace()
        if sid:
            kf = KnownFace.get_by_id(sid)
            # TODO: Check ownership
            merge_form_to_model(kf, fd)
            kf.face_encoding = _np_to_json(face_enc)
            with db.transaction() as txn:
                try:
                    rc = _update_entity(KnownFace,
                                        kf,
                                        exclude=[KnownFace.user])
                    usr = kf.user
                    merge_form_to_model(usr, fd["user"])
                    rc += _update_entity(User,
                                         usr,
                                         exclude=[User.role, User.password])
                    if rc != 2:
                        raise IntegrityError(
                            "Could not update. Please try again.")
                    txn.commit()
                except DatabaseError as dbe:
                    txn.rollback()
                    raise dbe
            logging.debug("Updated known face: {}".format(kf))

        else:
            with db.transaction() as txn:
                try:
                    u = User()
                    merge_form_to_model(u, fd["user"])
                    u.password = pbkdf2_sha256.hash(random_str(10))
                    _save_entity(u)

                    merge_form_to_model(kf, fd)
                    kf.user = u
                    kf.face_encoding = _np_to_json(face_enc)
                    _save_entity(kf)

                    txn.commit()
                except DatabaseError as dbe:
                    txn.rollback()
                    raise dbe
            logging.info("Inserted: {}".format(kf))

        return _ok_json(model_to_dict(kf))

    except Exception as ex:
        msg = "Error when saving known face."
        logging.exception(msg)
        return _error_json("{0}: {1}".format(msg, ex))
Ejemplo n.º 12
0
def logout():
    """ Logout view """
    session.pop('user', None)
    return _ok_json("Logged out.")
Ejemplo n.º 13
0
def home():
    """ Home view """
    return _ok_json("Welcome HOME!")