Exemple #1
0
def create_user():
    try:
        data = request.get_json()
        if User.find_by_username(data['username']) is not None:
            return response_with(resp.INVALID_INPUT_422)
        data['password'] = User.generate_hash(data['password'])
        user_schmea = UserSchema()
        user = user_schmea.load(data)
        if user.role not in ACCESS.keys():  #check if it's a valid role
            return jsonify(
                msg="{} is not a valid role!".format(user.role)), 403

        current_user = User.query.get(get_jwt_identity())

        if user.role == 'root' and current_user.role != 'root':
            return jsonify(msg="{You are not allowed to make a root!"), 403

        # Comment from this line if you don't want use email.

        # token = generate_verification_token(data['email'])
        # verification_email = url_for('user_routes.verify_email', token=token, _external=True)
        # html = render_template_string("<p>Welcome! Thanks for signing up. Please follow this link \
        #                               to activate your account:</p> <p><a href='{{ verification_email }}'\
        #                               >{{ verification_email }}</a></p> <br> <p>Thanks!</p>",\
        #                               verification_email=verification_email)
        # subject = "Please Verify your email"
        # send_email(user.email, subject, html)

        # Comment to this line if you don't want use email.

        user.create()
        return response_with(resp.SUCCESS_201)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
def authenticate_user():
    try:
        data = request.get_json()
        if data.get('email'):
            current_user = User.find_by_email(data.get('email'))
        elif data.get('username'):
            current_user = User.find_by_username(data.get('username'))
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)
        if current_user and not current_user.is_verified:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data.get('password'), current_user.password):
            access_token = create_access_token(identity=data.get('username'))
            user_schema = UserSchema()
            user = user_schema.dump(current_user)
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message':
                                     'Logged in as {}'.format(
                                         current_user.username),
                                     'access_token':
                                     access_token,
                                     'user':
                                     user
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401,
                                 value={'message': 'Password is wrong'})
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
def create_user():
    try:
        data = request.get_json()
        if User.find_by_email(
                data['email']) is not None or User.find_by_username(
                    data['username']) is not None:
            return response_with(resp.INVALID_INPUT_422)
        data['password'] = User.generate_hash(data['password'])
        user_schema = UserSchema()
        user = user_schema.load(data)
        token = generate_verification_token(data['email'])
        verification_email = url_for('user_routes.verify_email',
                                     token=token,
                                     _external=True)
        html = render_template_string(
            "<p>Welcome! Thanks for signing up. Please follow this link to activate your "
            "account:</p> <p><a href='{{ verification_email }}'>{{ verification_email "
            "}}</a></p> <br> <p>Thanks!</p>",
            verification_email=verification_email)
        subject = "Please Verify your email"
        send_email(user.email, subject, html)
        result = user_schema.dump(user.create())
        return response_with(resp.SUCCESS_201, value={'author': result})
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Exemple #4
0
def authenticate_user():
    try:
        data = request.get_json()
        if data.get('email'):
            current_user = User.find_by_email(data['email'])
        elif data.get('username'):
            current_user = User.find_by_username(data['username'])
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)

        # Comment from this line if you don't want use email.
        if current_user and not current_user.isVerified:
            return jsonify(message='User is not verified'), 403
        #Comment to this line if you don't want use email.

        if User.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(
                identity=current_user.id)  #,   expires_delta = False)
            return response_with(resp.SUCCESS_200, \
                                 value={'message': 'Logged in as {}'.format(current_user.username), \
                                        "access_token": access_token})
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
def authenticate_user():
    try:
        data = request.get_json()
        if data.get('email'):
            current_user = User.find_by_email(data['email'])
        elif data.get('username'):
            current_user = User.find_by_username(data['username'])
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)
        if current_user and not current_user.isVerified:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=current_user.username)
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message':
                                     'Logged in as {} '.format(
                                         current_user.username),
                                     "access_token":
                                     access_token
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Exemple #6
0
def create_users():
    user1 = User(email="*****@*****.**",
            username='******',
            password=User.generate_hash('helloworld'),
            isVerified=True).create()
    user2 = User(email="*****@*****.**",
            username='******',
            password=User.generate_hash('helloworld')).create()
 def update(self, instance: User, validated_data: dict) -> User:
     """
     Update a bulk quote entity
     :param instance: BulkQuoteSearch to update
     :param validated_data: Data to update with
     :return: Updated Entity
     """
     instance.save()
     return instance
 def create(self, validated_data: dict) -> User:
     """
     Create a new bulk quote entity
     :param validated_data: data to create with
     :return: Created Entity
     """
     instance = User(**validated_data)
     instance.save()
     return instance
    def create_portal(self, request: Request):

        portal = request.data.get('portal', None)
        if portal:
            new_user = User(portal_firestore_key=portal)
            new_user.save()
            return Response(status=200)
        else:
            return HttpResponse(status=401)
def create_user_in_db(db: Session, user: UserCreate):
    db_user = User(
        email=user.email,
        password=User.generate_hash(user.password),
        username=user.email,
        role=user.role,
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user
Exemple #11
0
def create_root():
    if User.find_by_id(1):
        return jsonify(msg="there is already a root!"), 403
    data = request.get_json()
    data['password'] = User.generate_hash(data['password'])
    user_schmea = UserSchema()
    user = user_schmea.load(data)
    user.role = 'root'
    user.isVerified = True
    user.create()
    return response_with(resp.SUCCESS_201)
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)  # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # existing user
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return (jsonify({'username': user.username}))
def create_user():
    user1 = User(
        username='******',
        email='*****@*****.**',
        password=User.generate_hash('nghi!abc123'),
        is_verified=True,
    ).create()

    user2 = User(
        username='******',
        email='*****@*****.**',
        password=User.generate_hash('nghi!abc123'),
        is_verified=False,
    ).create()
Exemple #14
0
 def post(self):
     args = self.parser.parse_args()
     try:
         user = User(username=args["username"],
                     email=args["email"],
                     company_id=args["company_id"])
         if args["password"] is not None:
             user.hash_password(args["password"])
         db.session.add(user)
         db.session.commit()
         return {"user" : marshal(user, user_field) }, 200
     except Exception as e:
         print e
         return {"error":"Error creating new user",
                 "msg" : str(e) }, 404
Exemple #15
0
def create_user():
    # try:
    data = request.get_json()
    data['password'] = User.generate_hash(data['password'])
    user = user_schema.load(data)
    result = user_schema.dump(user.create())
    return response_with(resp.SUCCESS_201)
Exemple #16
0
    def update_upc_map(self, request: Request):
        user = get_user_id_from_request(request)
        map_list = json.loads(request.data.get('map_list', None))
        if user and map_list:
            user = User(id=user)
            for code in map_list.get('upc_map', {}):
                upc_id = Upc.get_upc_id(code.get('upc__upc', None))
                item_id = Item.get_item_id(code.get('item__item_code', None))
                if UpcMap.objects.filter(upc=upc_id,
                                         user_id=user,
                                         item=item_id):
                    to_update = UpcMap.objects.get(upc=upc_id,
                                                   user_id=user,
                                                   item=item_id)
                    to_update.amount = code.get('amount')
                    to_update.save()
                elif not UpcMap.objects.filter(
                        upc=upc_id, user_id=user, item=item_id):
                    upc_list = UpcMap(user_id=user,
                                      upc=upc_id,
                                      item=item_id,
                                      amount=code.get('amount', 0))
                    upc_list.save(force_insert=True)

            return Response(status=200)
        else:
            return HttpResponse(status=401)
Exemple #17
0
def create_user():
    try:
        data = request.get_json()
        if (User.find_by_email(data['email']) is not None
                or User.find_by_username(data['username']) is not None):
            return response_with(resp.INVALID_INPUT_422)
        data['password'] = User.generate_hash(data['password'])
        user_schmea = UserSchema()
        user = user_schmea.load(data)
        sendEmailToken(data['email'])
        result = user_schmea.dump(user.create())
        return response_with(resp.SUCCESS_201)

    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
def authenticate_user(db, email: str, password: str):
    user = get_user(db, email)
    if not user:
        return False
    if not User.verify_hash(password, user.password):
        return False
    return user
Exemple #19
0
    def set_initial_inventory(self, request: Request):

        user = get_user_id_from_request(request)
        new_inventory = json.loads(request.data.get('inventory', None))
        if user and new_inventory:
            user = User(id=user)
            for item in new_inventory:
                item_id = Item.get_item_id(item.get('item', None))
                item_id = Item(id=item_id.id)
                if Supply.objects.filter(user_id=user, item_id=item_id):
                    old_amount = Supply.objects.get(user_id=user,
                                                    item_id=item_id)
                    new_amount = old_amount.amount + int(item.get('amount', 0))
                    to_update = Supply.objects.get(user_id=user,
                                                   item_id=item_id)
                    to_update.amount = new_amount
                    to_update.save()
                else:
                    inventory_item = Supply.objects.create(user_id=user,
                                                           item_id=item_id,
                                                           amount=item.get(
                                                               'amount', 1),
                                                           date=datetime.now())

            return Response(status=200)
        else:
            return HttpResponse(status=401)
Exemple #20
0
def authenticate_user():
    try:
        data = request.get_json()
        current_user = User.find_by_username(data['username'])
        if not current_user:
            return response_with(resp.INVALID_INPUT_422)
        if User.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=data['username'])
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message': 'Successfully logged',
                                     'access_toke': access_token
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        return response_with(resp.INVALID_INPUT_422)
Exemple #21
0
def signup(username, password):
    if db.session.query(exists().where(User.username == username)).scalar():
        raise HTTPNotFound(title='Cannot', description='asdfas')

    u = User(username=username, password=password)
    print(u)
    db.session.add(u)

    return {'token': generate_token(u)}
Exemple #22
0
def create_user():
    try:
        data = request.get_json()
        data['password'] = User.generate_hash(data['password'])
        user_schema = UserSchema()
        user = user_schema.load(data)
        result = user_schema.dump(user.create())
        return response_with(resp.SUCCESS_201)
    except Exception as e:
        return response_with(resp.INVALID_INPUT_422)
Exemple #23
0
def autehticate_user():
    # try :
    data = request.get_json()
    current_user = User.query.filter_by(username=data['username']).first()
    if not current_user :
        return response_with(resp.SERVER_ERROR_404)
    if User.verify_hash(data['password'],current_user.password):
        access_token = create_access_token(identity = data['username'])
        return response_with(resp.SUCCESS_201, value={'message': 'Logged in as {}'.format(current_user.username), "access_token": access_token})
    else:
        return response_with(resp.UNAUTHORIZED_401)
Exemple #24
0
    def test_delete_user(self):
        token = login(3)

        user = User.find_by_email("*****@*****.**")

        response = self.app.delete(
            '/api/users/' + str(user.id),
            content_type='application/json',
            headers={'Authorization': 'Bearer ' + token})

        self.assertEqual(204, response.status_code)
def authenticate_user():
    try:
        data = request.get_json()
        current_user = User.find_by_username(data['username'])
        if not current_user:
            return response_with(resp.SERVER_ERROR_404)
        if User.verify_hash(data['password'], current_user.password):
            access_token = create_access_token(identity=data['username'])
            return response_with(resp.SUCCESS_201,
                                 value={
                                     'message':
                                     'Logged in as {}'.format(
                                         current_user.username),
                                     "access_token":
                                     access_token
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print e
        return response_with(resp.INVALID_INPUT_422)
Exemple #26
0
def login():
    """
    Login existing user
    :return: Access token and Refresh token
    """
    payload = request.json
    email = payload.get('email', None)
    password = payload.get('password', None)

    user = User.find_by_email(email)
    validate_credentials(user, password)

    return jsonify({**generate_jwt(user.uuid), 'user': user})
Exemple #27
0
    def test_change_status_user(self):
        token = login(3)

        data = {"role": "admin"}

        user = User.find_by_email("*****@*****.**")

        response = self.app.post('/api/users/status/' + str(user.id),
                                 data=json.dumps(data),
                                 content_type='application/json',
                                 headers={'Authorization': 'Bearer ' + token})

        self.assertEqual(200, response.status_code)
    def create_inventory(self, request: Request):

        user = get_user_id_from_request(request)
        if user:
            item = Item(id=0)
            user = User(id=user)
            new_inventory = Supply(user_id=user,
                                   item_id=item,
                                   amount=0,
                                   date=datetime.datetime.now())
            new_inventory.save()
            return Response(status=200)
        else:
            return HttpResponse(status=401)
Exemple #29
0
def create_users():
    user1 = User(username='******', email="*****@*****.**", \
                 password=User.generate_hash('hello'), isVerified=True).create()

    user2 = User(username='******', email="*****@*****.**", \
                 password=User.generate_hash('hello')).create()

    user3 = User(username='******', email= "*****@*****.**", \
                 password=User.generate_hash('hello'), isVerified=True, role ="admin").create()
Exemple #30
0
    def test_get_user(self):
        token = login(3)

        user_to_get = User.find_by_email("*****@*****.**")

        response = self.app.get('/api/users/' + str(user_to_get.id),
                                content_type='application/json',
                                headers={'Authorization': 'Bearer ' + token})
        data = json.loads(response.data)

        print(data)

        user = {'email': '*****@*****.**', 'id': 2, 'role': 'user', \
                'username': '******', 'isVerified': False}

        self.assertEqual(200, response.status_code)
        self.assertTrue(user == data['user'])  #check the user
Exemple #31
0
 def submit_upc_map(self, request: Request):
     user = get_user_id_from_request(request)
     map_list = json.loads(request.data.get('map_list', None))
     if user and map_list:
         user = User(id=user)
         for code in map_list:
             for list_item in code:
                 upc_id = Upc.get_upc_id(list_item.get('upc', None))
                 upc_id = Upc(id=upc_id.id)
                 item_id = Item.get_item_id(list_item.get('item', None))
                 item_id = Item(id=item_id.id)
                 upc_list = UpcMap(user_id=user,
                                   upc=upc_id,
                                   item=item_id,
                                   amount=list_item.get('amount', 0))
                 upc_list.save(force_insert=True)
         return Response(status=200)
     else:
         return HttpResponse(status=401)