コード例 #1
0
    def test_get_by_id(self):
        """Get user by ID."""
        user = User('*****@*****.**')
        user.save()

        retrieved = User.get_by_id(user.id)
        assert retrieved == user
コード例 #2
0
def create():
    errors = User.validate(request.form)
    if errors:
        for error in errors:
            flash(error)
        return redirect(url_for('users:login_and_registration'))
    user_id = User.create(request.form)
    session['user_id'] = user_id
    return redirect(url_for("dashboard"))
コード例 #3
0
async def add_user_data(user: User = Body(...)):
    user = jsonable_encoder(user)
    password = user['password']
    user.pop('password')
    user['hashed_password'] = pwd_context.hash(password)
    new_user = await add_user(user)
    if new_user:
        return ResponseModel.return_response(new_user,
                                             'User added successfully')
    return ErrorResponseModel.return_response(
        'An error occurred', status.HTTP_403_FORBIDDEN,
        f'The username {user["username"]} is not available!')
コード例 #4
0
ファイル: auth.py プロジェクト: MohamedRaffik/YT-Collections
def callback():
    if session.get('error', None):
        return redirect('/')

    if session['state'] != request.args.get('state', None):
        return redirect('/')

    tokens = google_api.get_oauth_tokens(
        url_for('server.routes.auth.callback', _external=True),
        request.args['code'])
    email = google_api.get_user_email(tokens['access_token'])
    user = User.get(email)

    if not user:
        user = User(_id=email,
                    subscriptions=[],
                    collections={},
                    credentials=google_api.create_credentials(tokens),
                    job_id=None,
                    last_updated=datetime.utcnow())
        job = queue.enqueue('server.utils.google_api.build_collections',
                            access_token=tokens['access_token'],
                            username=email)
        user.job_id = job.id
        user.insert()
    else:
        user.update({'credentials': google_api.create_credentials(tokens)})

    login_user(user, remember=True, duration=timedelta(30))

    return redirect('/')
コード例 #5
0
def login():
    valid, response = User.login_helper(request.form)
    if not valid:
        flash(response)
        return redirect(url_for("users:login_and_registration"))
    session['user_id'] = response
    return redirect(url_for("dashboard"))
コード例 #6
0
def create():
    # @A1aaaaa
    alerts = User.validate(request.form)
    if len(alerts) > 0:
        print(len(alerts))
        if len(alerts) == 5:
            print(len(alerts))
            flash('All fields are required!')
            return redirect('/portfolio/user/register')
        else:
            print(len(alerts))
            for alert in alerts:
                flash(alert)
            return redirect('/portfolio/user/register')
    else:
        User.create(request.form)
        return redirect('/portfolio/user/thankyou')
コード例 #7
0
    def put(self, args, user_id):
        """Update a user."""
        user = User.get_by_id(user_id)
        if user:
            user = user.update(**args)
            return marshal(user, resource_fields), 201

        return 'User not found', 404
コード例 #8
0
def create():
    # @A1aaaaa
    alerts = User.validate(request.form)
    if len(alerts) > 0:
        print(alerts)
        if len(alerts) == 10:
            flash('All fields are required!')
            # return redirect('/user/register')
            return render_template('/partials/alerts.html'), 500   
        else:
            for alert in alerts:
                flash(alert)
            # return redirect('/user/register') 
            return render_template('/partials/alerts.html'), 500
    else:
        user_id = User.create(request.form)
        session['user_id'] = user_id
        return redirect('/user/thankyou')
コード例 #9
0
    def post(self, args):
        """Register user."""
        user = User.query.filter_by(email=args['email']).first()
        if user:
            return 'Email already registered', 409

        new_user = User.create(email=args['email'], password=args['password'])

        send_confirmation_email(new_user.email)
        return marshal(new_user, resource_fields), 201
コード例 #10
0
def login():
    username = request.json['username']
    password = request.json['password']

    user = User.by_username_password(username, password)
    if not user:
        return abort(401, "Incorrect username or password")

    session["user_id"] = user.id
    return jsonify({'username': user.username, 'loggedIn': True})
コード例 #11
0
def editing(user_id):
    user = User.query.get(user_id)
    errors = User.edit_validate(request.form)
    if errors:
        for error in errors:
            flash(error)
        return redirect(url_for('users:edit'))
    user.username = request.form['username']
    db.session.commit()
    return redirect(url_for('dashboard'))
コード例 #12
0
    def test_create_user(self, testapp):
        """Test create user through api."""
        res = testapp.post('/api/users', {
            'email': '*****@*****.**',
            'password': '******',
        },
                           status=201)
        user_id = res.json['id']

        assert res.json['email'] == '*****@*****.**'
        assert res.json['active'] is False
        assert User.get_by_id(user_id)
コード例 #13
0
ファイル: signup.py プロジェクト: gbengaPS/hellobooks
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('email',
                         required=True,
                         help='email field is required')
     parser.add_argument('full_name',
                         required=True,
                         help='full_name field is required')
     parser.add_argument('username',
                         required=True,
                         help='username field is required')
     parser.add_argument('password',
                         required=True,
                         help='password field is required')
     parser.parse_args()
     full_name = request.form['full_name']
     email = request.form['email']
     password = request.form['password']
     username = request.form['username']
     user = User(full_name, username, email, password)
     check_user = user.check_username_email(username, email)
     if check_user == None:
         user.save()
         user_details = {
             'id': user.id,
             'username': user.username,
             'email': user.email,
             'full_name': user.full_name
         }
         token = create_access_token(identity=user.id)
         return {
             'message': 'User created successfully',
             'user': user_details,
             'token': token
         }
     else:
         if check_user.username == username:
             return {'message': 'Username already in use'}, 409
         else:
             return {'message': 'Email already in use'}, 409
コード例 #14
0
def register():
    autologin = request.args.get("autologin", default="True").lower() == "true"

    username = request.json.get('username')
    password = request.json.get('password')

    user = User.try_register(username, password)
    if not user:
        print(username, password)
        return abort(400, "Invalid username or password")

    if autologin:
        session["user_id"] = user.id

    return jsonify({'username': user.username, 'loggedIn': autologin})
コード例 #15
0
def load_user(email):
    return User.get(email)
コード例 #16
0
def build_collections(access_token: str, username: str):
    subs, info = [], {'nextPageToken': ''}
    q = Queue()
    threads = []

    params = {
        'part': 'snippet',
        'mine': True,
        'maxResults': 50,
        'pageToken': info['nextPageToken']
    }

    while 'nextPageToken' in info:
        info = get(url='https://www.googleapis.com/youtube/v3/subscriptions',
                   headers={
                       'Authorization': f'Bearer {access_token}'
                   },
                   params={
                       **params, 'pageToken': info['nextPageToken']
                   }).json()
        subs.append({
            item['snippet']['resourceId']['channelId']: None
            for item in info['items']
        })
        threads.append(Thread(target=getTopics, args=(subs[-1].keys(), q)))
        threads[-1].start()

    topic_map = {
        '/m/04rlf': 'Music',
        '/m/0bzvm2': 'Gaming',
        '/m/06ntj': 'Sports',
        '/m/02jjt': 'Entertainment',
        '/m/019_rr': 'Lifestyle',
        '/m/01k8wb': 'Knowledge',
        '/m/098wr': 'Society'
    }

    collections = {
        'Music': [{}],
        'Gaming': [{}],
        'Sports': [{}],
        'Entertainment': [{}],
        'Lifestyle': [{}],
        'Knowledge': [{}],
        'Society': [{}]
    }

    pages = {
        'Music': 0,
        'Gaming': 0,
        'Sports': 0,
        'Entertainment': 0,
        'Lifestyle': 0,
        'Knowledge': 0,
        'Society': 0
    }

    for thread in threads:
        thread.join()

        info = q.get()

        for item in info['items']:
            if 'topicDetails' in item:
                for topic in set(item['topicDetails']['topicIds']):
                    if topic in topic_map:
                        t = topic_map[topic]
                        if len(collections[t][pages[t]]) == 50:
                            collections[t].append({})
                            pages[t] += 1
                        collections[t][pages[t]][item['id']] = None

    user = User.get(username)
    user.update({
        'subscriptions': subs,
        'collections': collections,
        'job_id': None
    })
    print('finished')
コード例 #17
0
 def test_created_at_defaults_to_datetime(self):
     """Test creation date."""
     user = User(email='*****@*****.**')
     user.save()
     assert bool(user.created_at)
     assert isinstance(user.created_at, dt.datetime)
コード例 #18
0
 def test_password_is_nullable(self):
     """Test null password."""
     user = User(email='*****@*****.**')
     user.save()
     assert user.password is None
コード例 #19
0
 def test_check_password(self):
     """Check password."""
     user = User.create(email='*****@*****.**', password='******')
     assert user.check_password('foobarbaz123') is True
     assert user.check_password('barfoobaz') is False
コード例 #20
0
 def get(self, user_id):
     """Get a user."""
     user = User.get_by_id(user_id)
     if user:
         return marshal(user, resource_fields), 201
     return 'User not found', 404