예제 #1
0
def user_login():
    try:
        data = request.get_json()
        email = data['email']
        password = data['password']

    except KeyError:
        abort(utils.response_fn(400, "error", "Should be email & password"))

    # check for the validity of the email
    v2utils.isEmailValid(email)
    # check if both values are stirngs
    utils.check_for_strings(data, ["email", "password"])
    # check for whitespaces.
    utils.check_for_whitespace(data, ["email", "password"])

    # try to get the record of the user by email.
    try:
        user = UserModel.get_user_by_mail(email)
        if not user:
            abort(utils.response_fn(404, "error", "User does not exist"))

        id = user[0][0]
        username = user[0][1]
        hashed_password = user[0][2]
        is_admin_prop = user[0][4]

        password = UserModel.check_if_password_n_hash_match(
            hashed_password, password)
        if not password:
            abort(
                utils.response_fn(400, "error",
                                  "The password is wrong, try again"))
        token = jwt.encode({
            "email": email,
            "isAdmin": is_admin_prop
        },
                           KEY,
                           algorithm='HS256')
        return utils.response_fn(
            200, "data", {
                "message": "Logged in successfully",
                "token": token.decode('UTF-8'),
                "user": {
                    "id": id,
                    "username": username
                }
            })
    except psycopg2.DatabaseError as _error:
        abort(utils.response_fn(500, "error", "Server error"))
예제 #2
0
def authorize_user_to_admin(user, user_id):
    try:
        adminprop = user[0][2]
    except:
        return utils.response_fn(401, "error",
                                 "You don't have an account. Create One")

    isUserAdmin(adminprop)
    userToBeElevated = UserModel.get_user_by_id(user_id)

    if userToBeElevated:
        UserModel.make_admin(userToBeElevated[0][0])
        return utils.response_fn(200, "data", [{
            "message": "Admin has been set"
        }])
    return utils.response_fn(
        404, "message", "The user you are trying to elevate is not registered")
예제 #3
0
def update_password():
    try:
        data = request.get_json()
        email = data['email']
        password = data['password']

    except KeyError:
        abort(utils.response_fn(400, "error", "Should be email & password"))

    v2utils.check_password_format(password)

    user = UserModel.get_user_by_mail(email)
    if not user:
        abort(utils.response_fn(404, "error", "User does not exist"))

    UserModel.update_password(email, password)

    return utils.response_fn(
        200, "data", {
            "message": "Password reset successfully. Login with new password",
        })
예제 #4
0
def secure_reset():
    """
        this endpoint is to be requested 
        from the server only via the 
        /auth/reset view. Client browsers accessing this view will
        be forbidden and hence the mail will not be sent
        view https://sendgrid.com/docs/for-developers/sending-email/cors/
        for more details on the reasons this implementation is necessary
    """
    try:
        data = request.get_json()
        email = data["email"]
    except KeyError:
        abort(utils.response_fn(400, "error", "Should be email"))
    # check if email is valid
    v2utils.isEmailValid(email)
    UserModel.sendmail(email)
    return utils.response_fn(200, "data", [{
        "message": "Check your email for password reset link",
        "email": email
    }])
예제 #5
0
def register_candidate_to_office(userobj, office_id):
    """
    this is where we check if the candidates information is
    eligible so that it can be registered to an office.
    """
    try:
        userAdminProperty = userobj[0][2]
    except:
        abort(
            utils.response_fn(401, "error",
                              "You don't have an account Create one"))

    try:
        data = request.get_json()
        user = data["user"]

    except KeyError:
        abort(utils.response_fn(400, "error", "User key should be present"))

    # check if details are for an admin.
    isUserAdmin(userAdminProperty)
    # check if fields are integers.
    utils.check_for_ints(data, ["user"])
    # does the candidate & office exist in the db.
    candidate = UserModel.get_user_by_id(user)
    office = OfficesModel.get_specific_office(office_id)
    if candidate and office:
        is_candidate_registered = CandidateModel.check_if_candidate_is_already_registered(
            user, office_id)
        if is_candidate_registered:
            abort(
                utils.response_fn(
                    400, "error",
                    "Candidate is already registered in this office"))

        # register the politician user.to a certain office.
        CandidateModel.register_politician_user_to_office(office_id, user)
        return utils.response_fn(201, "data", [{
            "office": office_id,
            "user": user
        }])
    else:
        return utils.response_fn(
            404, "error",
            "Either candidate or office is missing in the database")
예제 #6
0
def create_vote(user):
    """
    a voter can vote for a particular office
    if he has hasn't voted for it yet
    """
    try:
        user_id = user[0][1]
    except:
        return utils.response_fn(401, "error", "You don't have an account")

    try:
        data = request.get_json()
        office = data["office"]
        candidate = data["candidate"]

    except KeyError:
        abort(utils.response_fn(400, "error",
                                "Should be office & candidate, enter all fields"))

    utils.check_for_ints(data, ["office", "candidate"])
    try:

        iscandidatePresent = UserModel.get_user_by_id(candidate)
        isOfficePresent = OfficesModel.get_specific_office(office)
        if iscandidatePresent and isOfficePresent:
            isCandidateRegistered = CandidateModel.check_if_candidate_is_already_registered(
                candidate, office)
            if isCandidateRegistered:
                voted = VotesModel.check_if_user_already_voted(user_id, office)
                if voted:
                    return utils.response_fn(401, "error", "You have already voted")
                newvote = VotesModel(office, candidate, user_id)
                newvote.save_vote()
                return utils.response_fn(201, "data", [{
                    "office": office,
                    "candidate": candidate,
                    "voter": user_id
                }])
            return utils.response_fn(400, "error", "This candidate is not registered for the office.")
        return utils.response_fn(404, "error", "Either Candidate or party doesn't exist")

    except psycopg2.DatabaseError as _error:
        abort(utils.response_fn(500, "error", "Server error"))
예제 #7
0
def signup():
    """
        Sign a user up
    """
    try:
        data = request.get_json()
        firstname = data['firstname']
        lastname = data['lastname']
        username = data["username"]
        othername = data.get("othername", "")
        email = data["email"]
        phone = data["phone"]
        # doesnt have to fail because of absence of this value
        passportUrl = data.get("passportUrl", "")
        password = data["password"]
        retypedpassword = data["retypedpassword"]

    except:
        return abort(
            utils.response_fn(
                400, "error", 'Check your json keys. '
                'username, firstname, lastname,'
                'phone, email, password'))

    utils.check_for_strings(data, [
        "firstname", "lastname", "username", "othername", "passportUrl",
        "email", "phone"
    ])

    utils.check_for_whitespace(
        data, ["firstname", "lastname", "username", "email", "phone"])

    utils.check_for_bools(data, ["isAdmin", "isPolitician"])
    # check the passwords.
    v2utils.doPasswordsMatch(password, retypedpassword)
    # check the email provided
    v2utils.isEmailValid(email)
    # Check if phone number is valid
    v2utils.is_phone_number_valid(phone)

    v2utils.check_matching_items_in_db_table({"username": username}, "users")
    v2utils.check_matching_items_in_db_table({"email": email}, "users")

    newuser = UserModel(username=username,
                        email=email,
                        password=password,
                        firstname=firstname,
                        lastname=lastname,
                        phone=phone,
                        passportUrl=passportUrl,
                        othername=othername)
    newuser.save_user()
    token = jwt.encode({
        "email": email,
        "isAdmin": False
    },
                       KEY,
                       algorithm='HS256')
    return utils.response_fn(201, "data", [{
        "user": {
            "email": newuser.email,
            "username": newuser.username
        },
        "token": token.decode('UTF-8')
    }])
예제 #8
0
def get_all_users():
    return utils.response_fn(200, "data", UserModel.get_all_users())