def loaded_db(db, user_details, unconfirmed_user):
    """An active database instance with two users -- one admin, one contrib"""
    encrypted_user_details = {
        **user_details,
        "password": encrypt(user_details["password"]),
    }
    with Session(db._engine, future=True) as session:
        session.add(User(**encrypted_user_details))
        session.add(User(**unconfirmed_user))
        session.commit()
    return db
Beispiel #2
0
    async def get_users_for_client(self, client_token):
        while self._sultan:
            await asyncio.sleep(1)
        self._sultan = True
        data = []
        clients_users = await self.users_database.count_documents(
            {'client': client_token})
        if clients_users > 0:
            await self.take_away_all_users_from_client(client_token)
        needed_users = MAX_USERS_PER_CLIENT
        free_users = self.users_database.find({
            'client': None
        }).limit(needed_users)

        async for i in free_users:
            await self.users_database.update_one(
                filter={'_id': i['_id']},
                update={"$set": {
                    'client': client_token
                }})
            data.append(User(**i).dict())

        print(f'Sending {len(data)} users to {client_token}')
        self._sultan = False
        return data
def getnextid(city):
    lastUser = User.objects(
        uid__startswith=(str(city)[:3].upper())).order_by('-uid').first()
    if lastUser:
        return int(lastUser['uid'][3:]) + 1
    else:
        return 1
 def _ensure_admin(self):
     """
     For development use only. Creates a default admin user
     if one does not yet exist.
     """
     with Session(self._engine, future=True) as session:
         accounts = session.query(User).all()
         if len(accounts):
             log.info("Found an existing account.")
             return
         log.info("Creating a default admin account.")
         # cur_user = session.query(User).filter(User.username == 'admin').one()
         # session.delete(cur_user)
         # session.commit()
         user = User(
             id=str(uuid4()),
             username="******",
             password=encrypt("admin"),
             f_name="tha",
             l_name="admin",
             email="*****@*****.**",
             type="admin",
             confirmed=True,
             deactivated=False,
         )
         session.add(user)
         session.commit()
Beispiel #5
0
def getpartydetails():
    user = json.loads(User.objects(pk=request.form["id"]).first().to_json(follow_reference=True))

    data = {
        "id" : user['id'] if 'id' in user else "",
        "role" : user['role'] if 'role' in user else "",
        "branch" : user['branch']['id'] if 'branch' in user else "",
        "category" : user['category'] if 'category' in user else "",
        "group" : user['group']['id'] if 'group' in user else "",
        "companyname" : user['companyname'] if 'companyname' in user else "",
        "fullname" : user['fullname'] if 'fullname' in user else "",
        "email" : user['email'] if 'email' in user else "",
        "mobilenumber" : user['mobilenumber'] if 'mobilenumber' in user else "",
        "gstin" : user['gstin'] if 'gstin' in user else "",
        "billingaddress" : user['billingaddress'] if 'billingaddress' in user else "",
        "city" : user['city'] if 'city' in user else "",
        "state" : user['state'] if 'state' in user else "",
        "pincode" : user['pincode'] if 'pincode' in user else "",
        "openingbalance" : user['openingbalance'] if 'openingbalance' in user else "",
        "userclass" : user['userclass'],
        "openingbalancedate" : datetime.fromtimestamp(float(user['openingbalancedate'])).strftime("%d/%m/%Y") if 'openingbalancedate' in user else "",
        "status" : user['status'] if 'status' in user else "",
        "whatsapp" : user['whatsapp'] if 'whatsapp' in user else False
    }

    brands_data = ["label_" + str(brand.name).replace(" ","_").strip() for brand in Brands.objects()]
    for key in brands_data:
        data[key] = json.loads(user["brand"])[key] if key in json.loads(user["brand"]) else "NA",

    return jsonify(data)
def db(bare_db, admin_user_details):
    """An active database instance with one admin user"""
    # must start with an admin user
    encrypted_admin_details = {
        **admin_user_details,
        "password": encrypt(admin_user_details["password"]),
    }
    with Session(bare_db._engine, future=True) as session:
        session.add(User(**encrypted_admin_details))
        session.commit()
    return bare_db
def signin():
    form = LoginForm(request.form)

    if current_user.is_authenticated == True:
        return redirect("/")

    if request.method == 'POST' and form.validate_on_submit():
        if (re.search(r'[A-Za-z]{3}\d*', str(form.loginid.data))):
            checkuser = User.objects(uid=form.loginid.data).first()
        else:
            checkuser = User.objects(mobilenumber=form.loginid.data).first()

        if checkuser and bcrypt.check_password_hash(checkuser['password'],
                                                    form.password.data):
            login_user(checkuser)
            return redirect("/")

        flash("login id / Password Invalid!", "error")

    return render_template('auth/sign-in.html', form=form)
Beispiel #8
0
def getallparties():
    users = User.objects(role__lte=current_user.role, status__ne=userstatus['deleted'], pk__ne=current_user.pk).only('uid','fullname','mobilenumber','gstin','openingbalance','category','role','status','branch','group','companyname', 'userclass')
    users = [json.loads(user.to_json(follow_reference=True)) for user in users]
    for index, user in enumerate(users):
        if 'group' not in user:
            user['group'] = {"name": ""}
        if 'branch' not in user:
            user['branch'] = {"code": ""}
        user['role'] = list(roles.keys())[list(roles.values()).index(user['role'])].capitalize()
        user['status'] = list(userstatus.keys())[list(userstatus.values()).index(user['status'])].capitalize()
    return jsonify(data=users)
    def add_user(self, token: Token, user_details: Dict) -> UserDetails:
        """Adds a user to the database"""

        user_id, token = validate_token(token)
        if not self.check_if_username_is_unique(user_details["username"]):
            raise DuplicateUsernameError
        with Session(self._engine, future=True) as session:
            self._require_admin_user(
                user_id=user_id,
                session=session,
            )

            for field in user_details.keys():
                if field in PROTECTED_FIELDS:
                    raise UnauthorizedUserError

            # don't mutate original dict
            user_details = {
                **user_details,
                "id": str(uuid4()),
                "type": "contrib",
                "confirmed": False,
                "deactivated": False,
            }

            # handle password
            password = user_details["password"]
            user_details["password"] = encrypt(password)
            # create user object
            new_user = User(**user_details)

            session.add(new_user)
            session.commit()

            # TODO: when email service is enabled, add call here to send a token to
            # the provided email address.
            new_user_token = get_token(new_user.id)
            log.info(f"New User Token is: {new_user_token}")

            return token, new_user.to_dict()
def load_user(user_id):
    return User.objects(pk=user_id).first()
def editprofile():

    brands_data = [
        "label_" + str(brand.name).replace(" ", "_").strip()
        for brand in Brands.objects()
    ]
    labelsFields = []
    for key in brands_data:
        setattr(
            EditUserInfoForm, key,
            StringField(" ".join(str(key).split("_")[1:]) + " Label",
                        id=key,
                        _name=key))

    userinfoform = EditUserInfoForm(request.form)
    userpasswordform = EditUserPasswordForm(request.form)
    if request.method == 'GET':
        for key in userinfoform:
            if str(key.id).startswith("label_"):
                exec(
                    "userinfoform.%s.data = json.loads(current_user.brand)['%s'] if '%s' in json.loads(current_user.brand).keys() else 'NA'"
                    % (key.id, key.id, key.id))
                labelsFields.append(key)
            elif key.id not in [
                    "samebilladdress", "csrf_token", "whatsapp",
                    "submituserinfo"
            ]:
                exec("userinfoform.%s.data = current_user.%s" %
                     (key.id, key.id))
        userinfoform.samebilladdress.data = True if current_user.communicationaddress == current_user.billingaddress else False
        userinfoform.whatsapp.data = True if current_user.whatsapp else False

    if request.method == 'POST' and userinfoform.submituserinfo.data and userinfoform.validate(
    ):
        if userinfoform.gstin.data != "":
            # Validate GST Number Pattern.
            if (not gst.checkpattern(userinfoform.gstin.data)):
                flash("Invalid GST Pattern!", "error")
                return redirect(url_for('general.parties'))

            # Validate GST Number Checksum.
            if (not gst.checkchecksum(userinfoform.gstin.data)):
                flash("Invalid GST Number!", "error")
                return redirect(url_for('general.parties'))

        temp_labels = {}
        for key in userinfoform.data.items():
            if key[0].startswith('label_'):
                temp_labels[key[0]] = key[1] if key[1] else "NA"

        user = User.objects(uid=userinfoform.uid.data).update(
            category=userinfoform.category.data,
            companyname=userinfoform.companyname.data
            if userinfoform.category.data == "company" else "",
            fullname=userinfoform.fullname.data,
            email=userinfoform.email.data if userinfoform.email.data else None,
            mobilenumber=userinfoform.mobilenumber.data,
            whatsapp=userinfoform.whatsapp.data,
            gstin=userinfoform.gstin.data,
            communicationaddress=userinfoform.communicationaddress.data,
            billingaddress=userinfoform.billingaddress.data,
            state=userinfoform.state.data,
            city=userinfoform.city.data,
            pincode=userinfoform.pincode.data,
            brand=json.dumps(temp_labels))
        if user:
            flash("Profile Updated Successfully", "success")
            return redirect(url_for('dashboard.editprofile'))

        flash("Failed to Profile", "error")
        return redirect(url_for('dashboard.editprofile'))

    if request.method == 'POST' and userpasswordform.submituserpassword.data and userpasswordform.validate(
    ):
        if bcrypt.check_password_hash(current_user.password,
                                      userpasswordform.oldpassword.data):

            if userpasswordform.newpassword.data != userpasswordform.retypenewpassword.data:
                flash("Password and Confirm Password did't Match", "error")
                return redirect(url_for('dashboard.editprofile'))

            user = User(pk=current_user.pk).update(
                password=bcrypt.generate_password_hash(
                    userpasswordform.newpassword.data).decode("utf-8"))

            if user:
                flash("Password Updated Successfully", "success")
                return redirect(url_for('auth.logout'))

            flash("Failed to Update Password", "error")
            return redirect(url_for('dashboard.editprofile'))

        flash("Incorrect Old Password", "error")
        return redirect(url_for('dashboard.editprofile'))

    return render_template('dashboard/edit-profile.html',
                           userinfoform=userinfoform,
                           userpasswordform=userpasswordform,
                           brands_data=labelsFields)
Beispiel #12
0
def parties():
    brands_data = ["label_" + str(brand.name).replace(" ","_").strip() for brand in Brands.objects()]

    for key in brands_data:
        setattr(PartyForm, key, StringField(key))

    form = PartyForm(request.form)
    form.branch.choices = [("", "Select Branch")] + [(str(branch.pk), branch.code) for branch in Branches.objects()]
    form.group.choices = [("", "Select Group")] + [(str(group.pk), group.name) for group in User_Groups.objects()]
    
    if request.method == 'POST' and form.validate_on_submit():
        if form.gstin.data != "":
            # Validate GST Number Pattern.
            if (not gst.checkpattern(form.gstin.data)):
                flash("Invalid GST Pattern!", "error")
                return redirect(url_for('general.parties'))

            # Validate GST Number Checksum.
            if (not gst.checkchecksum(form.gstin.data)):
                flash("Invalid GST Number!", "error")
                return redirect(url_for('general.parties'))

        if form.id.data == "new":
            existing_user = User.objects(mobilenumber=form.mobilenumber.data).first()

            if existing_user is None:

                if not checkSMSBalance(mode="sms"):
                    flash("SMS Limit Exceeded", "error")
                    return redirect(url_for('general.parties'))

                password = generate_password(8)
                temp_labels = {}
                for key in form.data.items():
                    if key[0].startswith('label_'):
                        temp_labels[key[0]] = key[1] if key[1] else "NA"
                uid = str(form.city.data)[0:3].upper() + str(getnextid(form.city.data))
                user = User(
                    uid = uid,
                    role = int(form.role.data),
                    branch = Branches.objects(pk=form.branch.data).first().to_dbref() if form.branch.data else None,
                    category = form.category.data,
                    group = User_Groups.objects(pk=form.group.data).first().to_dbref() if form.group.data else None,
                    companyname = form.companyname.data,
                    userclass = form.userclass.data,
                    fullname = form.fullname.data,
                    password = bcrypt.generate_password_hash(password),
                    email = form.email.data if form.email.data else None,
                    mobilenumber = form.mobilenumber.data,
                    whatsapp = form.whatsapp.data,
                    gstin = form.gstin.data,
                    communicationaddress = form.billingaddress.data,
                    billingaddress = form.billingaddress.data,
                    brand = json.dumps(temp_labels),
                    state = form.state.data,
                    city = form.city.data,
                    pincode = form.pincode.data,
                    openingbalance = form.openingbalance.data if form.openingbalance.data else 0,
                    openingbalancedate = str(datetime.strptime(form.openingbalancedate.data, "%d/%m/%Y").timestamp()),
                    status = int(form.status.data)
                ).save()

                if user:
                    MSG = "Hey {}, Welcome to Paras Doors.\r\nFrom now you can login to www.parasdoors.com using\r\nLogin ID: {} / {},\r\nPassword: {}".format(form.fullname.data, uid, form.mobilenumber.data, password)
                    status = sendSMS(mobileNumber=form.mobilenumber.data, MSG=MSG, mode="sms")
                    if not status:
                        flash("Failed to Send SMS to User", "error")
                    flash("New User Added Successfully", "success")
                    return redirect(url_for('general.parties'))
                
                flash("Failed to Create User", "error")
                return redirect(url_for('general.parties'))

            flash("User Already Exists!", "error")
            return redirect(url_for('general.parties'))

        else:
            temp_labels = {}
            for key in form.data.items():
                if key[0].startswith('label_'):
                    temp_labels[key[0]] = key[1] if key[1] else "NA"
            existing_user = User.objects(mobilenumber=form.mobilenumber.data).first()
            if (existing_user is None) or (str(existing_user['id']) == form.id.data):
                user = User(pk=form.id.data).update(
                    role = int(form.role.data),
                    branch = Branches.objects(pk=form.branch.data).first().to_dbref() if form.branch.data else None,
                    category = form.category.data,
                    group = User_Groups.objects(pk=form.group.data).first().to_dbref() if form.group.data else None,
                    companyname = form.companyname.data if form.category.data == "company" else "",
                    userclass = form.userclass.data,
                    fullname = form.fullname.data,
                    email = form.email.data if form.email.data else None,
                    mobilenumber = form.mobilenumber.data,
                    whatsapp = form.whatsapp.data,
                    gstin = form.gstin.data,
                    communicationaddress = form.billingaddress.data,
                    billingaddress = form.billingaddress.data,
                    state = form.state.data,
                    city = form.city.data,
                    pincode = form.pincode.data,
                    brand = json.dumps(temp_labels),
                    openingbalance = form.openingbalance.data,
                    openingbalancedate = str(datetime.strptime(form.openingbalancedate.data, "%d/%m/%Y").timestamp()),
                    status = int(form.status.data)
                )

                if user:
                    flash("Updated User Successfully", "success")
                    return redirect(url_for('general.parties'))

                flash("Failed to Create User", "error")
                return redirect(url_for('general.parties'))
            
            flash("Mobile Number Already Exist", "error")
            return redirect(url_for('general.parties'))

    return render_template('dashboard/general/parties.html', form=form, brands_data=brands_data)
Beispiel #13
0
           "GRAY": "#808080",
           "BLACK": "#000000",
           "RED": "#FF0000",
           "MAROON": "#800000",
           "YELLOW": "#FFFF00",
           "OLIVE": "#808000",
           "LIME": "#00FF00",
           "GREEN": "#008000",
           "AQUA": "#00FFFF",
           "TEAL": "#008080",
           "BLUE": "#0000FF",
           "NAVY": "#000080",
           "FUCHSIA": "#FF00FF",
           "PURPLE": "#800080"}

if not User.objects(uid="dev"):
    User(
        uid="dev",
        role=128,
        category="individual",
        companyname="",
        fullname="Supreeth Kumar Y P",
        # Password 12345678
        password="******",
        email="*****@*****.**",
        mobilenumber="9743977577",
        gstin="",
        communicationaddress="Chitradurga",
        billingaddress="Chitradurga",
        state="Karnataka",
        city="Chitradurga",