Esempio n. 1
0
def reset_password(request):
    try:
        phone_number = request.data.get('phonenumber', None)
        if phone_number != None and phone_number != "":
            if User.objects.filter(user_phone=phone_number).exists() == False:
                return_data = {"error": "1", "message": "User does not exist"}
            else:
                user_data = otp.objects.get(user__user_phone=phone_number)
                user = User.objects.get(user_phone=phone_number)
                generate_pin = string_generator.alphanumeric(6)
                user_data.password_reset_code = generate_pin
                user_data.save()
                message = f"Welcome to Agrilance, your password reset code is {generate_pin}"
                sms.sendsms(phone_number[1:], message)
                timeLimit = datetime.datetime.utcnow() + datetime.timedelta(
                    minutes=1440)  #set limit for user
                payload = {
                    "user_id": f'{user.user_id}',
                    "validated": user_data.validated,
                    "exp": timeLimit
                }
                token = jwt.encode(payload, settings.SECRET_KEY)
                return_data = {
                    "error": "0",
                    "message": "Successful, reset code sent to Phone Number",
                    "token": token.decode('UTF-8')
                }
        else:
            return_data = {"error": "2", "message": "Invalid Parameter"}
    except Exception as e:
        return_data = {"error": "3", "message": str(e)}
    return Response(return_data)
Esempio n. 2
0
def redeemcoins(request,decrypedToken):
    try:
        coins_amount = request.data.get("amount",None)
        if coins_amount is not None and coins_amount is not "":
            coins_amount = float(coins_amount)
            if coins_amount == float(0) or coins_amount < float(0):
                return_data = {
                    "error": 2,
                    "message": "Number is negative or zero"
                }
            else:
                user_coins = UserCoins.objects.get(user__user_id=decrypedToken["user_id"])
                exchange_rate = fixed_var.exchange_rate
                numofCoins = user_coins.minedCoins
                user_data = User.objects.get(user_id=decrypedToken["user_id"])
                if coins_amount > numofCoins:
                    return_data = {
                        "error": "1",
                        "message": "Not enough coins"
                    }
                else:
                    transactionid = string_generator.alphanumeric(15)
                    toNaira = exchange_rate * coins_amount
                    user_coins.minedCoins = numofCoins - coins_amount
                    user_coins.redeemedWasteCoin = coins_amount
                    user_coins.save()
                    #Save Transaction
                    transaction = UserTrasactionHistory(user=user_data,transaction_id=transactionid,
                                                        amount=coins_amount,coin_redeemed_amount=toNaira,transaction="Debit")
                    transaction.save()
                    #Add coin to the coin repository
                    return_data = {
                        "error": "0",
                        "message": "Successfully redeemed coins",
                        "transaction_id": f"{transactionid}",
                        "amount": f"{toNaira}"
                    }
        else:
            return_data = {
                "error": 2,
                "message": "Invalid Parameter"
            }
    except Exception as e:
        return_data = {
            "error": "3",
            "message": str(e)
        }
    return Response(return_data)
Esempio n. 3
0
def signup(request):
    try:
        firstName = request.data.get('firstname', None)
        lastName = request.data.get('lastname', None)
        phoneNumber = request.data.get('phonenumber', None)
        email = request.data.get('email', None)
        password = request.data.get('password', None)
        address = request.data.get('address', None)
        reg_field = [
            firstName, lastName, phoneNumber, email, password, address
        ]
        if not None in reg_field and not "" in reg_field:
            if User.objects.filter(
                    user_phone=phoneNumber).exists() or User.objects.filter(
                        email=email).exists():
                return_data = {"error": "1", "message": "User Exists"}
            elif validator.checkmail(email) == False or validator.checkphone(
                    phoneNumber) == False:
                return_data = {
                    "error": "1",
                    "message": "Email or Phone number is Invalid"
                }
            else:
                #generate user_id
                userRandomId = string_generator.alphanumeric(6)
                #encrypt password
                encryped_password = password_functions.generate_password_hash(
                    password)
                #Save user_data
                new_userData = User(user_id=userRandomId,
                                    firstname=firstName,
                                    lastname=lastName,
                                    email=email,
                                    user_phone=phoneNumber,
                                    user_password=encryped_password,
                                    user_address=address)
                new_userData.save()
                #Generate OTP
                code = string_generator.numeric(6)
                #Save OTP
                user_OTP = otp(user=new_userData, otp_code=code)
                user_OTP.save()

                # Get User Validation
                validated = otp.objects.get(
                    user__user_id=userRandomId).validated
                #Generate token
                timeLimit = datetime.datetime.utcnow() + datetime.timedelta(
                    minutes=1440)  #set duration for token
                payload = {
                    "user_id": f"{userRandomId}",
                    "validated": validated,
                    "exp": timeLimit
                }
                token = jwt.encode(payload, settings.SECRET_KEY)
                message = f"Welcome to Agrilance, your verification code is {code}"
                sms.sendsms(phoneNumber[1:], message)
                return_data = {
                    "error": "0",
                    "message":
                    "The registration was successful, A verification SMS has been sent",
                    "token": f"{token.decode('UTF-8')}",
                    "elapsed_time": f"{timeLimit}",
                }
        else:
            return_data = {"error": "2", "message": "Invalid Parameter"}
    except Exception as e:
        return_data = {"error": "3", "message": str(e)}
    return Response(return_data)
Esempio n. 4
0
def allocate_coins(request,decrypedToken):
    try:
        coins_allocated = float(request.data.get("coins_allocated",None))
        total_coins_mined = UserTrasactionHistory.objects.filter(transaction="Credit").aggregate(Sum('amount'))['amount__sum']
        monthly_allocation = fixed_var.backallocation
        user_MinerID = request.data.get("miner_id",None)
        field = [coins_allocated,user_MinerID]
        if not None in field and not "" in field:
            if UserCoins.objects.filter(minerID=user_MinerID).exists() == False:
                return_data = {
                    "error": "1",
                    "message": "User does not exist"

                    }
            elif User.objects.get(user_id= decrypedToken['user_id']).role != "agent":
                return_data = {
                    "error": "2",
                    "message": "Unauthorized User"

                    }
            else:
                agent_coins = AgentCoins.objects.get(agent__user_id=decrypedToken["user_id"]).agentCoins
                if coins_allocated > agent_coins:
                    return_data = {
                        "error": "2",
                        "message": "Not enough coins"
                    }
                elif total_coins_mined >= monthly_allocation:
                    return_data = {
                        "error": "2",
                        "message": "Maximum monthly allocation reached"
                    }
                else:
                    wastecoin_user = UserCoins.objects.get(minerID=user_MinerID)
                    user = wastecoin_user.user
                    agent_user = User.objects.get(user_id= decrypedToken['user_id'])
                    agent_coins = AgentCoins.objects.get(agent__user_id=decrypedToken["user_id"])
                    user_coins = UserCoins.objects.get(user__user_id=user.user_id)
                    string_generator.alphanumeric(15)
                    #allocate Coin to user
                    remaining_coins =agent_coins.agentCoins - coins_allocated
                    agent_coins.agentCoins = remaining_coins
                    #Debit_agent
                    withdrawl= AgentTransactionHistory(agent=agent_user,transaction_id=string_generator.alphanumeric(15),amount=coins_allocated,
                                                       coin_allocated_to=user_MinerID,transaction="Debit")
                    agent_coins.save()
                    withdrawl.save()
                    #credit User
                    add_coins = user_coins.minedCoins + coins_allocated
                    user_coins.minedCoins = add_coins
                    allocate = UserTrasactionHistory(user=user,transaction_id=string_generator.alphanumeric(15),
                                                     amount=coins_allocated,transaction="Credit")
                    user_coins.save()
                    allocate.save()
                    return_data = {
                        "error": "0",
                        "message": f"Successful. WasteCoin is allocated to {user.firstname} {user.lastname}",
                        "current_balance": f"{remaining_coins}"
                    }
        else:
            return_data = {
                "error": "2",
                "message": "Invalid Parameters"
            }
    except Exception as e:
        return_data = {
            "error": "3",
            "message": str(e)
            }
    return Response(return_data)
Esempio n. 5
0
def user_registration(request):
    try:
        firstName = request.data.get('firstname',None)
        lastName = request.data.get('lastname',None)
        phoneNumber = request.data.get('phonenumber',None)
        email = request.data.get('email',None)
        gender = request.data.get('gender',None)
        password = request.data.get('password',None)
        address = request.data.get('address',None)
        lga = request.data.get('lga',None)
        state = request.data.get('state',None)
        country = request.data.get('country',None)
        reg_field = [firstName,lastName,phoneNumber,email,password,address,lga,state,country]
        if not None in reg_field and not "" in reg_field:
            if User.objects.filter(user_phone =phoneNumber).exists() or User.objects.filter(email =email).exists():
                return_data = {
                    "error": "1",
                    "message": "User Exists"
                }
            elif validator.checkmail(email) == False or validator.checkphone(phoneNumber)== False:
                return_data = {
                    "error": "1",
                    "message": "Email or Phone number is Invalid"
                }
            else:
                #generate user_id
                userRandomId = string_generator.alphanumeric(20)
                miner_id = string_generator.numeric(7)
                transactionid = string_generator.alphanumeric(15)
                #encrypt password
                encryped_password = password_functions.generate_password_hash(password)
                #Save user_data
                new_userData = User(user_id=userRandomId,firstname=firstName,lastname=lastName,
                                email=email,user_phone=phoneNumber,user_gender=gender,
                                user_password=encryped_password,user_address=address,
                                user_state=state,user_LGA=lga,user_country=country)
                new_userData.save()
                #Generate OTP
                code = string_generator.numeric(6)
                #Save OTP
                user_OTP =otp(user=new_userData,otp_code=code)
                user_OTP.save()
                #Generate default coins
                user_Coins = UserCoins(user=new_userData,minerID=miner_id,redeemedWasteCoin=0,minedCoins=0)
                user_Coins.save()
                #Save Transaction Details
                user_transaction = UserTrasactionHistory(user=new_userData,transaction_id=transactionid,
                                                        amount=0,coin_redeemed_amount=0,transaction="Credit")
                user_transaction.save()
                role = User.objects.get(user_id=userRandomId).role
                validated = otp.objects.get(user__user_id=userRandomId).validated
                #Generate token
                timeLimit= datetime.datetime.utcnow() + datetime.timedelta(minutes=1440) #set duration for token
                payload = {"user_id": f"{userRandomId}",
                           "role": role,
                           "validated": validated,
                           "exp":timeLimit}
                token = jwt.encode(payload,settings.SECRET_KEY)
                message = f"Welcome to WasteCoin, your verification code is {code}"
                sms.sendsms(phoneNumber[1:],message)
                return_data = {
                    "error": "0",
                    "message": "The registration was successful, A verrification SMS has been sent",
                    "token": f"{token.decode('UTF-8')}",
                    "elapsed_time": f"{timeLimit}",
                    }
        else:
            return_data = {
                "error":"2",
                "message": "Invalid Parameter"
            }
    except Exception as e:
        return_data = {
            "error": "3",
            "message": str(e)
        }
    return Response(return_data)