示例#1
0
 def tearDown(self):
     #delete all from users
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
示例#2
0
    def setUp(self):
        # disabling logs
        logging.disable(logging.CRITICAL)
        self.app = app.test_client()
        # connecting to the database
        db.connect()
        # creating tables
        db.create_tables([User], safe=True)
        db.create_tables([State], safe=True)
        db.create_tables([City], safe=True)
        db.create_tables([Place], safe=True)
        db.create_tables([PlaceBook], safe=True)

        # Creating a setUp
        new_state = State(name='California')
        new_state.save()
        new_city = City(name='San Francisco', state=1)
        new_city.save()
        # Creating a new users
        user1 = User(first_name='Jon',
                     last_name='Snow',
                     email='jon@snow',
                     password='******')
        user1.save()
        new_place = Place(owner=1,
                          city=1,
                          name="Steven",
                          description="house",
                          number_rooms=3,
                          number_bathrooms=2,
                          max_guest=3,
                          price_by_night=100,
                          latitude=37.774929,
                          longitude=-122.419416)
        new_place.save()
示例#3
0
 def setUp(self):
     #connect to db and delete everyone in the users table
     PlaceBook.delete().execute()
     Place.delete().execute()
     User.delete().execute()
     City.delete().execute()
     State.delete().execute()
示例#4
0
def create_new_user():
    post_data = request.values
    keys = ["first_name", "last_name", "email", "password"]
    for key in keys:
        if key not in post_data:
            return {"code":400, "msg":"incorrect parameters"}, 400
    email_query = User.select().where(User.email == post_data['email'])
    if email_query.exists():
        out = {
            'code': 10000, 
            'msg': 'Email already exists'
        }
        return out, 409
    try:
        user_row = User.create(
            password = "******",
            first_name = post_data['first_name'],
            last_name = post_data['last_name'],
            email = post_data['email']
        )
        user_row.password = user_row.set_password(post_data['password'])
        if 'is_admin' in post_data:
            if post_data['is_admin'].lower() == "true":
                user_row.is_admin = True
            elif post_data['is_admin'].lower() == "false":
                user_row.is_admin = False
        user_row.save()
        return user_row.to_hash()
    except:
        return {"code":400, "msg":"incorrect parameters"}, 400
示例#5
0
def users():
    """Handle GET and POST requests to /users route.

    Return a list of all users in the database in the case of a GET request.
    Create a new user record in the database in the case of a POST request.
    """
    # handle GET requests:
    # --------------------------------------------------------------------------
    if request.method == 'GET':
        list = ListStyle.list(User.select(), request)
        return jsonify(list)

    # handle POST requests:
    # --------------------------------------------------------------------------
    elif request.method == 'POST':
        try:
            record = User(
                email=request.form["email"],
                password=request.form["password"],
                first_name=request.form["first_name"],
                last_name=request.form["last_name"]
            )
            record.save()
            return jsonify(record.to_hash())

        # return 409 if user with given email already exists
        except IntegrityError:
            return json_response(
                add_status_=False,
                status_=409,
                code=10000,
                msg="Email already exists"
            )
示例#6
0
 def test_returns_current_user(self):
     u = User(name='Numpy', google_id='12345', email='*****@*****.**')
     u.save()
     with app.test_request_context():
         session['user_id'] = '12345'
         c_user = current_user()
         self.assertEqual(c_user, u)
示例#7
0
def create_database():
    try:
         User.create_table()
    except peewee.OperationalError:
        pass

    try:
         State.create_table()
    except peewee.OperationalError:
        pass

    try:
         City.create_table()
    except peewee.OperationalError:
        pass

    try:
         Place.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceBook.create_table()
    except peewee.OperationalError:
        pass

    try:
         Amenity.create_table()
    except peewee.OperationalError:
        pass

    try:
         PlaceAmenities.create_table()
    except peewee.OperationalError:
        pass
示例#8
0
 def test_login_with_other_credentials(self):
     user2 = User(name='user2', email='email2em.co')
     user2.password = hashlib.md5('pass2').hexdigest()
     db.session.add(user2)
     db.session.commit()
     response = self.login('user1', 'pass2')
     self.assertEqual(response.status_code, 401)
示例#9
0
def users():
    if request.method == 'GET':
        try:
            # Getting all the users
            list = ListStyle.list(User.select(), request)
            return jsonify(list)
        except:
            return make_response(jsonify({'code': 10000,
                                          'msg': 'users not found'}), 404)

    elif request.method == 'POST':
        user_email = request.form["email"]
        user_password = request.form["password"]
        user_first_name = request.form["first_name"]
        user_last_name = request.form["last_name"]
        try:
            new_user = User(email=user_email,
                            first_name=user_first_name,
                            last_name=user_last_name,
                            password=md5.new(user_password).hexdigest())
            new_user.save()
            return jsonify(new_user.to_dict())
        except:
            return make_response(jsonify({'code': 10000,
                                          'msg': 'email already exist'}), 409)
示例#10
0
  def get(self):
    response = fetch( \
      "https://rpxnow.com/api/v2/auth_info",
      payload = "apiKey=%s&token=%s" % \
    (
      "c53e2281f9009394b91c66e3a1914209b69cb4cd",
      self.request.get('token')
        ),
      method = POST
    )
    obj = parse_json(response.content)
    if response.status_code != 200 or obj['stat'] == 'fail':
      self.response.out.write("Fail! " + response.content)
      return


    if self.user:
      if 'identifier' in obj['profile']:
        user = User.all().filter('identifier', obj['profile']['identifier']).get()
	if user:
          self.render_error('already_exists', {'user' : user })
	  return
      self.user.verified = True
      self.user.update_from_profile(obj['profile'])
    else:
      self.user = User.from_profile(obj['profile'])

    self.generate_authenticity_token()
      
    self.redirect('/')
示例#11
0
def create_user(name, email, user_id, key=None):
    """
    Takes an optional key and a name, email, and user_id to create a user
    If key is not provided, one will be created from the user_id
    """
    if not name:
        raise ValueError("name is required")
    if not email:
        raise ValueError("email is required")
    if not user_id:
        raise ValueError("user_id is required")
    if not key:
        # Make our own dang key!
        key = User.build_key(user_id)

    kwargs = {
        'name': name,
        'email': email,
        'user_id': user_id
    }
    user = User(key=key, **kwargs)

    user.put()

    return user
示例#12
0
    def post(self):
        args = self.parser.parse_args()
        email = args['email']
        password = args['password']
        first = args['first']
        last = args['last']
        age_check = args.get('ageCheck', "true")
        age_check = True if age_check == "true" else False

        if email is None or len(email) < 3:
            return {'status': 'false', 'message': 'Invalid email'}, 400
        
        if password is None or len(password) < 4:
            return {'status': 'false', 'message': 'Invalid password (minimum length of 4)'}, 400

        if len(first) == 0 or len(last) == 0:
            return {'status': 'false', 'message': 'You must enter a first name and last name'}, 400

        if User.fetch_user_by_email(email) is not None:
            return {"status": "false", 'message': 'Email already in use'}, 400

        user = User.create_user(email, password, first, last, age_check)
        
        if user:
            return {'status': 'true'}, 201
        else:
            return {'status': 'false'}, 400
示例#13
0
def login_by_github_callback():
    """Github OAuth 回调
    """
    code, info = OAuthSignIn.get_provider('github').callback()
    if code is None:
        raise OAuthFail()

    user = User.query.filter_by(github_id = info.get('id')).first()
    if user is None:
        user = User(
                github_id = info.get('id'),
                nickname = info.get('login'),
                name = info.get('name'),
                avatar = info.get('avatar_url'),
                bio = info.get('bio'),
        )
        db.session.add(user)

    # update github info
    user.github_login = info.get('login')
    user.github_email = info.get('email')
    user.github_name = info.get('name')

    # update oauth code
    user.oauth_code = code
    db.session.commit()

    # 如果是admin来请求oauth
    if request.referrer == url_for('admin.admin_login', _external = True):
        if user.github_email in current_app.config['TECHSHOW_ADMIN']:
            login_user(user)
            return redirect(url_for('admin.admin_index'))

    return render_template('oauth_pending.html', oauth_logo = '/static/images/github_logo.png')
示例#14
0
def login_by_qiniu_callback():
    """Qiniu OAuth 回调
    """
    code, info = OAuthSignIn.get_provider('qiniu').callback()
    if code is None:
        raise OAuthFail()

    user = User.query.filter_by(qiniu_id = info.get('uid')).first()
    if user is None:
        user = User(
                qiniu_id = info.get('uid'),
                name = info.get('full_name'),
                nickname = info.get('full_name'),
                gender = info.get('gender')
        )
        db.session.add(user)

    # update qiniu info
    user.qiniu_name = info.get('full_name')
    user.qiniu_email = info.get('email')

    # update oauth_code
    user.oauth_code = code
    db.session.commit()

    # 如果是admin来请求oauth
    if request.referrer == url_for('admin.admin_login', _external = True):
        if user.qiniu_email in current_app.config['TECHSHOW_ADMINs']:
            login_user(user)
            return redirect(url_for('admin.admin_index'))

    return render_template('oauth_pending.html', oauth_logo = '/static/images/qiniu_logo.png')
示例#15
0
 def test_expired_confirmation_token(self):
     u = User(password='******')
     db.session.add(u)
     db.session.commit()
     token = u.generate_confirmation_token(1)
     time.sleep(2)
     self.assertFalse(u.confirm(token))
 def test_get_all_users_returns_correct_number_of_users(self):
     users = User.get_users()
     self.assertEqual(1, len(users))
     # Create a user, try it again.
     create_user(self.name, self.email, self.user_id)
     users = User.get_users()
     self.assertEqual(2, len(users))
示例#17
0
 def test_valid_confirmation_token(self):
     u = User(password='******')
     db.session.add(u)
     db.session.commit()
     token = u.generate_confirmation_token()
     self.assertTrue(u.confirm(token))
     self.assertTrue(u.confirmed)
示例#18
0
def user(number):
    if request.method == 'GET':
        try:
            query = User.get(User.id == number)
            return query.to_hash()
        except:
            return {'error':'user does not exist'}, 404
    elif request.method == 'PUT':
        post_data = request.values
        try:
            query = User.get(User.id == number)
        except:
            return {'error':'user does not exist'}
        if 'first_name' in post_data:
            query.first_name = post_data['first_name']
        if 'last_name' in post_data:
            query.last_name = post_data['last_name']
        if 'is_admin' in post_data:
            if post_data['is_admin'].lower() == "true":
                query.is_admin = True
            elif post_data['is_admin'].lower() == "false":
                query.is_admin = False
        if 'password' in post_data:
            query.set_password(post_data['password'])
        query.save()
        return query.to_hash()
    else:
        query = User.select().where(User.id == number)
        if query.exists():
            query = query.get()
            out_json = query.to_hash()
            query.delete_instance()
            return out_json
        else:
            return {"code":404, "msg":"not found"}, 404
示例#19
0
 def do_add_user(self, params):
     
     # initialize the result, set the value to indicate an error
     result = { 'returnCode': -1 }
     
     # Get player data from self.request
     pName = params['PlayerName']
     dName = params['PersonaName']
                     
     # Create and save the persona so it has a key
     # should really check for an existing persona here first
     newUser = User( name = dName )
         
     try:
         # try blocks should be limited just to calls that may fail 
         newUser.put()
         
     except ValueError:
         logging.error( 'Attempt to save a Player/Driver failed' )
         self.send_json( result )    
         
         
     result['returnCode'] = 0
     result['playerName'] = pName
     result['driverName'] = dName
         
     self.send_json( result )
     return
示例#20
0
文件: user.py 项目: uzh/msregistry
def get_user():
    user = User()
    result = user.getByUniqueID(stack.top.uniqueID)
    if result is not None:
        return jsonify(result.serialize())
    
    raise UserNotFound(stack.top.uniqueID)
示例#21
0
 def get_superadmin_index_data(self):
     paid_survey_users, all_quiz_attempts, paid_quiz_attempts = yield (
         User.get_paid_survey_users().fetch_async(),
         QuizAttempt.get_all_attempts().fetch_async(),
         QuizAttempt.get_non_trial_attempts().fetch_async()
     )
     all_users = yield ndb.get_multi_async([User.build_key(attempt.user_id) for attempt in all_quiz_attempts])
     raise ndb.Return((paid_survey_users, all_quiz_attempts, all_users, paid_quiz_attempts))
示例#22
0
 def test_get_report_no_admin(self):
     user2 = User(name='user2', email='*****@*****.**')
     user2.password = hashlib.md5('1').hexdigest()
     db.session.add(user2)
     db.session.commit()
     token = self.login('user2', '1').json['token']
     res = self.client.get('api/tasks/1/comments', headers={'token': token})
     self.assert403(res)
示例#23
0
文件: user.py 项目: uzh/msregistry
def get_user_consent_info():
    user = User()
    result = user.getUserConsentByUniqueID(stack.top.uniqueID)
    
    if result is not None:
        return jsonify(accepted=bool(result))
    
    raise UserNotFound(stack.top.uniqueID)
示例#24
0
 def test_invalid_confirmation_token(self):
     u1 = User(password='******')
     u2 = User(password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     token = u1.generate_confirmation_token()
     self.assertFalse(u2.confirm(token))
示例#25
0
def verify_password(email_or_token, password):
    user = User.verify_auth_token(email_or_token)
    if not user:
        user = User.objects(email=email_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True
示例#26
0
 def test_user(self):
     try:
         User.authenticate()
         assert False
     except Unauthorized:
         assert True
         return
     assert False
示例#27
0
def del_user(id):
    id_check = User.select().where(User.id == id)
    if not id_check:
        return {'code': 404, 'msg': 'User not found'}, 404

    item = User.delete().where(User.id == id)
    item.execute()
    return {'code': 200, 'msg': 'Deleted successfully'}, 200
示例#28
0
 def setUp(self):
     db.create_all()
     user1 = User(name='user1', email='*****@*****.**', is_admin=True)
     user1.password = hashlib.md5('pass1').hexdigest()
     db.session.add(user1)
     db.session.commit()
     self.token = user1.generate_auth_token()
     self.client = current_app.test_client()
     self.auth_header = {'token': self.token}
示例#29
0
 def tearDown(self):
     """
     Remove place table from airbnb_test database upon completion of test
     case.
     """
     Place.drop_table()
     City.drop_table()
     State.drop_table()
     User.drop_table()
示例#30
0
    def test_inserting_duplicate_username(self):
        u = User(username = '******', password = "******", email =
                '*****@*****.**')
        User.save_to_db(u);
        u2 = User(username = '******', password = "******", email =
                '*****@*****.**')

        assert User.save_to_db(u2) == False
        assert len(User.all()) == 1
示例#31
0
文件: fake.py 项目: gpython/ginger
#encoding:utf-8

from app import create_app
from app.models.base import db
from app.models.user import User

app = create_app()

with app.app_context():
    with db.auto_commit():
        #离线脚本 创建超级管理员帐户
        user = User()
        user.nickname = 'super'
        user.password = '******'
        user.email = '*****@*****.**'
        user.auth = 2
        db.session.add(user)
示例#32
0
def accept_invite(token):
    invited_user = InvitedUser.from_token(token)

    if not current_user.is_anonymous and current_user.email_address.lower(
    ) != invited_user.email_address.lower():
        message = Markup("""
            You’re signed in as {}.
            This invite is for another email address.
            <a href={} class="govuk-link govuk-link--no-visited-state">Sign out</a>
            and click the link again to accept this invite.
            """.format(current_user.email_address,
                       url_for("main.sign_out", _external=True)))

        flash(message=message)

        abort(403)

    if invited_user.status == 'cancelled':
        service = Service.from_id(invited_user.service)
        return render_template('views/cancelled-invitation.html',
                               from_user=invited_user.from_user.name,
                               service_name=service.name)

    if invited_user.status == 'accepted':
        session.pop('invited_user_id', None)
        service = Service.from_id(invited_user.service)
        if service.has_permission('broadcast'):
            return redirect(
                url_for('main.broadcast_tour',
                        service_id=service.id,
                        step_index=1))
        return redirect(
            url_for('main.service_dashboard', service_id=invited_user.service))

    session['invited_user_id'] = invited_user.id

    existing_user = User.from_email_address_or_none(invited_user.email_address)

    if existing_user:
        invited_user.accept_invite()
        if existing_user in Users(invited_user.service):
            return redirect(
                url_for('main.service_dashboard',
                        service_id=invited_user.service))
        else:
            service = Service.from_id(invited_user.service)
            # if the service you're being added to can modify auth type, then check if this is relevant
            if service.has_permission('email_auth') and (
                    # they have a phone number, we want them to start using it. if they dont have a mobile we just
                    # ignore that option of the invite
                (existing_user.mobile_number
                 and invited_user.auth_type == 'sms_auth') or
                    # we want them to start sending emails. it's always valid, so lets always update
                    invited_user.auth_type == 'email_auth'):
                existing_user.update(auth_type=invited_user.auth_type)
            existing_user.add_to_service(
                service_id=invited_user.service,
                permissions=invited_user.permissions,
                folder_permissions=invited_user.folder_permissions,
                invited_by_id=invited_user.from_user.id,
            )
            if service.has_permission('broadcast'):
                return redirect(
                    url_for('main.broadcast_tour',
                            service_id=service.id,
                            step_index=1))
            return redirect(
                url_for('main.service_dashboard', service_id=service.id))
    else:
        return redirect(url_for('main.register_from_invite'))
示例#33
0
文件: user.py 项目: azulkipli/albasia
 def add_claims_to_access_token(identity):
     user = UserModel.getByUsername(identity)
     return {
         'username': identity,
         'uid': user.id
     }
示例#34
0
 def get_user(user_id):
     """ return a passed user using the user id passed """
     return User.get_user(user_id)
示例#35
0
文件: user.py 项目: ohahlev/flaskit
def create_user():

    form = FormCreateUser()
    
    roles = Role.query.all()
    user_role = next((x for x in roles if x.name == USER), None)

    if form.validate_on_submit():

        user = User(
            name=form.name.data.strip(),
            phone=form.phone.data.strip(),
            email=form.email.data.strip(),
            password=form.password.data.strip(),
            confirmed=True
        )

        # assign role as normal user
        
        role_ids = zip(request.form.getlist("roles"))
        found_user_role = False
        for role_id in role_ids:
            find_role = next((x for x in roles if x.id == int(role_id[0])), None)
            if find_role:
                user.roles.append(find_role)
            if find_role.id == user_role:
                found_user_role = True

        if found_user_role is False:
            user.roles.append(user_role)

        # validate photo upload extension
        file_name = None
        if form.photo.data:
            file_name = secure_filename(form.photo.data.filename)
        if file_name and not util.allowed_file(file_name, app.config["ALLOWED_EXTENSIONS"]):
            flash("photo upload allows only {}".format(",".join(app.config["ALLOWED_EXTENSIONS"])))
            return redirect(url_for("userbe.create_user"))
        
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as err:
            logger.exception(err)
            flash("can not create user at this moment", "negative")
            return redirect(url_for("userbe.create_user"))

        if file_name:
                
            # check if parent dir exist
            parent_dir = os.path.join("app", app.config["UPLOAD_FOLDER"], 
                    "users", "{}".format(user.id), "photo")
            if not os.path.exists(parent_dir):
                os.makedirs(parent_dir)

            # if file for new logo already exists
            new_logo = os.path.join(parent_dir, "{0}".format(file_name))
            if os.path.isfile(new_logo):
                os.remove(new_logo)

            # save new logo to file
            form.photo.data.save(new_logo)

            user.photo = file_name

            try:
                db.session.commit()
            except Exception as err:
                logger.exception(err)
                flash("can not create user at this moment", "negative")
                return redirect(url_for("userbe.create_user"))

        flash("user = {0} is created".format(user.name), "positive")

        return redirect(url_for("userbe.search_users_results", is_advanced=0, keyword=util.EMPTY,
                                sorted_by=util.DEFAULT_SORT, sorted_as="desc", per_page=10, page=1,
                                id_to_filter=util.EMPTY, name_to_filter=util.EMPTY, email_to_filter=util.EMPTY,
                                phone_to_filter=util.EMPTY, confirmed_to_filter=util.EMPTY,
                                deleted_to_filter=util.EMPTY, role_to_filter=util.EMPTY))

    return render_template("backend/user/create.html", title="Create User", form=form, roles=roles, user_role=user_role)
示例#36
0
def login_user(provider):
    if provider == 'facebook':
        provider_class = FbOAuth()
        payload = {
            'client_id': provider_class.get_client_id(),
            'redirect_uri': provider_class.get_redirect_uri(),
            'client_secret': provider_class.get_client_secret(),
            'code': request.args.get('code')
        }
        if not payload['client_id'] or not payload['client_secret']:
            raise NotImplementedError({'source': ''}, 'Facebook Login Not Configured')
        access_token = requests.get('https://graph.facebook.com/v3.0/oauth/access_token', params=payload).json()
        payload_details = {
            'input_token': access_token['access_token'],
            'access_token': provider_class.get_client_id() + '|' + provider_class.get_client_secret()
        }
        details = requests.get('https://graph.facebook.com/debug_token', params=payload_details).json()
        user_details = requests.get('https://graph.facebook.com/v3.0/' + details['data']['user_id'],
                                    params={'access_token': access_token['access_token'],
                                            'fields': 'first_name, last_name, email'}).json()

        if get_count(db.session.query(User).filter_by(email=user_details['email'])) > 0:
            user = db.session.query(User).filter_by(email=user_details['email']).one()
            if not user.facebook_id:
                user.facebook_id = user_details['id']
                user.facebook_login_hash = random.getrandbits(128)
                save_to_db(user)
            return make_response(
                jsonify(user_id=user.id, email=user.email, oauth_hash=user.facebook_login_hash), 200)

        user = User()
        user.first_name = user_details['first_name']
        user.last_name = user_details['last_name']
        user.facebook_id = user_details['id']
        user.facebook_login_hash = random.getrandbits(128)
        user.password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))
        if user_details['email']:
            user.email = user_details['email']

        save_to_db(user)
        return make_response(jsonify(user_id=user.id, email=user.email, oauth_hash=user.facebook_login_hash),
                             200)

    elif provider == 'google':
        provider_class = GoogleOAuth()
        payload = {
            'client_id': provider_class.get_client_id(),
            'client_secret': provider_class.get_client_secret()
        }
    elif provider == 'twitter':
        provider_class = TwitterOAuth()
        payload = {
            'client_id': provider_class.get_client_id(),
            'client_secret': provider_class.get_client_secret()
        }
    elif provider == 'instagram':
        provider_class = InstagramOAuth()
        payload = {
            'client_id': provider_class.get_client_id(),
            'client_secret': provider_class.get_client_secret()
        }
    else:
        return make_response(jsonify(
            message="No support for {}".format(provider)), 200)
    response = requests.post(provider_class.get_token_uri(), params=payload)
    return make_response(jsonify(token=response.json()), 200)
示例#37
0
文件: fake.py 项目: wswjuea/ginger
"""
 Created by 七月 on 2018/5/1.
"""
__author__ = '七月'

from app import create_app
from app.models.base import db
from app.models.user import User

app = create_app()
with app.app_context():
    with db.auto_commit():
        # 创建一个超级管理员
        user = User()
        user.nickname = 'Super'
        user.password = '******'
        user.email = '*****@*****.**'
        user.auth = 2
        db.session.add(user)
示例#38
0
def __register_user_by_email():
    form = UserEmailForm(data=request.json)
    if form.validate():
        User.register_by_email(form.nickname.data, form.account.data,
                               form.secret.data)
    pass
示例#39
0
def __register_by_email():
    form = UserEmailForm().validate_for_api()
    User.register_by_email(form.nickname.data, form.account.data,
                           form.secret.data)
示例#40
0
 def update_password(self, user_id, password):
     data = {"_password": password}
     url = "/user/{}/update-password".format(user_id)
     user_data = self.post(url, data=data)
     return User(user_data['data'], max_failed_login_count=self.max_failed_login_count)
示例#41
0
 def reset_failed_login_count(self, user_id):
     url = "/user/{}/reset-failed-login-count".format(user_id)
     user_data = self.post(url, data={})
     return User(user_data['data'], max_failed_login_count=self.max_failed_login_count)
示例#42
0
 def get_users(self):
     users_data = self.get("/user")['data']
     users = []
     for user in users_data:
         users.append(User(user, max_failed_login_count=self.max_failed_login_count))
     return users
示例#43
0
 def get_user(self, user_id):
     return User(self._get_user(user_id)['data'], max_failed_login_count=self.max_failed_login_count)
示例#44
0
 def add_user_to_organisation(self, org_id, user_id):
     resp = self.post('/organisations/{}/users/{}'.format(org_id, user_id), data={})
     return User(resp['data'], max_failed_login_count=self.max_failed_login_count)
示例#45
0
def user_information(user_id):
    return render_template(
        'views/find-users/user-information.html',
        user=User.from_id(user_id),
    )
示例#46
0
 def get_users_for_organisation(self, org_id):
     endpoint = '/organisations/{}/users'.format(org_id)
     resp = self.get(endpoint)
     return [User(data) for data in resp['data']]
示例#47
0
def confirm(token):
    if User.confirm_token(token):
        flash('activate success, please login in !')
    else:
        flash('activate fail, token may has been expired !')
    return redirect(url_for('web.auth:login'))
示例#48
0
 def get_users_for_service(self, service_id):
     endpoint = '/service/{}/users'.format(service_id)
     resp = self.get(endpoint)
     return [User(data) for data in resp['data']]
示例#49
0
def ComputeEligibleCompetitors(championship, competition, results):
    if championship.national_championship:
        # We don't save this in the datastore because it's easy enough to compute.
        return set([
            r.person.id() for r in results
            if r.person_country == ndb.Key(Country, 'USA')
        ])
    competitors = set([r.person for r in results])
    users = User.query(User.wca_person.IN(competitors)).fetch()
    user_keys = [user.key for user in users]

    # Load the saved eligibilities, so that one person can't be eligible for two
    # championships of the same type.
    if championship.region:
        eligibility_class = RegionalChampionshipEligibility

        def eligibility_field(user):
            if not user.regional_eligibilities:
                user.regional_eligibilities = []
            return user.regional_eligibilities
    else:
        eligibility_class = StateChampionshipEligibility

        def eligibility_field(user):
            if not user.state_eligibilities:
                user.state_eligibilities = []
            return user.state_eligibilities

    valid_state_keys = championship.GetEligibleStateKeys()
    residency_deadline = (championship.residency_deadline
                          or datetime.datetime.combine(competition.start_date,
                                                       datetime.time(0, 0, 0)))

    eligible_competitors = set()
    competitors_to_put = []

    class Resolution:
        ELIGIBLE = 0
        INELIGIBLE = 1
        UNRESOLVED = 2

    for user in users:
        resolution = Resolution.UNRESOLVED
        for eligibility in eligibility_field(user):
            if eligibility.year != championship.year:
                continue
            if eligibility.championship == championship.key:
                resolution = Resolution.ELIGIBLE
            else:
                resolution = Resolution.INELIGIBLE
        # If the competitor hasn't already used their eligibility, check their state.
        if resolution == Resolution.UNRESOLVED:
            state = None
            for update in user.updates or []:
                if update.update_time < residency_deadline:
                    state = update.state
            if state and state in valid_state_keys:
                # This competitor is eligible, so save this on their User.
                resolution = Resolution.ELIGIBLE
                eligibility = eligibility_class()
                eligibility.championship = championship.key
                eligibility_field(user).append(eligibility)
                competitors_to_put.append(user)
            else:
                resolution = Resolution.INELIGIBLE
        if resolution == Resolution.ELIGIBLE:
            eligible_competitors.add(user.wca_person.id())
    ndb.put_multi(competitors_to_put)
    return eligible_competitors
示例#50
0
def index():
    users = User.select()
    return users
示例#51
0
def save_user(name, password):
    """添加用户"""
    user = User(name=name, password=password)
    db.session.add(user)
    db.session.commit()
示例#52
0
def load_user(user_id):
    return User.from_id(user_id)
示例#53
0
文件: user.py 项目: azulkipli/albasia
    def post(self):
        args = request.get_json()
        validator = MyValidator()
        dovalidate = validator.wrp_validate(args, {
            'username': {'type': 'string', 'required': True, 'empty': False},
            'password': {'type': 'string', 'required': True, 'empty': False}
            })
        if(dovalidate['status'] is False):
            return self.response({
            	'title':'Error',
            	'body':dovalidate['messages'],
            	'status_code':422
            })

        user = UserModel.getByUsername(args['username']).serialize()
        print(user)
        
        # Check Max Login Attempt Mode
        max_login_attempt = int(app.config['MAX_LOGIN_ATTEMPT'])
        if user is not None:

            if user['login_attempt'] >= max_login_attempt or user['status'] == VariableConstant.USER_STATUS_BLOCKED:
                return self.response(VariableConstant.USER_BLOCKED_RESPONSE)

            password = util.generate_password(args['username'],args['password'],user['password_salt'])
            if password != user['password']:
                app.logger.error('ERROR LOGIN : '******'msg': 'Wrong Username or Password'})

                # Auto Increment Login Attempt
                la = UserModel.incrementLoginAttempt(user['id'])
                if (user['login_attempt'] + 1) >= max_login_attempt:
                    # Block user
                    UserModel.doUpdate(
                        user['id'],
                        {
                            'status': VariableConstant.USER_STATUS_BLOCKED,
                            'isloggedin': 0,
                            'login_attempt': 0
                        })
                    return self.response(VariableConstant.USER_BLOCKED_RESPONSE)
                    
                return self.response(VariableConstant.USER_LOGIN_FAILED_RESPONSE)
        else:
            app.logger.error('ERROR LOGIN : '******'msg': 'User Not Found '})
            return self.response(VariableConstant.USER_LOGIN_FAILED_RESPONSE)

        user['access_token'] = create_access_token(identity=args['username'])
        user['refresh_token'] = create_refresh_token(identity=args['username'])

        access_jti = get_jti(encoded_token=user['access_token'])
        refresh_jti = get_jti(encoded_token=user['refresh_token'])
        revoked_store.set(access_jti, 'false', app.config['JWT_ACCESS_TOKEN_EXPIRES'] * 1.2)
        revoked_store.set(refresh_jti, 'false', app.config['JWT_REFRESH_TOKEN_EXPIRES'] * 1.2)

        #update last logged in
        UserModel.doUpdate(user['id'],{
        	'last_loggedin_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 
        	'is_loggedin': 1
        })

        del user['password']
        del user['password_salt']

        return self.response({'data':json.dumps(user)})
示例#54
0
def verify_refresh_token(token):
    user = User.verify_refresh_token(token)
    if not user:
        return False
    g.user = user
    return True
示例#55
0
"""
  Created by Kenneth Luff
  Email: [email protected]
"""
from app import create_app
from app.models.base import db
from app.models.user import User

app = create_app()
with app.app_context():
    with db.auto_commit():
        user = User()
        user.nickname = 'Super'
        user.password = '******'
        user.email = '*****@*****.**'
        user.auth = 2
        db.session.add(user)
示例#56
0
 def is_email_available(email):
     current_user = User.find_by_email(email)
     if not current_user:
         return True
     return False
 def cancelled_by(self):
     return User.from_id(self.cancelled_by_id)
示例#58
0
def execute_before_any_test():
    IngredientsReceipts.truncate()
    UsersReceipts.truncate()
    Receipt.truncate()
    Ingredient.truncate()
    User.truncate()
示例#59
0
 def get_user_by_email(self, email_address):
     user_data = self.get('/user/email', params={'email': email_address})
     return User(user_data['data'], max_failed_login_count=self.max_failed_login_count)
示例#60
0
 def activate_user(self, user):
     if user.state == 'pending':
         user_data = self._activate_user(user.id)
         return User(user_data['data'], max_failed_login_count=self.max_failed_login_count)
     else:
         return user