コード例 #1
0
ファイル: views.py プロジェクト: Ekan5h/fras
def login():
    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 == 'Y':
                return VU._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_hashed)

        if not valid:
            return VU._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 = VU._make_nav(u.role)
            return VU._ok_json({"user": user_obj, "nav": nav})
    except Exception as ex:
        msg = "Error when authenticating."
        logging.exception(msg)
        return VU._error_json(msg)
コード例 #2
0
ファイル: views.py プロジェクト: Ekan5h/fras
def kface_view(id=None):
    try:
        kf = KnownFace.get_by_id(id)
        if kf:
            obj = model_to_dict(kf, exclude=[KnownFace.user.password_hashed])
            return VU._ok_json(obj)
        else:
            return VU._error_json("Record not found for ID {}".format(id))
    except Exception as ex:
        msg = "Error when fetching known face."
        logging.exception(ex)
        return VU._error_json("{0}: {1}".format(msg, ex))
コード例 #3
0
ファイル: views.py プロジェクト: Ekan5h/fras
def kface_bulk_add():
    try:
        zipf = request.files['zip_file']
        if zipf.filename == '':
            return VU._error_json("No file supplied!")
        filename = secure_filename(zipf.filename)
        file_path = os.path.join(VU._get_upload_folder(), filename)
        zipf.save(file_path)
        recs = VU._process_photos_zip(file_path)
        return VU._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 VU._error_json("{0}: {1}".format(msg, ex))
コード例 #4
0
ファイル: views.py プロジェクト: Ekan5h/fras
def current_user():
    if "user" in session:
        u = session['user']
        nav = VU._make_nav(u["role"])
        return VU._ok_json({"user": u, "nav": nav})
    else:
        return VU._error_json("User not logged in.")
コード例 #5
0
ファイル: views.py プロジェクト: Ekan5h/fras
def kface_find():
    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_hashed])
            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 VU._ok_json(res)

    except Exception as ex:
        msg = "Error when finding known faces."
        logging.exception(ex)
        return VU._error_json(msg)
コード例 #6
0
ファイル: views.py プロジェクト: Ekan5h/fras
def signup():
    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_hashed=pw_hashed)
            # TODO: Validate user
            u.save()
            return VU._ok_json(
                "User created. Please login with your credentials.")
        else:
            return VU._error_json("GET not supported.")

    except Exception as ex:
        logging.exception("Error occurred when signing up.")
        return VU._error_json(str(ex))
コード例 #7
0
ファイル: views.py プロジェクト: Ekan5h/fras
def all_attendance():
    try:
        att = Attendance.select()
        return VU._ok_json([{
            "first_name": a.user.first_name,
            "last_name": a.user.last_name,
            "marked_on": a.ins_ts
        } for a in att])
    except Exception as ex:
        msg = "Error when fetching attendance."
        logging.exception(msg)
        return VU._error_json(msg)
コード例 #8
0
ファイル: views.py プロジェクト: Ekan5h/fras
def kface_delete():
    try:
        fd = request.get_json(force=True)
        ids = fd.get("ids")
        rc = 0
        if ids:
            rc = KnownFace.delete().where(KnownFace.id << ids).execute()
        return VU._ok_json("Deleted {} records.".format(rc))
    except Exception as ex:
        msg = "Error occurred when deleting faces."
        logging.exception(msg)
        return VU._error_json(msg)
コード例 #9
0
ファイル: views.py プロジェクト: Ekan5h/fras
def users_upload():
    try:
        # Only a superuser can add new users
        if not VU._is_user_in_role("SU"):
            return VU._error_json(
                "Operation not allowed. Insufficient privileges!")

        users_file = request.files['users_file']
        if users_file.filename == '':
            return VU._error_json("No file supplied!")
        filename = secure_filename(users_file.filename)
        file_path = os.path.join(VU._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_hashed=pbkdf2_sha256.hash(
                                 random_str(10)))
                    VU._save_entity(u)
            txn.commit()

        return VU._ok_json("Users added successfully!")

    except Exception as ex:
        print(ex)
        msg = "Error when handling users upload request."
        logging.exception(msg)
        return VU._error_json(msg)
コード例 #10
0
ファイル: views.py プロジェクト: Ekan5h/fras
def mark_attendance():
    try:
        grp_ph = request.files['group_photo']
        if grp_ph.filename == '':
            return VU._error_json("No file supplied!")
        filename = secure_filename(grp_ph.filename)
        file_path = os.path.join(VU._get_upload_folder(), filename)
        grp_ph.save(file_path)
        result = fapi.find_persons_in_photo(file_path,
                                            VU._fetch_known_faces_encodings())
        present = result["names_found"]
        for pp in present:
            u = User.get_by_id(pp["user_id"])
            ua = Attendance(user=u, status="Present")
            VU._save_entity(ua)
        result.pop("names_missing")
        print(result)
        return VU._ok_json(result)

    except Exception as ex:
        msg = "Error when handling attendance marking request."
        logging.exception(msg)
        return VU._error_json("{0}: {1}".format(msg, ex))
コード例 #11
0
ファイル: views.py プロジェクト: Ekan5h/fras
def kface_save():
    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")
            if ph.startswith(B64_HDR):
                photo_b64 = ph[len(B64_HDR):]
                face_enc = fapi.get_face_encoding_b64(photo_b64)
            else:
                raise Exception(
                    "Please supply a JPG format image. Mere renaming to .jpg won't work!"
                )
        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_enc = VU._np_to_json(face_enc)
            with db.transaction() as txn:
                try:
                    rc = VU._update_entity(KnownFace,
                                           kf,
                                           exclude=[KnownFace.user])
                    usr = kf.user
                    merge_form_to_model(usr, fd["user"])
                    rc += VU._update_entity(
                        User, usr, exclude=[User.role, User.password_hashed])
                    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_hashed = pbkdf2_sha256.hash(random_str(10))
                    VU._save_entity(u)

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

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

        return VU._ok_json(model_to_dict(kf))

    except Exception as ex:
        msg = "Error when saving known face."
        logging.exception(msg)
        return VU._error_json("{0}: {1}".format(msg, ex))