Ejemplo n.º 1
0
def done(message):
    if active:
        user = Users.get_or_none(tel_id=message.from_user.id)
        if user == None:
            Users.create(tel_id=message.from_user.id,
                         name=message.from_user.first_name,
                         username=message.from_user.username)
            user = Users.get(tel_id=message.from_user.id)
            bot.send_message(message.chat.id,
                             user.name + " был зарегистрирован.")

        if not user.done_today:
            if user.sick:
                bot.reply_to(message, "Видимо вы больше не больны.")
                user.sick = False
            user.done_today = True
            user.done += 1
            user.save()
            bot.reply_to(
                message, f"Тренировка засчитана! Всего выполнено: {user.done}")
            fileID = message.photo[-1].file_id
            file = bot.get_file(fileID)
            downloaded = bot.download_file(file.file_path)
            new_img = open("received_img.jpg", "wb")
            new_img.write(downloaded)
            new_img.close()
            bot.reply_to(
                message,
                f"Предположитнльная продлжительность: {recognise(Image.open('received_img.jpg'))}."
            )
        else:
            bot.reply_to(
                message,
                f"2 раза за день перебор) Всего выполнено: {user.done}")
Ejemplo n.º 2
0
def register_user(username, password, passphrase=None, verbose=False):
    '''
    Register a new user
    '''
    if passphrase is None:
        passphrase = password
    crypt.rsa_gen(username, passphrase, verbose=verbose)
    hashed_password, salt = crypt.salt_hash(password)
    Users.create(
        username=username,
        salt=salt,
        password=hashed_password
    )
Ejemplo n.º 3
0
def test_role_auth(bearer_auth, app, db):
    """Check that role-based authorization works as expected."""
    profile = {"email": EMAIL}

    with app.test_request_context():
        # Unregistered user should not be authorized to do anything to any resource except "users"
        with pytest.raises(Unauthorized, match="not registered"):
            bearer_auth.role_auth(profile, [], "some-resource", "some-http-method")

        # Unregistered user should not be able to GET users
        with pytest.raises(Unauthorized, match="not registered"):
            bearer_auth.role_auth(profile, [], "users", "GET")

        # Unregistered user should be able to POST users
        assert bearer_auth.role_auth(profile, [], "new_users", "POST")

    # Add the user to the db but don't approve yet
    Users.create(profile)

    with app.test_request_context():
        # Unapproved user isn't authorized to do anything
        with pytest.raises(Unauthorized, match="pending approval"):
            bearer_auth.role_auth(profile, [], "new_users", "POST")

        # Give the user a role but don't approve them
        db.query(Users).filter_by(email=EMAIL).update(dict(role="cimac-user"))
        db.commit()

        # Unapproved user *with an authorized role* still shouldn't be authorized
        with pytest.raises(Unauthorized, match="pending approval"):
            bearer_auth.role_auth(profile, ["cimac-user"], "new_users", "POST")

    # Approve the user
    db.query(Users).filter_by(email=EMAIL).update(dict(approval_date=datetime.now()))
    db.commit()

    with app.test_request_context():
        # If user doesn't have required role, they should not be authorized.
        with pytest.raises(Unauthorized, match="not authorized to access"):
            bearer_auth.role_auth(
                profile, ["cidc-admin"], "some-resource", "some-http-method"
            )

        # If user has an allowed role, they should be authorized
        assert bearer_auth.role_auth(
            profile, ["cimac-user"], "some-resource", "some-http-method"
        )

        # If the resource has no role restrictions, they should be authorized
        assert bearer_auth.role_auth(profile, [], "some-resource", "some-http-method")
Ejemplo n.º 4
0
def addUser(name, emailIn, passIn):
    from models import Users
    #hash the password like grandma makes a hashbrown egg dish
    hash = hashPass(passIn)
    #create user
    user = Users.create(email=emailIn, passHash=hash, person=name)
    user.save()
Ejemplo n.º 5
0
 def create(cls, request: Request, **kwargs):
     """ Creating new user """
     login = request.get("login")
     name = request.get("name")
     country_id = int(request.get("country_id")) if request.get(
         "country_id", None) else None
     city_id = int(request.get("city_id")) if request.get("city_id",
                                                          None) else None
     return Users.create(login, name, country_id, city_id)
Ejemplo n.º 6
0
def process_new_user():
    print(f"ROUTE: process_new_user")
    errors = Users.validate(request.form)
    if errors:
        for error in errors:
            flash(error)
        return redirect('/register')

    user_id = Users.create(request.form)
    session['user_id'] = user_id
    return redirect(url_for("show_dashboard"))
Ejemplo n.º 7
0
def create_movie():
    if not request.is_json:
        return 'You should send JSON data', 400
    data = request.json
    if type(data) == list:
        return 'You should send JSON dictionary', 400
    if 'name' not in data:
        return '"Name" field is required', 400
    name = data.get('name')
    user = Users.create(name=name)
    return jsonify(user.to_dict()), 201
Ejemplo n.º 8
0
def register():
    _json = request.json
    name = _json['name']
    email = _json['email']
    password = _json['password']

    if name and email and password:
        # signup a user
        return Users.create({
            'name': name,
            'email': email,
            'password': password
        })
    else:
        return not_found()
Ejemplo n.º 9
0
 def register(phone,password):
     register_user=Users.select().where(Users.phone==phone).first()
     if register_user:
         return {
             'code':101,
             'data':None,
             'message':u' 用户已存在'
         }
     else:
         new_user=Users.create(phone=phone,password=Users.hash_password(password))
         new_user.save()
     return {
         'code': 0,
         'data': None,
         'message': u'注册成功'
     }
Ejemplo n.º 10
0
def new_user(resp):
	'''
	Creates a new user if the user had not previously signed in with openid. Otherwise, just sets the session to the correct user.
		arg: resp - the response from the openid provider

		return: the view to display (redirected to originally asked for page)
	'''
	session['openid'] = resp.identity_url
	user = Users.get_by_openid(session['openid'])
	#if we haven't created the user before, create it
	if user is None:
		user = Users.create(resp.fullname, resp.email)
		Users.create_openid_association(user.id, session['openid'])
		session['user'] = user
	else:
		session['user'] = user

	return redirect(oid.get_next_url())
Ejemplo n.º 11
0
 def post(self):
     email = self.get_body_argument('email')
     username = self.get_body_argument('username')
     password = self.get_body_argument('password')
     passwordConfirm = self.get_body_argument('passwordConfirm')
     messages = []
     user = self.user_exists(email)
     # Validations
     # if user exists
     if user:
         messages.append("Email already exists")
     # if email invalid format
     if not validate_email(email):
         messages.append("Invalid email address")
     # checks if username is not an empty string
     if username == "":
         messages.append("Input username")
     # checks if passwords match
     if password != passwordConfirm:
         messages.append("Passwords do not match")
     # checks password length is valid
     if len(password) < 8:
         messages.append("Password length must by greater than 7")
     # if errors occured, display errors and redirect to signup
     if messages:
         return self.render_template("signup.html",
                                     {'messages': tuple(messages)})
     # create hashed & salted user password
     # tornado.escape.utf8 converts string to byte string
     # https://github.com/pyca/bcrypt#password-hashing
     hashed_password = bcrypt.hashpw(tornado.escape.utf8(password),
                                     bcrypt.gensalt())
     # create user
     user = Users.create(email=email,
                         username=username,
                         hashed_password=hashed_password)
     self.set_secure_cookie("blog_user", str(user.id))
     return self.redirect("/")
Ejemplo n.º 12
0
InstagramAPI = InstagramAPI("testing_accaunt", "cgfhnfrxtvgbjy1922")
InstagramAPI.login()
InstagramAPI.searchUsername('princegeorgii')
media_id = InstagramAPI.LastJson
followers = InstagramAPI.getTotalFollowers(media_id['user']['pk'])
followers_ids = []
for follower in followers:
    followers_ids.append(follower['pk'])
    try:
        Users.get(Users.pk == follower['pk'])
    except Users.DoesNotExist:
        Users.create(pk=follower['pk'],
                     full_name=str(follower['full_name']),
                     has_anonymous_profile_picture=str(
                         follower['has_anonymous_profile_picture']),
                     is_private=str(follower['is_private']),
                     is_verified=str(follower['is_verified']),
                     profile_pic_url=str(follower['profile_pic_url']),
                     username=str(follower['username']),
                     insta_link='https://www.instagram.com/' +
                     str(follower['username']) + '/')
date = datetime.datetime.now()

for item in Profile.select().order_by(Profile.id.desc()).limit(1):
    previous_followers = list(map(int, item.followers.split()))
unfollow = set(previous_followers) - set(followers_ids)
follow = set(followers_ids) - set(previous_followers)
unfollow_len = len(unfollow)
follow_len = len(follow)
follow_str = " ".join(str(pk) for pk in follow)
unfollow_str = " ".join(str(pk) for pk in follow)
Friendship.create(
Ejemplo n.º 13
0
 def add_user(message, ua, ru, uk, us):
     try:
         user = Users.create(user_id=message.chat.id, ua=ua, ru=ru, uk=uk, us=us)
         return True
     except:
         return False