Ejemplo n.º 1
0
 def post(cls):
     data = request.get_json()
     user = UserSchema().load(data)
     if User.find_by_email(user.email):
         return response_with(
             resp.BAD_REQUESTS_400,
             message=USER_ALREADY_EXISTS,
         )
     try:
         user.save_to_db()
         confirmation = Confirmation(user.id)
         confirmation.save_to_db()
         user.send_confirmation_email()
         return response_with(resp.SUCCESS_201,
                              message=SUCCESS_REGISTER_MESSAGE)
     except MailgunException as e:
         user.delete_from_db()
         return response_with(resp.SERVER_ERROR_500, message=str(e))
     except IntegrityError as err:
         return response_with(resp.BAD_REQUESTS_400,
                              message=USER_ALREADY_EXISTS)
     except:
         traceback.print_exc()
         user.delete_from_db()
         return response_with(resp.SERVER_ERROR_500,
                              message=FAILED_TO_CREATE)
Ejemplo n.º 2
0
    def delete(self, uuid: str) -> tuple:
        """Delete a user from the database.

        Delete a user with provided UUID and returns user info.

        Args:
            uuid (str): UUID of user to delete.

        Returns:
            tuple: (User Info | Error Message, HTTP Return Code)
        """
        # Confirm UUID is valid
        if not uuid_is_valid(uuid):
            return {"message": "{uuid} is not a valid UUID".format(uuid=uuid)}, 400

        # Confirm user exists
        existing_user = db.session.query(UserModel).filter_by(uuid=uuid).first()
        if existing_user is None:
            return {"message": "No user with uuid {uuid} found.".format(uuid=uuid)}, 404

        # Confirm user exists
        existing_user = db.session.query(UserModel).filter_by(uuid=uuid).first()
        if existing_user is None:
            return {"message": "User with uuid {uuid} not found.".format(uuid=uuid)}, 404

        # Delete user
        db.session.delete(existing_user)
        db.session.commit()

        # Return Deleted User w/o ID or Password info
        user_schema = UserSchema()
        return user_schema.dump(existing_user), 200
Ejemplo n.º 3
0
    def get(cls):

        page = request.args.get("page", 1, type=int)
        pagination = User.query.paginate(
            page,
            per_page=current_app.config["USERS_PER_PAGE"],
            error_out=False)
        get_users = pagination.items
        prev = None
        if pagination.has_prev:
            prev = url_for("user-list", page=page - 1)
        _next = None
        if pagination.has_next:
            _next = url_for("user-list", page=page + 1)

        users_schema = UserSchema(many=True, exclude=("posts", ))
        users = users_schema.dump(get_users)

        return response_with(
            resp.SUCCESS_200,
            value={"users": users},
            pagination={
                "prev": prev,
                "next": _next,
                "count": pagination.total
            },
        )
Ejemplo n.º 4
0
def get_user(user_id):
    user = User.query.get(user_id)
    if user == None:
        abort(404)

    user_schema = UserSchema()
    return user_schema.jsonify(user)
Ejemplo n.º 5
0
def get_user_details(uid):
    try:
        user = User.query.filter_by(id=uid).first()
        if not user:
            message = notFound.format("User")
            return response_with(resp.NOT_FOUND_HANDLER_404, message=message)

        user_schema = UserSchema()
        user_data, error = user_schema.dump(user)

        json_count = Json.count_json(uid)
        team_count = Team.count_teams(uid)

        val = {
            'id': user_data['id'],
            'name': user_data['name'],
            'surname': user_data['surname'],
            'email': user_data['email'],
            'login': user_data['login'],
            'created': user_data['created'],
            'updated': user_data['updated'],
            'json_count': json_count,
            'team_count': team_count
        }

        return response_with(resp.SUCCESS_200, value=val)
    except Exception as e:
        logging.error(e)
        return response_with(resp.SERVER_ERROR_500)
Ejemplo n.º 6
0
def update_user(id):
    fetched = request.get_json()
    resource = User.query.get_or_404(id)
    for key, value in fetched.items():
        setattr(resource, key, value)
    user_schema = UserSchema()
    data = user_schema.dump(resource.update()).data
    return response_with(resp.SUCCESS_200, value={'data': data})
Ejemplo n.º 7
0
def create_user():
    try:
        data = request.get_json()
        user_schema = UserSchema()
        user, error = user_schema.load(data)
        result = user_schema.dump(user.create()).data
        return response_with(resp.SUCCESS_200, value={"user": result})
    except Exception as e:
        logging.error(e)
        return response_with(resp.INVALID_INPUT_422)
Ejemplo n.º 8
0
def create_user():
    username = request.json['username']
    email = request.json['email']
    user = User(username, email)

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

    user_schema = UserSchema()
    return user_schema.jsonify(user)
Ejemplo n.º 9
0
def delete_user(user_id):
    user = User.query.get(user_id)
    if user == None:
        abort(404)

    db.session.delete(user)
    db.session.commit()

    user_schema = UserSchema()
    return user_schema.jsonify(user)
Ejemplo n.º 10
0
    def put(cls, _id):
        user = User.query.get_or_404(_id)
        updatable_fields = ("first_name", "last_name", "username", "avatar",
                            "bio")
        data = request.get_json()

        user_schema = UserSchema(only=updatable_fields)
        updated_user_info = user_schema.load(data, instance=user, partial=True)
        result = UserSchema(only=updatable_fields).dump(
            updated_user_info.save_to_db())
        return response_with(resp.SUCCESS_200, value={"user": result})
Ejemplo n.º 11
0
def add_user():
    # fetched = request.get_json()
    # import json
    # return json.dumps(fetched)
    try:
        fetched = request.get_json()
        user_schema = UserSchema()
        user, error = user_schema.load(fetched)
        data = user_schema.dump(user.create()).data
        return response_with(resp.SUCCESS_200, value={'data': data})
    except:
        return response_with(resp.INVALID_INPUT_422)
Ejemplo n.º 12
0
def registe():
    fetched = request.get_json()
    user = User.query.filter_by(email=fetched['email']).first()
    if not user:
        try:
            user_schema = UserSchema()
            user, error = user_schema.load(fetched)
            user = user_schema.dump(user.create()).data
            return response_with(resp.SUCCESS_200)

        except Exception as e:
            return response_with(resp.SERVER_ERROR_500)
    else:
        return response_with(resp.INVALID_INPUT_422)
Ejemplo n.º 13
0
def update_user(user_id):
    user = User.query.get(user_id)
    if user == None:
        abort(404)

    username = request.json['username']
    email = request.json['email']

    user.username = username
    user.email = email

    db.session.commit()

    user_schema = UserSchema()
    return user_schema.jsonify(user)
Ejemplo n.º 14
0
    def post(self) -> tuple:
        """Creates a new user in the database.

        Creates a user with provided information, auto generated uuid and hashed password.

        Returns:
            tuple: (User Info | Error Message, HTTP Return Code)
        """
        # Check for JSON content
        new_user_json = request.get_json(silent=True)
        if new_user_json is None:
            return {"message": "Could not parse JSON"}, 500

        # Check for missing keys
        keys_to_look_for = ["first_name", "last_name", "email", "password"]
        for key in keys_to_look_for:
            if key not in new_user_json:
                return {"message": "Missing key: {key}".format(key=key)}, 422

        # Check for existing user by email
        existing_user = db.session.query(UserModel).filter_by(
            email=new_user_json["email"]).first()
        if existing_user is not None:
            return {"message": "A user with email address {email} already exists.".format(
                email=new_user_json["email"])}, 409

        # Create argon2 Password Hash
        password_hash = ph.hash(new_user_json["password"])

        # Create New User
        new_user = UserModel(
            first_name=new_user_json["first_name"],
            last_name=new_user_json["last_name"],
            email=new_user_json["email"],
            password_hash=password_hash
        )

        # Add User to Database
        db.session.add(new_user)
        db.session.commit()

        # Return Created User w/o ID or Password info
        user_schema = UserSchema()
        return user_schema.dump(new_user), 200
Ejemplo n.º 15
0
    def post(self):
        args = self.reqparse.parse_args()
        user = UserModel(args.name, args.state)

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

        response = UserSchema().dump(user)

        return response, 201
Ejemplo n.º 16
0
    def get(self, uuid: str) -> tuple:
        """Returns user info for given UUID.

        Args:
            uuid (str): UUID of user to lookup.

        Returns:
            tuple: (User Info | Error Message, HTTP Return Code)
        """
        # Confirm UUID is valid
        if not uuid_is_valid(uuid):
            return {"message": "{uuid} is not a valid UUID".format(uuid=uuid)}, 400

        # Confirm user exists
        existing_user = db.session.query(UserModel).filter_by(uuid=uuid).first()
        if existing_user is None:
            return {"message": "No user with uuid {uuid} found.".format(uuid=uuid)}, 404

        # Return User w/o ID or Password info
        user = UserSchema()
        return user.dump(existing_user), 200
Ejemplo n.º 17
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.º 18
0
def get_users():
    resource = User.query.all()
    user_schema = UserSchema(many=True)
    data = user_schema.dump(resource).data
    return response_with(resp.SUCCESS_200, value={'data': data})
Ejemplo n.º 19
0
def create_user():

    """
    Create user endpoint
    ---

    parameters:
      - in: body
        name: body
    schema:
      id: UserSignup
      required:
        - username
        - password
        - email
      properties:
        username:
          type: string
          description: Unique username of the user
          default: "Johndoe"
        password:
          type: string
          description: email of the user
          default: "*****@*****.**"
        email:
          type: string
          description: email of the user
          default: "*****@*****.**"
    responses:
      201:
        description: User successfully created
        schema:
          id: UserSignUpSchema
          properties:
            code:
              type: string
      422:
        description: Invalid input arguments
        schema:
          id: invalidInput
          properties:
            code:
              type: string
            message:
              type: string
    """
    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)
        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 forsigning 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_schmea.dump(user.create())
        return response_with(resp.SUCCESS_201)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Ejemplo n.º 20
0
 def get(cls, _id):
     get_user = User.query.get_or_404(_id)
     user = UserSchema().dump(get_user)
     return response_with(resp.SUCCESS_200, value={"user": user})
Ejemplo n.º 21
0
 def get(self, id):
     user = db.session.query(UserModel).filter_by(id=id).first()
     json = UserSchema().dump(user)
     return json, 201
Ejemplo n.º 22
0
def get_users():
    users = User.query.all()
    users_schema = UserSchema(many=True)
    return users_schema.jsonify(users)
Ejemplo n.º 23
0
 def get(self):
     results = UserModel.query.all()
     jsonData = UserSchema(many=True).dump(results)
     return jsonData, 201