Beispiel #1
0
def test_get_by_email(client):
    """ Get user by email ."""
    user = User('*****@*****.**', 'foo')
    user.save()

    retrieved = User.get_by_email(user.email)
    assert retrieved == user
Beispiel #2
0
def test_create_short_id(client, mocker):
    user = User('*****@*****.**', 'foo')
    user.save()
    short_url = Url(long_url='https://google.com',
                    user=user,
                    short_id=Url.create_id())
    short_url.save()
    assert short_url.short_id
Beispiel #3
0
def test_get_by_short_url(client):
    """ Get url by short url. """
    user = User('*****@*****.**', 'foo')
    user.save()
    new_short_url = Url(long_url='http://google.com',
                        user=user,
                        short_id=Url.create_id())
    new_short_url.save()

    retrieved = Url.get_by_short_url(new_short_url.get_short_url())
    assert retrieved == new_short_url
Beispiel #4
0
    def post(self):
        dados = request.json #pega apenas o corpo da requisição, ou seja, o json, para poder fazer um POST desses dados

        nome = dados.get('nome')
        email = dados.get('email') #pega o nome que esta no formato json
        password = dados.get('password')
        estado = dados.get('estado')
        cidade = dados.get('cidade')
        cep = dados.get('cep')
        endereço = dados.get('endereço')
        bloco_apartamento = dados.get('bloco_apartamento')
        

        if not email or not password or not nome or not estado or not cidade or not cep or not endereço or not bloco_apartamento:
            return {"error": "Email, nome, senha e dados de endereço obrigatórios!"},400

        if User.query.filter_by(email=email).first():
            return {"error": "Já existe um usuário cadastrado com este email!"},400

        if len(email)>40:
            return {"error": "String de email excede o tamanho de 40 caracteres!"},400
        
        if len(nome)>50:
            return {"error": "String de nome excede o tamanho de 50 caracteres!"},400
        
        if len(estado)>20:
            return {"error": "String de estado excede o tamanho de 20 caracteres!"},400

        if len(password)>200:
            return {"error": "String de senha excede o tamanho de 50 caracteres!"},400

        if not isinstance(email,str) or not isinstance(password,str) or not isinstance(nome,str) or not isinstance(estado,str) or not isinstance(cidade,str) or not isinstance(cep,int) or not isinstance(endereço,str) or not isinstance(bloco_apartamento,str):
            return {"error": "Algum tipo inserido é inválido!"},400
        
        password_hash = bcrypt.hashpw(password.encode(),bcrypt.gensalt())

        user = User(nome=nome,email=email,password_hash=password_hash,estado=estado,cidade=cidade,cep=cep,endereço=endereço,bloco_apartamento=bloco_apartamento)

        db.session.add(user)
        db.session.commit()

        msg = Message(
            sender='*****@*****.**',
            recipients=[email],
            subject='Obrigado pelo Cadastro - Naomi', 
            html = render_template('email1.html',nome=nome) #por configuração esse render_template já busca pelo folder templates
        )

        mail.send(msg)

        return user.json(),200
def init_random_data():
    password_hash = '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'
    users = [None, None, None]
    for i in range(0, 3):
        rand_int_str = str(random.randint(1, 1000))
        users[i] = User(username='******' + rand_int_str,
                        first_name=rand_int_str,
                        last_name=rand_int_str,
                        email=f'test_{rand_int_str}@example.com',
                        password_hash=password_hash,
                        status=f'I am a test user {rand_int_str}',
                        registered_at=datetime.now())
        print(users[i])
        db.session.add(users[i])
    posts = [None, None, None]
    for i in range(0, 3):
        rand_int_str = str(random.randint(1, 1000))
        posts[i] = Post(title=f'Test post {rand_int_str}',
                        text=f'Example post with random int {rand_int_str}',
                        author=users[i],
                        published_at=datetime.now())
        print(posts[i])
        db.session.add(posts[i])
    for i in range(0, 3):
        rand_int_str = str(random.randint(1, 1000))
        comment = Comment(
            text=f'Test comment for post {i}, rand int {rand_int_str}',
            author=users[i],
            post=posts[i],
            published_at=datetime.now())
        print(comment)
        db.session.add(comment)
    db.session.commit()
    print(Post.query.all())
    return "Initialized random posts, users and comments"
Beispiel #6
0
def insert_users():
    reader = csv.reader(open(os.path.join(__location__, 'users.csv')),
                        delimiter=',',
                        quotechar='"')
    for row in reader:
        username = (row[0] + '.' + row[1]).lower()

        if User.find(username=username) is None:
            User(email=row[2],
                 password=row[3],
                 status=row[6],
                 firstname=row[0],
                 lastname=row[1],
                 username=username,
                 employee_id=row[4],
                 role='administrator').save()
    print 'inserted users.'
Beispiel #7
0
def insert_user_departments():
    users = User.list()
    department_A = Department.find(id=60430)
    department_B = Department.find(id=60350)
    for user in users:
        user.departments.append(department_A)
        user.departments.append(department_B)

    print 'associated users with departments'
Beispiel #8
0
def insert_user_departments():
    users = User.list()
    department_A = Department.find(id=60430)
    department_B = Department.find(id=60350)
    for user in users:
        user.departments.append(department_A)
        user.departments.append(department_B)

    print 'associated users with departments'
Beispiel #9
0
 def regester():
     email = request.form.get('email')
     username = request.form.get('username')
     password = request.form.get('password')
     user = User(email=email,
                 username=username,
                 password=User.set_password(password))
     result = user.add(user)
     print(result)
     if user.id:
         returnUser = {
             'id': user.id,
             'username': user.username,
             'email': user.email,
             'login_time': user.login_time
         }
         return jsonify(common.trueReturn(returnUser, '用户注册成功'))
     else:
         return jsonify(common.falseReturn('', '用户注册失败'))
Beispiel #10
0
 def get():
     result = Auth.identify(Auth, request)
     if (result['status'] and result['data']):
         user = User.get(User, result['data'])
         returnUser = {
             'id': user.id,
             'username': user.username,
             'email': user.email,
             'login_time': user.login_time
         }
         result = common.trueReturn(returnUser, '请求成功')
     return jsonify(result)
Beispiel #11
0
 def authenticate(self, username, password):
     userInfo = User.query.filter_by(username=username).first()
     if userInfo is None:
         return jsonify(common.falseReturn('', '找不到用户'))
     else:
         if (User.check_password(userInfo.password, password)):
             login_time = int(time.time())
             userInfo.login_time = login_time
             userInfo.update()
             token = self.encode_auth_token(userInfo.id, login_time)
             return jsonify(common.trueReturn(token.decode(), '登录成功'))
         else:
             return jsonify(common.falseReturn('', '密码不正确'))
Beispiel #12
0
def insert_users():
    reader = csv.reader(open(os.path.join(__location__, 'users.csv')), delimiter=',', quotechar='"')
    for row in reader:
        username = (row[0] + '.' + row[1]).lower()

        if User.find(username=username) is None:
            User(
                email=row[2],
                password=row[3],
                status=row[6],
                firstname=row[0],
                lastname=row[1],
                username=username,
                employee_id=row[4],
                role='administrator'
            ).save()
    print 'inserted users.'
Beispiel #13
0
def register_url():
    logging.info('Processing shorten request')
    url = request.json.get('url')
    current_user = User.get_by_email(get_jwt_identity())
    if not current_user:
        abort(HTTPStatus.BAD_REQUEST, INVALID_ACCOUNT)

    # create short url
    new_short_url = Url(user=current_user,
                        long_url=url,
                        short_id=Url.create_id())
    new_short_url.save()

    response = create_response({'short_url': new_short_url.get_short_url()},
                               SHORT_URL_CREATED, HTTPStatus.CREATED)

    return response
Beispiel #14
0
def create_user():
    username = request.json.get('username')
    first_name = request.json.get('first_name')
    last_name = request.json.get('last_name')
    email = request.json.get('email')
    password = request.json.get('password')
    can_create_users = request.json.get('can_create_users')
    registered_at = datetime.now()
    password_hash = sha256(password.encode('utf-8')).hexdigest()
    print(password_hash)
    user = User(username=username,
                first_name=first_name,
                last_name=last_name,
                email=email,
                registered_at=registered_at,
                can_create_users=can_create_users,
                password_hash=password_hash)
    db.session.add(user)
    db.session.commit()
    return {'status': 'success'}
Beispiel #15
0
def create_user():
    username = request.form.get('username')
    first_name = request.form.get('first_name')
    last_name = request.form.get('last_name')
    email = request.form.get('email')
    # TODO: Maybe it will be more secure to transfer hash of password, not password itself
    # almost no need if HTTPS is used since client-side code is easily visible
    password = request.form.get('password')
    status = request.form.get('status')
    registered_at = datetime.now()
    password_hash = sha256(password.encode('utf-8')).hexdigest()
    print(password_hash)
    user = User(username=username,
                first_name=first_name,
                last_name=last_name,
                email=email,
                registered_at=registered_at,
                status=status,
                password_hash=password_hash)
    db.session.add(user)
    db.session.commit()
    return 'ok'
Beispiel #16
0
 def identify(self, request):
     auth_header = request.headers.get('Authorization')
     if (auth_header):
         auth_tokenArr = auth_header.split(" ")
         if (not auth_tokenArr or auth_tokenArr[0] != 'JWT'
                 or len(auth_tokenArr) != 2):
             result = common.falseReturn('', '请传递正确的验证头信息')
         else:
             auth_token = auth_tokenArr[1]
             payload = self.decode_auth_token(auth_token)
             if not isinstance(payload, str):
                 user = User.get(User, payload['data']['id'])
                 if (user is None):
                     result = common.falseReturn('', '找不到该用户信息')
                 else:
                     if (user.login_time == payload['data']['login_time']):
                         result = common.trueReturn(user.id, '请求成功')
                     else:
                         result = common.falseReturn('', 'Token已更改,请重新登录获取')
             else:
                 result = common.falseReturn('', payload)
     else:
         result = common.falseReturn('', '没有提供认证token')
     return result
Beispiel #17
0
def test_check_password_is_hashed(client):
    """Test password is hashed."""
    user = User(email='*****@*****.**', password='******')
    user.save()
    assert user.password[0:7] == '$argon2'
Beispiel #18
0
def test_check_password(client):
    """ Test password validation """
    user = User(email='*****@*****.**', password='******')
    user.save()
    assert user.check_password('foobarbaz123')
Beispiel #19
0
def test_password_is_not_nullable(client):
    """ test that exception is raised if password is not set """
    with pytest.raises(TypeError):
        assert User(email='*****@*****.**')
Beispiel #20
0
def test_created_at_defaults_to_datetime(client):
    """ Test creation date. """
    user = User(email='*****@*****.**', password='******')
    user.save()
    assert bool(user.created_at)
    assert isinstance(user.created_at, dt.datetime)