Ejemplo n.º 1
0
    def post(self):
        deserialized = request.get_json().copy()

        errors = {}
        if not user_validator.is_valid(deserialized):
            errors.update(handle_validation_errors(
                        user_validator.iter_errors(deserialized)))

        if deserialized.get('password', None) != \
           deserialized.get('confirmPassword', None):
            errors['confirmPassword'] = '******'
        if deserialized.get('email', None) != \
           deserialized.get('confirmEmail', None):
            errors['confirmEmail'] = 'Must match email'

        if User.exists_by_username(deserialized.get('username', '')):
            errors['username'] = '******'
        if User.exists_by_email(deserialized.get('email', '')):
            errors['email'] = 'Email is already registered'

        if errors != {}:
            return dumps(errors), 400

        deserialized['password'] = bcrypt.generate_password_hash(
            deserialized['password'])

        del deserialized['confirmPassword']
        del deserialized['confirmEmail']
        user = User.create(deserialized)

        mail.send_message(subject='Thanks For Registering!',
                          recipients=[deserialized['email']],
                          body=render_template('registration_email.html'))

        return dumps(user.serialized)
Ejemplo n.º 2
0
 def create(self, validated_data):
     """creates a user
     """
     user = User(**validated_data)
     user.set_password(validated_data['password'])
     user.save()
     return user
Ejemplo n.º 3
0
 def setUp(self):
     """initializes the test client and test users
     """
     self.client = APIClient()
     self.anonymous_user = User(username='******')
     self.anonymous_user.set_password('dbfdu76&mHN')
     self.anonymous_user.save()
     self.anonymous_user = User(username='******')
     self.anonymous_user.set_password('ncvsN809ibkj!*HJ2612J')
     self.anonymous_user.save()
Ejemplo n.º 4
0
    def create(self, validated_data):
        """creates a user
        """

        user = User(
            username=validated_data['username'].lower()
        )
        user.set_password(validated_data['password'])
        user.save()
        return user
Ejemplo n.º 5
0
 def wrapper(*args, **kwargs):
     access_token = request.args.get('access_token', '')
     user_info = User.objects(token=access_token)
     if app.config['AUTH']['enabled']:
         if user_info.count() == 0:
             abort(401)
         else:
             user_data = dict(
                 id=str(user_info.get().id),
                 name=user_info.get().name,
                 email=user_info.get().email,
                 password=user_info.get().password,
                 roles=user_info.get().roles,
                 token=user_info.get().token)
             if roles != '*':
                 if any(value in user_info.get().roles
                        for value in roles):
                     request.user = user_data
                     request.profile = user_info.get()
                     return function(*args, **kwargs)
                 else:
                     abort(401)
             else:
                 request.user = user_data
                 request.profile = user_info.get()
                 return function(*args, **kwargs)
     else:
         return function(*args, **kwargs)
Ejemplo n.º 6
0
def users_reset():
    forgot_info = Forgot.objects(token=request.args.get('token', ''))
    if forgot_info.count():
        user_info = User.objects(email=forgot_info.get().email)
        if user_info.count():
            randompass = os.urandom(16).encode("base64")[:10]
            user_info.update(set__password=sha1(randompass).hexdigest())
            forgot_info.delete()
            # Message
            msg = Message("Your new Password",
                          recipients=[user_info.get().email])
            msg.html = """
            <h2>Hi, %s</h2>
            <p>
            Your new password was successfully generated.
            </p>
            <p>
                <b>Password: </b> %s
            </p>
            """ % (user_info.get().name, randompass)

            @copy_current_request_context
            def send_message(message):
                mail.send(message)

            sender = threading.Thread(
                name='mail_reset_sender', target=send_message, args=(msg,))
            sender.start()
            # Returns a response
            return JSON(message='An email with the new password has been sent to your email.')
        else:
            raise InvalidRequest('User not found!')
    else:
        raise InvalidRequest('Forgot Token is invalid!')
Ejemplo n.º 7
0
def users_activate_user():
    activate_info = Activate.objects(token=request.args.get('token', ''))
    if activate_info.count():
        user_info = User.objects(email=activate_info.get().email)
        if user_info.count():
            user_info.update(set__status=True)
            activate_info.delete()
            # Message
            msg = Message("Your Account is Activated",
                          recipients=[user_info.get().email])
            msg.html = """
            <h2>Hi, %s</h2>
            <p>
            Your new access token was successfully generated.
                <p>
                    <b>Access Token: </b> %s
                </p>
            </p>
            """ % (user_info.get().name, user_info.get().token)

            @copy_current_request_context
            def send_message(message):
                mail.send(message)

            sender = threading.Thread(
                name='mail_activate_sender', target=send_message, args=(msg,))
            sender.start()
            # Returns a response
            return JSON(message='An email with the your new token has been sent to your email.')
        else:
            raise InvalidRequest('User not found!')
    else:
        raise InvalidRequest('Activate Token is invalid!')
Ejemplo n.º 8
0
def add_dummy_car():
    u = User.get_user('351.394.078.80')
    u.name = 'Mário do'
    u.phone = '(11) 223-244-523'
    u.driver_license = '123.55.13.2.13.23'
    u_key = u.put()

    license_plate = ''.join(random.choice('ABCDEFGH') for _ in range(3)) + \
                    ''.join(random.choice('1234567890') for _ in range(4))
    c = Car.get_car(license_plate)
    c.brand = 'Mercedes'
    c.model = 'Classe ' + random.choice('ABCD')
    c.year = 2007
    c.optionals = 3
    c.price = 250
    c.fuel = 'Gasolina'
    c.available_date = '2/2/2015'
    c.available_start_time = 2
    c.available_end_time = 4
    c.owner = u_key
    c_key = c.put()
    return jsonify({
        'user': u_key.id(),
        'car': c_key.id(),
    })
Ejemplo n.º 9
0
def add_car():
    try:
        logging.info("NOVOO CARROOOO %r", request.form)
        logging.info("NOVOO OWNER %r", request.form['owner_cpf'])
        u = User.get_user(request.form['owner_cpf'])
        u.name = request.form.get('owner_name')
        u.phone = request.form.get('owner_phone')
        u.driver_license = request.form.get('owner_driver_license')
        u_key = u.put()

        c = Car.get_car(request.form.get('license_plate'))
        c.brand = request.form.get('brand')
        c.model = request.form.get('model')
        c.year = int(request.form.get('year'))
        c.optionals = int(request.form.get('optionals'))
        c.price = float(request.form.get('price'))
        c.fuel = request.form.get('fuel')
        c.available_date = request.form.get('available_date')
        c.available_start_time = int(request.form.get('available_start_time'))
        c.available_end_time = int(request.form.get('available_end_time'))
        c.owner = u_key
        c_key = c.put()

        return jsonify({
            'status': 'ok',
            'message': 'Carro criado com sucesso!',
            'car_key': c_key.id(),
        })

    except Exception, e:
        logger.exception("Error saving car")
        return jsonify({
            'status': 'fail',
            'message': e.message,
        })
Ejemplo n.º 10
0
def users_forgot():
    data = request.get_json()
    user_info = User.objects(email=data['email'])
    if user_info.count():
        create_forgot_token = Forgot(
            email=user_info.get().email, token=str(uuid.uuid4()))
        create_forgot_token.save()
        # Message
        msg = Message("Forgot Password",
                      recipients=[user_info.get().email])
        msg.html = """
        <h2>Hi, %s</h2>
        <p>
        You requested a password change. Use the link below to create a new password.
        </p>
        <p>
            <a href="https://livia.herokuapp.com/forgot/reset?token=%s" target="_blank">Reset Password</a>
        </p>
        """ % (user_info.get().name, create_forgot_token.token)

        @copy_current_request_context
        def send_message(message):
            mail.send(message)

        sender = threading.Thread(
            name='mail_forgot_sender', target=send_message, args=(msg,))
        sender.start()
        # Returns a response
        return JSON(message='An email with the password reset link has been sent to your email.')
    else:
        raise InvalidRequest('User not found!')
Ejemplo n.º 11
0
def signin():
    # Retorna a user data
    user_info = User.objects(email=request.form['email'], password=sha1(
        request.form['password']).hexdigest())
    if user_info.count():
        return JSON(token=user_info.get().token, roles=user_info.get().roles)
    else:
        return JSON(message='User not found')
Ejemplo n.º 12
0
Archivo: user.py Proyecto: booo/gid
    def post(self):
        form = RegistrationForm(request.form, csrf_enabled = False)
        
        if form.validate():
            if not User.query.filter_by(username = form.username.data).count() > 0:
                try: 
                    user = User(form.username.data, form.email.data,
                                form.password.data)
                    db.session.add(user)
                    db.session.commit()

                    return jsonify(user=user.toDict())

                except IntegrityError as e:
                    return jsonify({"error": "Username or email do already exist"})


        return jsonify({"error": form.errors})
Ejemplo n.º 13
0
 def load_user_from_request(request):
     print "Loading user from request"
     access_token=request.headers.get('Authorization')
     if access_token:
         print "fetching user"
         user=User.objects(access_token=access_token)
         if user:
             return user[0]
     return None
Ejemplo n.º 14
0
def signup():
    # Create new user
    new_user = User()
    new_user.name = request.form['name']
    new_user.email = request.form['email']
    new_user.password = sha1(request.form['password']).hexdigest()
    new_user.token = str(uuid.uuid4())
    new_user.save()
    return JSON(message='User created successfully')
Ejemplo n.º 15
0
def get_user(user_id):
    try:
        cursor=User.objects(user_id=user_id)
        if cursor:
            user=cursor[0]
            user_json=user_helper.generate_user_json(user)
            response={'message':'Cool Profile','error_code':0,'user':user_json}
        else:
            response={'message':'No user with this id','error_code':1}
    except Exception as e:
        response={'message':'no data in database','error_code':1}
        print traceback.format_exc(e)
    return response
Ejemplo n.º 16
0
def user_login(email,password):
    try:
        print "--------------------------- Trying to log in -------------------------------"
        cursor=User.objects(email=email)
        if cursor:
            user=cursor[0]
            if user.password==password:
                response={'message':'You are logged in','error_code':0,'user':user}
            else:
                response={'message':'wrong password','error_code':1}
        else:
            response={'message':'wrong email','error_code':1}
    except Exception as e:
        print traceback.format_exc(e)
        response={'message':'no data in database','error_code':1}
    return response
Ejemplo n.º 17
0
    def post(self):
        deserialized = request.get_json()

        if not game_validator.is_valid(deserialized):
            errors = handle_validation_errors(
                        game_validator.iter_errors(deserialized))
            return dumps(errors), 400
        else:
            errors = {}
            for player in ['x_player_id', 'o_player_id']:
                if not User.exists_by_id(deserialized[player]):
                    errors[player] = 'Player does not exist'
            if errors != {}:
                return dumps(errors), 400

        game = Game.create(deserialized)

        return dumps(game.serialized)
Ejemplo n.º 18
0
def signup() -> (str, int):
    s: UserInfo = json.loads(request.data)
    app.logger.info(f"POST => /signup {s['username']}")
    try:
        Schema(UserInfoType).validate(s)
        password_hash = pbkdf2_sha256.hash(s.get('password'))
        user = User(**{
            'username': s.get('username'),
            'password': password_hash,
        })
        # TODO: abstract away adding user to db?
        db.session.add(user)
        db.session.commit()
        return 'Successful signup', 201
    except SchemaError:
        app.logger.error(f"POST => /signup: schema error")
        return 'Username or password must be string', 400
    except IntegrityError:
        app.logger.error(f"POST => /signup: integrity error")
        return 'Username already exits', 409
Ejemplo n.º 19
0
def reset_password():
    try:
        data = request.get_json()
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if data and data['username']:
        user = User.getUser(data['username'])
        expire = datetime.datetime.utcnow() + datetime.timedelta(hours=24)
        token = jwt.encode({
            'id': user.username,
            'exp': expire
        }, app.config.get('SECRET_KEY'))
        return jsonify(Response(200).generateResetURL(token.decode('UTF-8')))
    else:
        return ErrorResponse(JsonNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
Ejemplo n.º 20
0
    def func(*args, **kwargs):
        try:
            if 'authorization' not in request.headers:
                abort(
                    404,
                    message="You need to be logged in to access this resource")

            payload = _decode_jwt()
            g.user_id = payload['id']

            g.user = User.find(g.user_id)
            if g.user is None:
                abort(404, message="The user id is invalid")
            return f(*args, **kwargs)
        except JWTError as e:
            abort(
                400,
                message=
                "There was a problem while trying to parse your token -> {0}".
                format(e))
Ejemplo n.º 21
0
    def test_soft_delete_center_with_user(  #pylint:disable=C0103
            self, client, init_db, test_center, auth_header):  # pylint: disable=W0613
        """
            Tests for soft deleting a center with an associated user
        """
        test_role = Role(title='dev').save()
        User(
            id='-GTHFDR56765',
            name='Duke',
            email='*****@*****.**',
            center_id=test_center.id,
            role_id=test_role.id).save()

        response = client.delete(
            f'{API_V1_BASE_URL}/centers/{test_center.id}', headers=auth_header)
        response_json = json.loads(response.data.decode(CHARSET))

        assert response.status_code == 200
        assert response_json['status'] == 'success'
        assert response_json['message'] == SUCCESS_MESSAGES[
            'soft_delete'].format(test_center.name)
Ejemplo n.º 22
0
def login_google():
    oauth = Session().query(OauthGoogle).filter(
        OauthGoogle.party_id == g.info.get('id')).first()
    is_new = True if oauth is None else False

    if is_new:
        user = afr(User(email=g.info.get('email')))
        oauth = afr(OauthGoogle(user, g.info))
        user.oauth_google_id = oauth.id

    user_session = UserSession(oauth.user,
                               third_party_token=request.json.get('token'))
    Session(changed=True).add(user_session)

    return {
        'okay': True,
        'user_id': oauth.user.id,
        'token': user_session.token,
        'is_new': is_new,
        'expiry': DateTimeHelper.full_datetime(user_session.expiry)
    }, Status.HTTP_200_OK
Ejemplo n.º 23
0
    def post(self):
        schema = QuestionSchema()
        question = request.get_json()

        try:
            schema.load(question)
        except ValidationErrorSchema as err:
            raise ValidationError(err.messages, 400)
        
        user_id = request.decoded_token['id']

        user = User.get(user_id)
        new_question = Question(**question, user=user)
        new_question.save()
        question = schema.dump(new_question)

        return {
            'success': 'true',
            'message': 'question added successfully',
            'question': question
        }
Ejemplo n.º 24
0
def login_naver():
    g.info = g.info.get('response')
    oauth = Session().query(OauthNaver).filter(
        OauthNaver.party_id == g.info.get('id')).first()
    is_new = True if oauth is None else False

    if is_new:
        user = afr(User(email=g.info.get('email')))
        oauth = afr(OauthNaver(user, g.info))
        afr(UserPoint(user_id=user.id))

    user_session = UserSession(oauth.user,
                               third_party_token=request.json.get('token'))
    Session(changed=True).add(user_session)

    return {
        'user_id': oauth.user.id,
        'token': user_session.token,
        'is_new': is_new,
        'expiry': DateTimeHelper.full_datetime(user_session.expiry)
    }, Status.HTTP_200_OK
Ejemplo n.º 25
0
def user_search_results(search):
    results = []
#    search_dim = search.data['select']
    search_string = search.data['search']

    if search_string == '':
        return render_template('notfound.html')
    else:
        # display results
        results = User().find(search_string, page_number(), page_size())
        if not results:
            flash(search_string)
            return render_template('notfound.html')
        table = UserResults(results)
        table.border = True
        return render_template('user-results.html', table=table, results=results, form=search)

    search = SearchForm(request.form)
    if request.method == 'POST':
        return user_search_results(search)
    return render_template('user-search.html', form=search)
Ejemplo n.º 26
0
    def post(self):
        """ Endpoint to request password reset link """

        request_data = request.get_json()
        email = request_data['email']
        user = User.find_by_email(email)

        if not user:
            error_response['message'] = 'User not found'
            return error_response, 404

        user_schema = UserSchema()
        send_email(user_schema.dump(user), 'Password Reset Request',
                   'password_reset_email.html')

        return {
            'status':
            'success',
            'message':
            'Request successfully submitted. Please check your email to continue.'
        }, 200
Ejemplo n.º 27
0
 def get(self):
     try:
         users = dict()
         users["users"] = []
         for user in User.objects():
             follow_list = [
                 follow for follow in Followers.objects.filter(
                     follower_username=user)
             ]
             following_list = [
                 follow
                 for follow in Followers.objects.filter(added_by=user)
             ]
             user = User.objects.get(id=user.id)
             user.update(followings=follow_list, followers=following_list)
             users["users"].append(user.to_json())
         return users, 200
     except DoesNotExist:
         raise UserNotExistsError
     except Exception:
         raise InternalServerError
Ejemplo n.º 28
0
    def decorated_function(*args, **kwargs):
        try:
            # get the auth token
            auth_header = request.headers.get('Authorization')
            if auth_header:
                auth_token = auth_header.split(" ")[1]
            else:
                auth_token = None
            if auth_token is not None:
                result = User.decode_auth_token(auth_token)
                try:
                    g.user_id = uuid.UUID(hex=result).hex
                    user = User.query.get(g.user_id)
                    if user is not None:
                        g.user = user
                        return func(*args, **kwargs)
                    else:
                        responseObject = {
                            'status': 'fail',
                            'message': 'Auth token for nonexistent user.'
                        }
                        return make_response(jsonify(responseObject), 401)
                except ValueError:
                    responseObject = {'status': 'fail', 'message': result}

                return make_response(jsonify(responseObject), 401)
            else:
                responseObject = {
                    'status': 'fail',
                    'message': 'Provide a valid auth token.'
                }
                return make_response(jsonify(responseObject), 401)

        except Exception as e:

            responseObject = {
                'status': 'fail',
                'message': 'Something went wrong.'
            }
            return make_response(jsonify(responseObject), 401)
Ejemplo n.º 29
0
Archivo: auth.py Proyecto: qurit/raiven
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(session)):
    username = form_data.username
    password = form_data.password
    user = User.query(db).filter_by(username=username).first()

    # Try creating an new ldap account
    if not user and config.LDAP_AUTH_ENABLED:
        user = ldap.user_factory(username, password, db)

    # User is invalid
    if not user:
        raise LoginException()

    # Try LDAP authentication
    if user.ldap_user and not ldap.authenticate(username, password):
        raise LoginException()

    # Local user Authentication
    elif user.local_user and not user.local_user.verify_password(password):
        raise LoginException()

    return Token(access_token=user.generate_token())
Ejemplo n.º 30
0
def login():
    try:
        data = request.get_json()
        fetched = User.query.filter_by(login=data["login"]).first()

        valid_password = User.validate_password(
            data["password"], fetched.password if fetched else None)
        if not valid_password:
            val = {"message": "Invalid credentials."}
            return response_with(resp.BAD_REQUEST_400, value=val)

        user_schema = UserSchema()
        user, error = user_schema.dump(fetched)
        token = generate_jwt(user)
        return response_with(resp.SUCCESS_200,
                             value={
                                 "user": user,
                                 "token": token
                             })
    except Exception as e:
        logging.error(e)
        return response_with(resp.SERVER_ERROR_500)
Ejemplo n.º 31
0
    def test_create_or_modify_returns_created_user_offerer_search_by_relationship_ids(
            self, app):
        # Given
        offerer = Offerer(name="foo")
        user = User(email="foo.marx@com", publicName="Foo Marx")
        ApiHandler.save(offerer, user)

        # When
        user_offerer = UserOfferer.create_or_modify({
            '__SEARCH_BY__': ['offererId', 'userId'],
            'rights':
            'admin',
            'offererId':
            humanize(offerer.id),
            'userId':
            humanize(user.id)
        })

        # Then
        assert user_offerer.offererId == offerer.id
        assert user_offerer.rights == 'admin'
        assert user_offerer.userId == user.id
Ejemplo n.º 32
0
def background_color():
    try:
        data = request.get_json()['data']['attributes']
        bg_color = data['bg_color']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    svg2png = SVG2PNG()

    bg_color = '#' + str(bg_color)
    user_defined_path = svg2png.do_svg2png(1, bg_color)
    with open(user_defined_path, "rb") as image_file:
        image_data = base64.b64encode(image_file.read())
        os.remove(user_defined_path)

    try:
        imageName = saveToImage(imageFile=image_data.decode('utf-8'),
                                extension=".png")
    except Exception:
        return ErrorResponse(ImageNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data['uid']
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=imageName,
                       filetype='image',
                       uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(ColorImageSchema().dump(file_upload).data)
Ejemplo n.º 33
0
 def put(self):
     try:
         args = parser.parse_args()
         if (args['device'] is None) or (args['login'] is None) or (
                 args['password'] is None):
             return {'success': False, 'errno': ERRNO_FIELDS_ABSENT}, 400
         pass_md5 = hashlib.md5(
             args['password'].encode('utf-8')).hexdigest()
         new_user = User(login=args['login'], password=pass_md5)
         db.session.add(new_user)
         new_token = Token(token=str(uuid.uuid4()),
                           user=new_user,
                           device=args['device'])
         if args['expires'] is not None:
             new_token.expires_at = datetime.fromtimestamp(args['expires'] /
                                                           1000.0)
         db.session.add(new_token)
         db.session.commit()
         return {'token': new_token.token}
     except Exception as e:
         db.session.rollback()
         log.error(e)
         return {'success': False, 'errno': ERRNO_INTERNAL_UNKNOWN}, 500
Ejemplo n.º 34
0
def generate_token(exp=None):
    """
    Generates jwt tokens for testing purpose

    Args:
        exp: Token Expiration. This could be datetime object or an integer
    Returns:
        token: This is the bearer token in this format 'Bearer token'
    """

    secret_key = getenv('JWT_SECRET_KEY')
    user = {
        'first_name': fake.name(),
        'last_name': fake.name(),
        'email': fake.email(),
        'is_admin': IsAdmin.yes,
        'password': fake.password()
    }

    payload = {'id': str(User.find_or_create(user, email=user['email']).id)}
    payload.__setitem__('exp', exp) if exp is not None else ''
    token = jwt.encode(payload, secret_key, algorithm='HS256').decode(CHARSET)
    return 'Bearer {0}'.format(token)
Ejemplo n.º 35
0
def fileUpload():
    try:
        data = request.json['csvFile']
        csv = data['csvFile']
    except Exception:
        return ErrorResponse(PayloadNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    if 'extension' not in data.keys():
        return ErrorResponse(ExtensionNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    extension = data['extension']
    if extension != 'csv':
        return ErrorResponse(CSVNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()
    try:
        csvName = saveToCSV(csvFile=csv, extension='.csv')
    except Exception:
        return ErrorResponse(OperationNotFound().message, 422, {
            'Content-Type': 'application/json'
        }).respond()

    uid = data.get('uid')
    fetch_user = User.getUser(user_id=uid)
    if fetch_user is None:
        return ErrorResponse(
            UserNotFound(uid).message, 422, {
                'Content-Type': 'application/json'
            }).respond()

    file_upload = File(filename=csvName, filetype='csv', uploader=fetch_user)
    file_upload.save_to_db()
    return jsonify(CSVUploadSchema().dump(file_upload).data)
Ejemplo n.º 36
0
 def add_book(self, title, author, date_published, genre, description, isbn,
              copies, date_created):
     '''Function for adding a user'''
     User().check_user_is_admin()
     if Books().query.filter_by(isbn=isbn).count() != 0:
         existing_book = Books().query.filter_by(isbn=isbn).first()
         existing_book.copies += 1
         db.session.commit()
         return jsonify(
             {'message': 'Book exists, copies incremented by 1.'}), 201
     else:
         new_book = Books(title=title,
                          author=author,
                          date_published=date_published,
                          genre=genre,
                          description=description,
                          isbn=isbn,
                          copies=copies,
                          date_created=date_created)
         self.save(new_book)
         return jsonify({
             "message":
             "%s by %s has been added to library" % (title, author)
         }), 201
Ejemplo n.º 37
0
    def get(self):
        """Get request to verify the user's emails"""

        # get the verification_token from the request params
        verification_token = request.args.get('token')

        # check if the token is valid and look for the token in the database
        Encryption.detokenize(verification_token)
        found_token = User.query_(token=verification_token).first()

        # throw an error if not found else update and return a success message
        if not found_token:
            return {'status': 'error', 'message': MESSAGES['VERIFIED']}, 409

        else:
            found_token.update_(token=None, verified=True)

            return {
                'status':
                'success',
                'message':
                MESSAGES['PROCEED_TO_LOGIN'].format(
                    'Your account has been successfully verified'),
            }, 200
Ejemplo n.º 38
0
 def edit_book(self, title, book_id, author, date_published, genre,
               description, copies, isbn):
     '''Function for editing a book'''
     User().check_user_is_admin()
     self.check_if_book_exists(book_id)
     book = Books().query.filter_by(id=book_id).first()
     fields = {
         'title': title,
         'id': book_id,
         'author': author,
         'genre': genre,
         'description': description,
         'copies': copies,
         'isbn': isbn
     }
     #edit fields with data only
     for key in fields:
         if fields[key] is not None:
             if HelloBooks().edit_book_validation({'%s' % key: fields[key]
                                                   }) is True:
                 setattr(book, key, fields[key])
             else:
                 return jsonify(
                     {'message': 'Please enter fields correctly.'})
     #edit the date
     if date_published is not None:
         if HelloBooks().date_validate(date_published) is True:
             book.date_published = date_published
         else:
             return jsonify({
                 'message':
                 'Please enter a correct date format DD/MM/YYYY'
             }), 400
     book.date_modified = datetime.datetime.now()
     db.session.commit()
     return jsonify({"message": "Successfully edited %s" % book.title}), 201
Ejemplo n.º 39
0
def users_signup():
    # Create new user
    data = request.get_json()
    new_user = User()
    new_user.name = data['name']
    new_user.email = data['email']
    new_user.password = sha1(data['password']).hexdigest()
    new_user.token = str(uuid.uuid4())
    new_user.save()
    create_activate_token = Activate(
        email=new_user.email, token=str(uuid.uuid4()))
    create_activate_token.save()
    # Message
    msg = Message("Welcome to Liv",
                  recipients=[new_user.email])
    msg.html = """
    <h2>Hi, %s</h2>
    <h4>Welcome to Liv</h4>
    <p>
    To start using the Liv, you need to activate your account. 
    Click the link to activate your account.
    </p>
    <p>
        <a href="https://livia.herokuapp.com/signup/activate?token=%s" target="_blank">Activate your Liv account</a>
    </p>
    """ % (new_user.name, create_activate_token.token)

    @copy_current_request_context
    def send_message(message):
        mail.send(message)

    sender = threading.Thread(
        name='mail_signup_sender', target=send_message, args=(msg,))
    sender.start()
    # Returns a response
    return JSON(message='An email with the your activation token has been sent to your email.')
Ejemplo n.º 40
0
 def post(self):
     ''' class method which allows user to sign up'''
     username = request.json.get('username')
     phone = request.json.get('phone')
     password = request.json.get('password')
     confirm_p = request.json.get('confirm')
     if username and phone and password and confirm_p:
         if not User.check_phone(phone):
             return make_response(
                 jsonify({
                     'message':
                     'enter phone contact in 072-333-2222 format'
                 })), 409
         if not User.verify_password(password, confirm_p):
             return make_response(
                 jsonify({
                     'message':
                     'Ensure password and confirm password matches.'
                 })), 409
         check_pass = User.p_strength(password)
         if not check_pass:
             return make_response(jsonify({'message': check_pass})), 409
         if User.does_user_exist(users, phone):
             return make_response(
                 jsonify({
                     'message':
                     'a user with that phone contact already exist'
                 })), 409
         user_obj = User(username, phone, password, confirm_p)
         user = User.serialize_user(user_obj)
         users.append(user)
         return make_response(
             jsonify({
                 'message':
                 'welcome to our community,{}'.format(user['username'])
             })), 201
     return make_response(
         jsonify(
             {'message':
              'ensure you have provide all required details'})), 400
Ejemplo n.º 41
0
 def test_should_return_user_by_find_by_mobile(self):
     user = User.find_by_mobile(self.user.mobile)
     self.assertEqual(self.user, user)
Ejemplo n.º 42
0
 def test_should_return_None_by_find_by_email(self):
     user = User.find_by_email("*****@*****.**")
     self.assertEqual(None, user)
Ejemplo n.º 43
0
 def test_should_return_user_by_find_by_email(self):
     user = User.find_by_email(self.user.email)
     self.assertEqual(self.user, user)
Ejemplo n.º 44
0
 def test_should_return_None_by_find_by_user_id(self):
     user = User.find_by_id("some_wrong_user_id")
     self.assertEqual(None, user)
Ejemplo n.º 45
0
 def test_should_return_user_by_find_by_user_id(self):
     user = User.find_by_id(self.user.user_id)
     self.assertEqual(self.user, user)
Ejemplo n.º 46
0
def get_articles():
    tom = User(name='Tom')
    return flask.jsonify([
        Article(title='Howdy', content='First article!', author=tom).to_dict()
    ])
Ejemplo n.º 47
0
def modules_update():
    data = request.get_json()
    modules = User.objects(email=request.user['email'])
    modules.update(set__modules=data['modules'])
    return JSON(message='Modules updated successfully!')
Ejemplo n.º 48
0
 def test_user_exists_by_id(self):
     self.assertFalse(User.exists_by_id(505050))
     self.assertTrue(User.exists_by_id(self.new_user().id))
Ejemplo n.º 49
0
 def test_user_exists_by_email(self):
     self.assertFalse(User.exists_by_email('nonsense'))
     self.assertTrue(User.exists_by_email(self.new_user().email))
Ejemplo n.º 50
0
 def to_dict(self):
     d = super(Car, self).to_dict()
     d['license_plate'] = self.key.id()
     d['owner'] = User.get_user(d['owner'].id()).to_dict() \
         if d['owner'] else None
     return d
Ejemplo n.º 51
0
 def activate(self, user_id):
     user = User.query.get_or_404(user_id)
     user.is_active = True
     User.update(user)
     return dumps('User has been activated')
Ejemplo n.º 52
0
class PheditAPITestCase(APITestCase):
    """defines tests for the api
    """

    def setUp(self):
        """initializes the test client and test users
        """
        self.client = APIClient()
        self.anonymous_user = User(username='******')
        self.anonymous_user.set_password('dbfdu76&mHN')
        self.anonymous_user.save()
        self.anonymous_user = User(username='******')
        self.anonymous_user.set_password('ncvsN809ibkj!*HJ2612J')
        self.anonymous_user.save()

    def test_api_endpoint(self):
        """test for api endpoint
        """
        response = self.client.get('/api/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.data['users'],
            'http://testserver/api/users/'
        )
        self.assertEqual(
            response.data['images'],
            'http://testserver/api/images/'
        )

    def test_api_users_endpoint(self):
        """test for api users endpoint
        """
        response = self.client.get('/api/users/')
        self.assertEqual(response.status_code, 200)

    def test_creating_api_user_endpoint(self):
        """test for creating a new user
        """
        response = self.client.post(
            '/api/users/',
            {'username': '******', 'password': '******'}
        )
        # import ipdb; ipdb.set_trace()
        self.assertEqual(response.status_code, 201)

    def test_getting_api_user_endpoint(self):
        """test for getting users
        """
        self.client.post(
            '/api/users/',
            {'username': '******', 'password': '******'}
        )
        response = self.client.get('/api/users/anotheruser/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.data['username'],
            'anotheruser'
        )

    def test_api_images_endpoint(self):
        """test for getting images
        """
        response = self.client.get('/api/images/')
        self.assertEqual(response.status_code, 200)

    def test_uploading_image_to_images_api_endpoint_as_anonymous_user(self):
        """test for creating a new image
        """
        path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(path, 'hashtag.jpg'), "rb") as image:
            response = self.client.post(
                '/api/images/',
                {'image': image},
                format='multipart'
            )
        self.assertEqual(response.status_code, 201)

        # test uploader
        response = self.client.get('/api/images/')
        self.assertEqual(
            response.data[0].get('uploaded_by'),
            'anonymous'
        )
        self.assertEqual(response.status_code, 200)

    def test_uploading_image_to_images_api_endpoint_as_other_user(self):
        """test for creating a new image as logged-in user
        """
        self.client.login(
            username='******',
            password='******'
        )

        path = os.path.dirname(os.path.abspath(__file__))
        with open(os.path.join(path, 'hashtag.jpg'), "rb") as image:
            response = self.client.post(
                '/api/images/',
                {'image': image},
                format='multipart'
            )
        self.assertEqual(response.status_code, 201)

        # test uploaded by other user
        response = self.client.get('/api/images/')
        self.assertEqual(
            response.data[0].get('uploaded_by'),
            'testuser'
        )
        self.assertEqual(response.status_code, 200)

        self.client.logout()

    def test_redirect_when_accessing_webapp_unauthenticated(self):
        """user gets redirected if they navigate to app directly
        """
        unauthenticated_response = self.client.get('/app/')
        self.assertEqual(unauthenticated_response.status_code, 302)
        self.client.login(
            username='******',
            password='******'
        )
        authenticated_response = self.client.get('/app/')
        self.assertEqual(authenticated_response.status_code, 200)

    def test_accessing_navigating_to_gallery_page(self):
        self.client.login(
            username='******',
            password='******'
        )
        response = self.client.get('/gallery/')
        self.assertContains(response, 'Gallery')
Ejemplo n.º 53
0
 def test_should_return_None_by_find_by_mobile(self):
     user = User.find_by_mobile("4545454545")
     self.assertEqual(None, user)
Ejemplo n.º 54
0
 def test_user_exists_by_username(self):
     self.assertFalse(User.exists_by_username('nonsense'))
     self.assertTrue(User.exists_by_username(self.new_user().username))
Ejemplo n.º 55
0
 def test_empty_login(self):
     test_user = User(email=email,
                      user="",
                      password="",
                      confirm_password=None)
     self.assertFalse(LoginForm(test_user).check_username_exists())
Ejemplo n.º 56
0
def modules_index():
    modules_data = User.objects(email=request.user['email']).get()['modules']
    return JSON(modules=modules_data, total=len(modules_data))