示例#1
0
def register():
    body = request.get_json()
    try:
        # userRegistrationSchema.validate(body)
        username = body.get('username')
        user_email = body.get('email')
        firstname = body.get('firstname')
        lastname = body.get('lastname')
        gender = body.get('gender')
        password = body.get('password')

        user_password = bcrypt.generate_password_hash(
            password=password).decode('utf-8')

        users_registered = User.objects(username=username)
        if len(users_registered) == 0:
            User(username=username,
                 email=user_email,
                 password=user_password,
                 gender=gender,
                 firstname=firstname,
                 lastname=lastname).save()
            new_profile = User.objects(username=username)[0]
            return {
                'username': new_profile.username,
                'email': new_profile.email,
                'token': get_token()
            }, 201
        else:
            return jsonify({'message': 'User already exists!'}), 409
    except Exception as e:
        return {'error': str(e)}, 400
def create_test_data(file):

    conn = sqlite3.connect(file)
    conn.row_factory = sqlite3.Row
    cursor = conn.cursor()
    users = [
        User("pabloi09", "password").to_insert(),
        User("prueba", "password").to_insert(),
        User("prueba2", "password").to_insert(),
    ]

    with open(PROJECT_PATH.format(
            "reddit_downloader/config.json")) as json_config:
        reddit_config = json.load(json_config)

    with open(PROJECT_PATH.format("twitter_util/config.json")) as json_config:
        twitter_config = json.load(json_config)

    with open(
            PROJECT_PATH.format("instagram_util/config.json")) as json_config:
        insta_config = json.load(json_config)

    projects = [
        Project(reddit_config, twitter_config, insta_config, 1).to_insert(),
        #Project(reddit_config, twitter_config, insta_config,1).to_insert(),
        #Project(reddit_config, twitter_config, insta_config,2).to_insert(),
        #Project(reddit_config, twitter_config, insta_config,3).to_insert(),
        #Project(reddit_config, twitter_config, insta_config,3).to_insert(),
    ]

    cursor.executemany(
        "INSERT INTO project(reddit_config, twitter_config, insta_config, user_id) VALUES (?,?,?,?)",
        projects)
    conn.commit()
    cursor.execute("select * from project")
    projects = cursor.fetchall()
    for project in projects:
        p = Project.from_database(project)
        p.reddit_config["path"] = REDDIT_PATH.format(p.user_id, p.project_id)
        p.insta_config["cookie_location"] = INSTA_PATH.format(
            p.user_id, p.project_id)
        q = p.to_insert()
        cursor.execute(
            "UPDATE project SET reddit_config = ?, insta_config = ? WHERE project_id = ?",
            (q[0], q[2], p.project_id))
        cursor.executemany(
            "INSERT INTO tw_engagement(username, project_id) VALUES (?,?)",
            [(username, p.project_id)
             for username in twitter_config["engagement_accounts"]])
        cursor.executemany(
            "INSERT INTO insta_engagement(username, project_id) VALUES (?,?)",
            [(username, p.project_id)
             for username in insta_config["engagement_accounts"]])
        conn.commit()

    conn.close()
示例#3
0
 def get_statistics(cls, company_id: str) -> dict:
     """
     Returns a statistics report per company
     """
     return {
         "time": datetime.utcnow(),
         "company_id": company_id,
         "server": {
             "version":
             current_version,
             "deployment":
             get_deployment_type(),
             "uuid":
             get_server_uuid(),
             "queues": {
                 "count": Queue.objects(company=company_id).count()
             },
             "users": {
                 "count": User.objects(company=company_id).count()
             },
             "resources":
             cls.threads.resource_monitor.get_stats(),
             "experiments":
             next(iter(cls._get_experiments_stats(company_id).values()),
                  {}),
         },
         "agents": cls._get_agents_statistics(company_id),
     }
示例#4
0
    def get(self):
        """[Retrieves all Boards by user]
        
        Raises:
            InternalServerError: [If Error in retrieval]
        
        Returns:
            [json] -- [Json object with message and status code]
        """
        try:
            user_id = get_jwt_identity()
            user = User.objects(id=ObjectId(user_id)).only('username')
            now = datetime.datetime.now()
            boards = Board.objects(added_by=ObjectId(user_id))
            boards_list = []
            for board in boards:
                board_dict = board.to_mongo().to_dict()
                data = timeago.format(board.created_at, now)
                board_dict['time_stamp'] = data
                board_dict['username'] = user[0].username
                boards_list.append(board_dict)
            res = {'data': boards_list, 'message': "Successfully retrieved", "count": len(boards_list)}
            boards_josn = dumps(res)
            return Response(boards_josn, mimetype="application/json", status=200)


        except Exception as e:
            print(e)
            raise InternalServerError
示例#5
0
    def save(self, _dict):
        user = User(**_dict)

        database.session.add(user)
        database.session.commit()

        return user
示例#6
0
def create_user():
    try:
        body = request.get_json()
        body['password'] = bcrypt.generate_password_hash(body['password'])
        User(**body).save()
        return make_response({"completed": "true"}, 200)
    except:
        return make_response({"error": "Bad Request"}, 400)
示例#7
0
 def get(self, id):
     try:
         user = User.objects(id=id).to_json()
         return Response(user, mimetype="application/json", status=200)
     except DoesNotExist:
         raise UserNotExistsError
     except Exception as err:
         raise InternalServerError
示例#8
0
def register():
    if request.method == 'POST':
        try:
            User(username=request.form['username'], password=request.form['password']).save()
            return redirect(url_for('login'))
        except:
            return render_template('index.html', message="User Already Exists")
    else:
        return render_template('register.html')
示例#9
0
def login():
    body = request.get_json()
    username = body.get('username')
    password = body.get('password')
    profile = User.objects(username=username).first()
    if profile and bcrypt.check_password_hash(profile.password, password):
        token = get_token()
        Session(username=username, session_id=token).save()
        return {'token': token}, 200
    return {'message': 'Invalid username or password'}, 401
示例#10
0
def sign_up():
    body = request.get_json()
    user = User(**body)
    user.hash_password()
    user.save()
    id = user.id
    return {'id': str(id)}, 200
示例#11
0
 def post():
     """[Signup]
     
     Raises:
         SchemaValidationError: [Error in data]
         EmailAlreadyExistsError: [Email exists]
         InternalServerError: [Query error]
     
     Returns:
         [json] -- [Json object with message and status code]
     """
     try:
         body = request.get_json()
         user = User(**body)
         user.hash_password()
         user.save()
         userId = user.id
         return tokenCreation(user, body, "Successfully signed up", userId)
     except FieldDoesNotExist as e:
         print(e)
         raise SchemaValidationError
     except NotUniqueError as e:
         print(e)
         for field in User._fields:  # You could also loop in User._fields to make something generic
             if field in str(e):
                 if field == 'username':
                     raise UserNameDoesnotExistsError
                 if field == 'email':
                     raise EmailAlreadyExistsError
     except Exception as e:
         print(e)
         raise InternalServerError
def create_user():
    user_schema = user.UserSchema(strict=True, many=False)
    user_data = request.get_json()

    data = user_schema.load(user_data).data    
    print(data)
    new_user = User(name=data["name"])
    session.add(new_user)
    session.commit()
    
    result = user_schema.dump(new_user)

    return jsonify(result[0])
示例#13
0
def create_user(data):
    try:
        user = User(name=data['name'],
                    email=data['email'],
                    password=data['password'])
        db.session.add(user)
        db.session.commit()
        return make_response(
            jsonify({
                'message': 'data added to database',
                'user_id': user.id
            }), 200)
    except Exception as e:
        return make_response(jsonify({'message': e.__doc__}), 500)
示例#14
0
 def post(self):
     try:
         body = request.get_json()
         password_hash = generate_password_hash(body.get('password'))
         body['password'] = password_hash
         user = User(**body).save()
         id = user.id
         return {'msg': 'user is created successfully', 'id': str(id)}, 200
     except (FieldDoesNotExist, ValidationError):
         raise SchemaValidationError
     except NotUniqueError:
         raise UserAlreadyExistsError
     except Exception as err:
         raise InternalServerError
 def post(self):
     # Creates a User in the db. Do not pass in a user_id, the DB created this!
     parser = reqparse.RequestParser()
     parser.add_argument('first_name', type=str, required=True)
     parser.add_argument('last_name', type=str, required=True)
     parser.add_argument('email', type=email, required=True)
     parser.add_argument('phone', type=str, required=True)
     parser.add_argument('paypal_id', type=str, required=True)
     parser.add_argument('password', type=str, required=True)
     parser.add_argument('saved_address', type=str, required=True)
     args = parser.parse_args(strict=True)
     new_user = self.update_sqlachemy_object(User(), args)
     db.session.add(new_user)
     db.session.commit()
     return self.make_response_from_sqlalchemy(
         new_user), 201  # HTTP 201 CREATED
示例#16
0
def new_user(user_data: User_Create, db: Session = Depends(get_db)):
    '''
    Add new user to the System

    Args:
        User_Create schema data format provide details to add new user
    Response:
        200 - data of the new user is returned. Data in User_Create schema format
        400 - when user email ID already exists. Response in json data
    '''
    try:
        user = User(**user_data.dict())
        db.add(user)
        db.commit()
        return user
    except:
        raise HTTPException(status_code=400, detail="User already exists")
示例#17
0
 def get(self):
     users = User.objects().to_json()
     return Response(users, mimetype="application/json", status=200)
示例#18
0
 def post(self):
     body = request.get_json()
     user = User(**body).save()
     id = user.id
     return {'id': str(id)}, 200
示例#19
0
def oauth_callback(provider):
    if current_app.debug:
        print("OAuth Callback called with provider : {}".format(provider))

    if not current_user.is_anonymous():
        flash('Already logged in!')
        return redirect(url_for('welcome_page'))

    oauth = OAuthSignIn.get_provider(provider)
    oauth_data = oauth.callback()

    if not check_authorization(oauth_data):
        if current_app.debug:
            print("OAuth data:")
            for k,v in oauth_data.items():
                print("{} : {}".format(k,v))
        flash('Authentication failed!', category='warning')
        return redirect(url_for('welcome_page'))
   
    provider = oauth_data.get('provider')
    oauth_id = oauth_data.get('id')
    nickname = oauth_data.get('nickname')
    email = oauth_data.get('email')
    name = oauth_data.get('name')

    # TODO: The following fails if there are more than one oauth_id (should not happen, since unique field)
    try:
        oauthuser = OAuthUser.query.filter_by(provider=provider).filter_by(oauth_id=oauth_id).scalar()
    except MultipleResultsFound as e:
        if current_app.debug:
            print("Error. Multiple results were found from unique field: {}".format(str(e)))
        return abort(500)

    if not oauthuser:
        # If oauthuser was not found, we check whether we can match email and nickname to an existing use (potential security hazard!)
        try:
            user = User.query.filter_by(email=email).scalar()
        except MultipleResultsFound as e:
            if current_app.debug:
                print("Error. Multiple results were found from unique field: {}".format(str(e)))
            return abort(500)

        if not user:
            numusers = User.query.count()
            user = User(email=email, nickname=nickname, name=name)
            if numusers == 0:
                # First user is admin
                user.admin = True
            db.session.add(user)

        oauthuser = OAuthUser(provider=provider, oauth_id=oauth_id, user=user)
        db.session.add(oauthuser)
        db.session.commit()

    else:
        user = oauthuser.user

    login_user(user, remember=True)

    flash('Login successful.')
    return redirect(url_for('welcome_page'))
def seed_users():
    return [
        User(name="seed_user_1"),
        User(name="seed_user_2"),
    ]