Esempio n. 1
0
def add_meal():
    form = AddMeal()
    with db_session:
        form.unity.choices = [(u.symbol, u.symbol) for u in Unity.select()]
        form.category.choices = [(c.id, c.description)
                                 for c in Category.select()]
        form.subcategory.choices = [(s.id, s.description)
                                    for s in SubCategory.select()]
    if form.validate_on_submit():
        with db_session:
            meal = Meal(buy_date=form.buy_date.data,
                        expiration_date=form.expiration_date.data,
                        freezing_date=form.freezing_date.data,
                        description=form.description.data,
                        units=form.units.data,
                        weight=form.weight.data,
                        unity=Unity.select(
                            lambda u: u.symbol == form.unity.data).first(),
                        category=Category.select(
                            lambda u: u.id == form.category.data).first(),
                        subcategory=SubCategory.select(
                            lambda u: u.id == form.subcategory.data).first(),
                        drawer=form.drawer.data,
                        user=current_user)
            print(meal)
            commit()
        return redirect('/index')
    return render_template('add_meal.html', title='Add Meal', form=form)
Esempio n. 2
0
def delete_meal():
    form = DeleteMeal()
    if form.validate_on_submit():
        with db_session:
            Meal[form.meal_id.data].delete()
            commit()
        return redirect('/index')
    return render_template('delete_meal.html', title='Add Meal', form=form)
Esempio n. 3
0
def register():
    if current_user.is_authenticated:
        return redirect('/index')
    form = RegistrationForm()
    if form.validate_on_submit():
        with db_session:
            user = User(name=form.name.data, password=form.password.data)
            commit()
        flash('Congratulations, you are now a registered user!')
        return redirect('/login')
    return render_template('register.html', title='Register', form=form)
Esempio n. 4
0
async def validate(email: EmailStr, code: str):
    if not check_email2(email):
        raise HTTPException(status_code=400, detail="Email not registered")
    if check_validation_code(email, code):
        with db_session:
            user = db.DB_User.get(email=email)
            user.set(email_confirmed=True)
            commit()
        return {"Validated!"}
    else:
        raise HTTPException(status_code=404, detail="Invalid Code")
Esempio n. 5
0
def call(program, argv):
    parser = ArgumentParser(prog=program)

    parser.add_argument("dbid", help="DBID of profile", type=int)

    sources = parser.add_mutually_exclusive_group(required=True)
    sources.add_argument("-u", "--url", help="url of skin", dest="url")
    sources.add_argument("-f", help="file path of skin", dest="path")
    sources.add_argument("--delete",
                         help="reset profile skin",
                         action="store_true")

    parser.add_argument("--slim", help="slim model", action="store_true")

    args = parser.parse_args(argv)

    profile: Profile = Profile.get(id=args.dbid)
    if profile is None:
        print("No profile matches that DBID!")
        exit(1)

    if args.url is not None:
        fd = BytesIO(get(args.url).content)
    elif args.path is not None:
        fd = Path(args.path)
    elif not args.delete:
        print("You must specify a file!")
        exit(1)

    if args.delete:
        profile.reset_skin()
    else:
        try:
            image: Image = Image.open(fd)
        except (FileNotFoundError, UnidentifiedImageError, ValueError):
            print(INVALID_IMAGE.message)
            exit(1)

        try:
            profile.update_skin(image, "slim" if args.slim else "")
        except ValueError:
            print(INVALID_SKIN.message)
            exit(1)

    try:
        commit()
    except Exception as e:
        print(e)
        exit(1)

    if not args.delete:
        print(f"Texture name: {profile.profile_skin.name}")
Esempio n. 6
0
async def register(user: User = me):
    """
    User register endpoint
    Params: User data->
      * username : str
      * email : EmailStr
      * password : str
    """
    if not check_username(user) and not check_email(user):
        with db_session:
            db.DB_User(
                username=user.username,
                email=user.email,
                hashed_password=get_password_hash(user.password),
                email_confirmed=False,
                icon=user.icon,
                creation_date=datetime.today().strftime("%Y-%m-%d"),
            )
            commit()

        if user in test_users:
            with db_session:
                user = db.DB_User.get(email=user.email)
                user.set(email_confirmed=True)
                commit()
            return {"Listo mostroo"}
        else:
            v = Validation()
            v.send_mail(user.email)
        # background_t.add_task(validator.send_mail, user.email)

        return {
            "message":
            user.username + ", a verification email has" + " been sent to " +
            user.email
        }
    else:
        msg = ""
        if check_username(user):
            msg += "Username already registered "
            raise HTTPException(status_code=409,
                                detail="Username already registered ")
        elif check_email(user):
            msg += "Email already registered"
            raise HTTPException(status_code=409,
                                detail="Email already registered")
        return {msg}
Esempio n. 7
0
 def __add__(self, *args, **kwargs):
     if not kwargs or len(args) > 0:
         if self.cls.__name__ == 'Organisation':
             kwargs = {
                 'Name': args[0],
                 'Description': args[1],
                 'Position': args[2]
             }
     just_now = now()
     kwargs.update({
         'created': just_now,
         'modified': just_now,
         'accessed': just_now
     })
     current = self.cls(**kwargs)
     commit()
     kwargs.update({'id': current.id})
     return kwargs
Esempio n. 8
0
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="DBID of account", type=int)

    uuids = parser.add_mutually_exclusive_group()
    uuids.add_argument("-u", "--uuid", help="change account UUID", type=UUID)
    uuids.add_argument("-ru",
                       "--random-uuid",
                       help="refresh account UUID",
                       action="store_true")

    parser.add_argument("-n", "--username", help="change account username")
    parser.add_argument("-p", "--password", help="change account password")
    parser.add_argument("--delete",
                        help="delete this account",
                        action="store_true")

    args = parser.parse_args(argv)

    account: Account = Account.get(id=args.dbid)
    if account is None:
        print("No account matches that DBID!")
        exit(1)

    if args.uuid is not None:
        account.uuid = args.uuid
    if args.random_uuid:
        account.uuid = uuid4()
    if args.username is not None:
        account.username = args.username
    if args.password is not None:
        account.password = password_hash(args.password)
    if args.delete:
        account.delete()

    try:
        commit()
    except Exception as e:
        print(e)
        exit(1)

    if not args.delete:
        print(str(account))
Esempio n. 9
0
async def register_sample_users():
    if sample_users_registered():
        return

    for user in test_users:
        with db_session:
            db.DB_User(
                username=user.username,
                email=user.email,
                hashed_password=get_password_hash(user.password),
                email_confirmed=False,
                icon=user.icon,
                creation_date=datetime.today().strftime("%Y-%m-%d"),
            )

            u = db.DB_User.get(email=user.email)
            u.set(email_confirmed=True)

            commit()
    print("Sample users registered!")
Esempio n. 10
0
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="DBID of profile", type=int)

    uuids = parser.add_mutually_exclusive_group()
    uuids.add_argument("-u", "--uuid", help="change profile UUID", type=UUID)
    uuids.add_argument("-ru",
                       "--random-uuid",
                       help="refresh profile UUID",
                       action="store_true")

    parser.add_argument("-a", "--agent", help="change profile agent")
    parser.add_argument("--delete",
                        help="delete this profile",
                        action="store_true")

    args = parser.parse_args(argv)

    profile: Profile = Profile.get(id=args.dbid)
    if profile is None:
        print("No profile matches that DBID!")
        exit(1)

    if args.uuid is not None:
        profile.uuid = args.uuid
    if args.random_uuid:
        profile.uuid = uuid4()
    if args.agent is not None:
        profile.agent = args.agent
    if args.delete:
        profile.delete()

    try:
        commit()
    except Exception as e:
        print(e)
        exit(1)

    if not args.delete:
        print(str(profile))
Esempio n. 11
0
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="DBID of profile", type=int)
    parser.add_argument("name", help="new name of profile")

    parser.add_argument("--bypass-wait",
                        help="do not wait 30 days between name changes",
                        action="store_true")
    parser.add_argument("--bypass-lock",
                        help="do not wait 37 days for profile name to unlock",
                        action="store_true")

    args = parser.parse_args(argv)

    profile: Profile = Profile.get(id=args.dbid)
    if profile is None:
        print("No profile matches that DBID!")
        exit(1)

    if not (args.bypass_wait or profile.can_change_name()):
        print(
            f"Cannot change name until {profile.time_of_next_name_change()}. Wait {profile.time_to_name_change()}."
        )
        exit(1)

    if not (args.bypass_lock
            or profile.is_name_available_for_change(args.name)):
        print("Name not available.")
        exit(1)

    profile.change_name(args.name)

    try:
        commit()
    except Exception as e:
        print(e)
        exit(1)

    print(profile)