Exemplo n.º 1
0
def create_user():
    """
    data:
        username (string): Unique identifier for new user

    Returns:
        A serialized version of the user or an error message.
    """

    username = request.json["username"]

    existing_user = User.query.filter_by(username=username).first()
    if existing_user:
        return jsonify(error="User already exists. Failed to create account.")

    user = User(username=username)
    user.save()
    county = County(
        kingdom_id=1,
        name=f"County-{user.id}",
        leader=f"Leader-{user.id}",
        user_id=user.id,
        race="Human",
        title="Lady",
        background="Warlord",
    )
    county.save()
    return jsonify(user=UserSerializer.call(user))
Exemplo n.º 2
0
    def post(self):
        args = self.parser.parse_args()
        print(args)
        email = args.get('email')
        username = args.get('username')
        password = str(args.get('password'))
        users = User.query.filter_by(username=username)

        if User.query.filter_by(
                username=username).first() or User.query.filter_by(
                    email=email).first():
            data = {
                'msg': '用户名已存在',
                'status': 400,
                # 'data': {},
            }
            return data
        user = User(email=email,
                    username=username,
                    password=User().set_password(password))
        db.session.add(user)
        db.session.commit()
        data = {
            'msg': 'ok',
            'status': 201,
            'data': user,
        }
        return data
Exemplo n.º 3
0
def dummy():
    # Create a user if they do not exist.
    user = User.query.filter_by(email="*****@*****.**").first()
    if not user:
        user = User("*****@*****.**", "123456")
        user.save()

    for i in range(100):
        # Add events to the database
        event = Event(faker.lorem_ipsum.title(words_quantity=10), faker.name.location(), faker.date.date(), user.id)
        event.save()

    for j in range(500):
        # Add guests to the database
        guest = Guest(faker.name.first_name(), faker.name.last_name(), faker.name.company_name(), faker.email.address(user=None), user.id)
        guest.save()

    for ev in range(1000):
        # Add tickets to the event
        event = Event.query.filter_by(event_id=randint(1, Event.query.count() - 1)).first()
        guest = Guest.query.filter_by(guest_id=randint(1, Guest.query.count() - 1)).first()
        ticket = Ticket(event.event_id, guest.guest_id, faker.lorem_ipsum.words(quantity=15, as_list=False), faker.basic.number(at_least=0, at_most=1), faker.basic.number(at_least=0, at_most=1), faker.basic.number(at_least=0, at_most=1000))
        db.session.add(ticket)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
Exemplo n.º 4
0
 def register_new_user():
     name = request.get_json()['name']
     country = request.get_json()['country']
     phone = request.get_json()['phone']
     password = request.get_json()['password']
     email = request.get_json()['email']
     role = request.get_json()['role']
     thumbnail = request.get_json()['thumbnail']
     if not thumbnail:
         thumbnail = 'https://img.favpng.com/20/11/12/computer-icons-user-profile-png-favpng-0UAKKCpRRsMj5NaiELzw1pV7L.jpg'
     verify_data = Register_Validation({
         "name": name,
         "country": country,
         "password": password,
         "email": email,
         "thumbnail": thumbnail,
         "role": role
     })
     is_verified = verify_data.check_input()
     if is_verified[0] == 200:
         if not User.query.filter_by(email=email).first():
             new_user = User(name, country, password, phone, email,
                             thumbnail, role)
             new_user.save()
             return make_response(
                 jsonify({"message": "User successfully created!"})), 201
         else:
             return make_response(
                 jsonify({"message": "Email already being used here."}))
     else:
         return make_response(jsonify({"message":
                                       is_verified[1]})), is_verified[0]
Exemplo n.º 5
0
def sign_up():
    data = request.json

    # function to check sign-up and handle errors
    errors = validate_sign_up(data)
    if (len(errors) > 0):
        return jsonify({'validated': False, 'errors': errors})

    # Create a hashed password
    password = data['password'].encode()
    hashed_password = bcrypt.hashpw(
        password, bcrypt.gensalt(14)).decode('utf-8')

    # Generate and add new user to db
    new_user = User(name=data['name'],
                    email=data['email'],
                    hashed_password=hashed_password)
    db.session()
    db.session.add(new_user)
    db.session.commit()

    # create jwt to return
    jwt = create_jwt(new_user.to_dict())

    return jsonify({'validated': True, "user": new_user.to_dict(), "token": str(jwt)})
Exemplo n.º 6
0
def create_user(
    user_to_create: schemas.UserIn, 
    user: schemas.UserOut = Depends(get_logged_user),
    db: Session = Depends(get_db)
):
    # Only a admin user can create other users
    admin_user = db.query(User).get(user.username)
    if not admin_user.admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only admin users can create users"
        )
    
    # Username must be unique
    if db.query(User).get(user_to_create.username):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Username already exists"
        )

    new_user = User(**user_to_create.dict())
    new_user.hashed_password = hash_password(user_to_create.password)
    db.add(new_user)
    db.flush()
    db.commit()
    return schemas.UserOut(**new_user.dict())
Exemplo n.º 7
0
def test_auth_token(login_admin):
    user = User.objects(email='*****@*****.**').first()
    assert str(user) == '[email protected]'
    assert repr(user) == "<User '*****@*****.**'>"
    token = user.generate_auth_token()
    assert User.verify_auth_token(token).id == user.id
    assert not User.verify_auth_token('wrong token')
Exemplo n.º 8
0
def inviteAdmin(zemail, zaccountType = None, zpassword = None):
    import app.models.users, app.models.invitations
    
    if zaccountType == None:
        zaccountType = User.accountTypes.student
    
    try:
        zaccountType = toAccountNum(zaccountType)
    except ValueError:
        return False
        
    if zpassword:
        hash = User.createHash(zpassword)
        
        newUser = User(email = zemail,
                       hash = hash,
                       accountType = zaccountType)
        newUser.save()
        
        print "inviteAdmin: Created user {email: %s, hash: %s, accountType: %s}" % \
                  (zemail, hash, User.accountTypes.getName(zaccountType))
    else:
        raise NotImplementedError
        
    return True
Exemplo n.º 9
0
def update_email():
    if request.method == "GET":
        user = User.query.filter_by(email=current_user.email).first()
        return render_template("pages/account.html",
                               form=UpdateEmailForm(),
                               user=user)

    # If user is admin
    if request.method == "POST":
        form = UpdateEmailForm(request.form)
        if form.validate_on_submit():
            verified = User.verify_user(current_user.email,
                                        form.data.get("password"))
            if verified:
                # TODO: Handle condition for uniqueness
                try:
                    updated = User.update_email(old_email=current_user.email,
                                                email=form.data.get("email"))
                    if updated:
                        Notifications.info_account_updated(**form.data)
                        login_user(current_user)
                        return redirect(url_for("account"))
                except EmailExistsError:
                    Notifications.email_exists(form.data.get("email"))
                    return redirect(url_for("update_email"))

        Notifications.info_try_again()
        return redirect(url_for("update_email"))
Exemplo n.º 10
0
 def test_valid_reset_token(self):
     u = User(password='******')
     db.session.add(u)
     db.session.commit()
     token = u.generate_reset_token()
     self.assertTrue(u.reset_password(token, 'dog'))
     self.assertTrue(u.verify_password('dog'))
Exemplo n.º 11
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))
Exemplo n.º 12
0
 def test_expired_confirmation_token(self):
     u = User(email=u"*****@*****.**", username=u"u", password=u"cat")
     db.session.add(u)
     db.session.commit()
     token = u.generate_confirmation_token(1)
     time.sleep(2)
     self.assertFalse(u.confirm(token))
Exemplo n.º 13
0
def update_password():
    if request.method == "GET":
        user = User.query.filter_by(email=current_user.email).first()
        return render_template(
            "pages/account.html", form=UpdatePasswordForm(), user=user
        )

    # If user is admin
    elif request.method == "POST":
        form = UpdatePasswordForm(request.form)
        if form.validate_on_submit():
            verified = User.verify_user(
                current_user.email, form.data.get("old_password")
            )
            if verified or current_user:
                updated = User.update_password(
                    email=current_user.email, password=form.data.get("new_password")
                )
                if updated:
                    Notifications.info_account_updated(**form.data)
                    login_user(current_user)
                    return redirect(url_for("account"))

        Notifications.info_try_again()
        return redirect(url_for("update_password"))
Exemplo n.º 14
0
def authenticate_dev_user():
    try:
        data = request.get_json()
        current_user = {}
        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['is_verified']:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data['password'], current_user['password']):
            # JWT_ACCESS_TOKEN_EXPIRES en desarrollo el token no expira.
            access_token = create_access_token(
                identity=current_user['username'], expires_delta=False)
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message': 'Logged in as admin',
                                     "access_token": access_token
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Exemplo n.º 15
0
def authenticate_user():
    try:
        data = request.get_json()
        current_user = {}
        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['is_verified']:
            return response_with(resp.BAD_REQUEST_400)
        if User.verify_hash(data['password'], current_user['password']):
            # JWT_ACCESS_TOKEN_EXPIRES = 15 minutos por defecto
            expires = datetime.timedelta(minutes=int(
                os.environ.get('JWT_ACCESS_TOKEN_EXPIRES',
                               DevelopmentConfig.JWT_ACCESS_TOKEN_EXPIRES)))
            access_token = create_access_token(
                identity=current_user['username'], expires_delta=expires)
            return response_with(resp.SUCCESS_200,
                                 value={
                                     'message': 'Logged in as admin',
                                     "access_token": access_token
                                 })
        else:
            return response_with(resp.UNAUTHORIZED_401)
    except Exception as e:
        print(e)
        return response_with(resp.INVALID_INPUT_422)
Exemplo n.º 16
0
 def test_valid_email_change(self):
     u = User(email=u"*****@*****.**", username=u"u", password=u"cat")
     db.session.add(u)
     db.session.commit()
     token = u.generate_email_change_token(u"*****@*****.**")
     self.assertTrue(u.change_email(token))
     self.assertTrue(u.email == u"*****@*****.**")
Exemplo n.º 17
0
 def post(self, args, user_id):
     contacts = []
     for contact in args['connections']:
         if Util.is_valid_contact_number(contact):
             contacts.append(Util.clean_contact_number(contact))
     User.set_user_connections(user_id, contacts)
     return None, 202
Exemplo n.º 18
0
def signup():
    name = request.form.get("name")
    email = request.form.get("email")
    password = request.form.get("password")
    is_admin = request.form.get("is_admin", False)

    # register user to db
    try:
        new_user = User.register(name, email, is_admin, password)
        if new_user is None:
            Notifications.info_try_again()

        if not current_user.is_anonymous:
            if current_user.is_admin:
                Notifications.info_account_created(name, password, email)
                return redirect(url_for("admin"))
        else:
            # Login the user
            u = User.verify_user(email, password)
            login_user(u)
            Notifications.info_account_created(name, password, email)
            return redirect(url_for("home"))
    except EmailExistsError:
        Notifications.email_exists(email)
    except PasswordTooShortError:
        Notifications.password_too_short()
    return redirect(url_for("home"))
Exemplo n.º 19
0
 def test_valid_email_change_token(self):
     u = User(email='*****@*****.**', password='******')
     db.session.add(u)
     db.session.commit()
     token = u.generate_email_change_token('*****@*****.**')
     self.assertTrue(u.change_email(token))
     self.assertTrue(u.email == '*****@*****.**')
Exemplo n.º 20
0
 def test_username_unique(self):
     u1 = User(email=u"*****@*****.**", username=u"u1", password=u"cat")
     db.session.add(u1)
     db.session.commit()
     with self.assertRaises(IntegrityError):
         u2 = User(email=u"*****@*****.**", username=u"u1", password=u"cat")
         db.session.add(u2)
         db.session.commit()
def update_user(db: Session, user: UserBase, db_user: User):
    if user.name.strip():
        db_user.name = user.name
    if user.email.strip():
        db_user.email = user.email
    db.flush()
    db.commit()
    return db_user
Exemplo n.º 22
0
 def test_expired_email_change(self):
     u = User(email=u"*****@*****.**", username=u"u", password=u"cat")
     db.session.add(u)
     db.session.commit()
     token = u.generate_email_change_token(u"*****@*****.**", 1)
     time.sleep(2)
     self.assertFalse(u.change_email(token))
     self.assertFalse(u.email == u"*****@*****.**")
Exemplo n.º 23
0
 def test_invalid_confirmation_token(self):
     u1 = User(email=u"*****@*****.**", username=u"u1", password=u"cat")
     u2 = User(email=u"*****@*****.**", username=u"u2", password=u"cat")
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     token = u1.generate_confirmation_token()
     self.assertFalse(u2.confirm(token))
Exemplo n.º 24
0
    def _create_admin_user(self, email, password, active):
        user = User(email=email, password=password, active=active)
        user.roles = [self.admin_role]

        with app.app_context():
            db.session.add(user)
            db.session.commit()

            return User.query.filter_by(email=user.email).first()
Exemplo n.º 25
0
def update_favourites():

    # form value will be a boolean indicating a liked or disliked recipe
    if request.form['value'] == 'true':
        User.add_liked_disliked(request.form['_id'], request.form['opinion'])
    else: 
        User.remove_liked_disliked(request.form['_id'], request.form['opinion'])

    return 'Favourites Updated'
Exemplo n.º 26
0
 def test_duplicate_email_change_token(self):
     u1 = User(email='*****@*****.**', password='******')
     u2 = User(email='*****@*****.**', password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     token = u2.generate_email_change_token('*****@*****.**')
     self.assertFalse(u2.change_email(token))
     self.assertTrue(u2.email == '*****@*****.**')
Exemplo n.º 27
0
    def post(self):
        data = request.get_json()
        if 'roles' in data:
            del data['roles']
        if data is None or len(data) == 0:
            return {"message": "Request params required"}, 400
        create_user_schema = CreateUserSchema()
        errors = create_user_schema.validate(data)
        if len(errors) == 0:
            data = create_user_schema.load(data)

            # check username
            user = User.query.filter_by(username=data['username']).first()
            if user is not None:
                return {'message': 'Username exists!'}, 400

            # check email
            user = User.query.filter_by(email=data['email']).first()
            if user is not None:
                return {'message': 'Email exists!'}, 400

            # create user
            u = User(username=data['username'],
                     email=data['email'],
                     first_name=data['first_name'],
                     last_name=data['last_name'])
            u.set_password(data['password'])
            roles = Role.query.filter(Role.name.in_(data['roles'])).all()
            for r in roles:
                u.roles.append(r)
            try:
                db.session.add(u)
                db.session.commit()

            except SQLAlchemyError as e:
                db.session.rollback()
                if type(e).__name__ == 'IntegrityError':
                    response = {
                        'message':
                        'Error inserting new user: '******'message': 'DB error: ' + e.orig.args[0]}
                return response, 500

            user_schema = UserSchema()
            result = user_schema.dumps(u)
            response = {'data': result}
            sendWelcomeEmail(u)
            return "", 201
        else:
            response = {
                'message': 'there were errors with the user submission',
                'errors': errors
            }
            return response, 400
Exemplo n.º 28
0
 def test_invalid_email_change(self):
     u1 = User(email=u"*****@*****.**", username=u"u1", password=u"cat")
     u2 = User(email=u"*****@*****.**", username=u"u2", password=u"cat")
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     token = u1.generate_email_change_token(u"*****@*****.**")
     self.assertFalse(u2.change_email(token))
     self.assertFalse(u1.email == u"*****@*****.**")
     self.assertFalse(u2.email == u"*****@*****.**")
Exemplo n.º 29
0
def deploy():
    from flask_migrate import upgrade
    from app.models.users import Role, User

    upgrade()

    # 创建表
    Role.insert_roles()
    # 建立自连接
    User.add_self_follows()
Exemplo n.º 30
0
def init():
    u = User.query.all()
    if not u:
        admin_user = User(username=app.config['APP_DEFAULT_USERNAME'], )
        admin_user.set_password(app.config['APP_DEFAULT_PASSWORD'])
        admin_group = Group(name=app.config['APP_DEFAULT_ADMIN_GROUP'])
        admin_user.in_groups.append(admin_group)
        db.session.add(admin_user)
        db.session.add(admin_group)
        db.session.commit()
Exemplo n.º 31
0
def test_waitlist(self):

    if self.get_argument('date'):
        date = datetime.strptime(self.get_argument('date'), '%Y-%m-%d')
        sched = yield InstructorSchedule.objects.get(date=date)
        if not sched:
            sched_id = ObjectId(self.get_argument('sched_id'))
            if sched_id:
                ins = yield Instructor.objects.limit(1).find_all()
                if ins:
                    sched = InstructorSchedule(
                        instructor=ins[0],
                        type='regular',
                        day='mon',
                        start=datetime.strptime('7:00 AM', '%I:%M %p'),
                        end=datetime.strptime('9:30 AM', '%I:%M %p'))
                    sched = yield sched.save()
            else:
                self.write('Please provide a date')
                self.finish()
                return

        user = yield User.objects.get(email='*****@*****.**')
        if not user:
            user = User(first_name='user',
                        last_name='user',
                        password='******',
                        email='*****@*****.**',
                        credits=3)
            user = yield user.save()

        yield BookedSchedule.objects.filter(user_id=user._id).delete()
        currentBooks = yield BookedSchedule.objects.filter(
            schedule=sched._id).find_all()

        for x in range(0, sched.seats):
            isReserved = False
            for i, book in enumerate(currentBooks):
                if (x + 1) == book.seat_number:
                    isReserved = True
                    break

            if isReserved:
                continue

            if user:
                book = BookedSchedule(user_id=user._id,
                                      date=date,
                                      schedule=sched._id,
                                      seat_number=x + 1,
                                      status='booked')
                book = yield book.save()
    else:
        self.write('Please provide a date')
    self.finish()
Exemplo n.º 32
0
def google_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in.", category="error")
        return False

    response = blueprint.session.get("/oauth2/v1/userinfo")
    if not response.ok:
        msg = "Failed to fetch user info."
        flash(msg, category="error")
        return False

    info = response.json()
    user_id = info["id"]
    first_name = info.get("given_name", None)
    last_name = info.get("family_name", None)
    if first_name and last_name:
        full_name = f"{first_name} {last_name}"
    else:
        full_name = None

    # Find this OAuth token in the database, or create it
    try:
        oauth = OAuth.query.filter_by(provider=blueprint.name,
                                      provider_user_id=user_id).one()
    except NoResultFound:
        oauth = OAuth(provider=blueprint.name,
                      provider_user_id=user_id,
                      token=token)

    if oauth.user:
        login_user(oauth.user)
    else:
        # Try finding user with given e-mail in database
        user = User.load_by_attribute("email", info["email"])
        if not user:
            # Create a new local user account for this user
            user = User.create(
                email=info["email"],
                password="******",
                full_name=full_name,
                active=True,
                do_hash=False,
            )
        # user.save()
        # Associate the new local user account with the OAuth token
        oauth.user = user
        # oauth.save()
        # Save and commit our database models
        db.session.add_all([user, oauth])
        db.session.commit()
        # Log in the new local user account
        login_user(user)

    # Disable Flask-Dance's default behavior for saving the OAuth token
    return False
Exemplo n.º 33
0
def setup():
    role = Role.first(name='user') #Get the 'user' role or create it
    if not role:
       role = Role.create(name='user', description='provides basic system access', bitmask=2)

    if not User.first(email="*****@*****.**"):
        mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('hello'),
                confirmed_at=datetime.now(), roles=[role])

    if not User.first(email="*****@*****.**"):
        mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('world'),
                roles=[role])
Exemplo n.º 34
0
def create_users():
    admin_user = User.from_args('*****@*****.**', 'testtest', '1', 'PayPay',
                                'Admin', datetime.utcnow(), datetime.utcnow())

    db.session.add(admin_user)
    db.session.commit()

    employee_user = User.from_args('*****@*****.**', 'testtest', '2',
                                   'Employee', '1', datetime.utcnow(),
                                   datetime.utcnow())

    db.session.add(employee_user)
    db.session.commit()
Exemplo n.º 35
0
 def post(self, args):
     activity_pref = args.pop('activity_preferences')
     user_details = args
     user_id = User.insert_user(user_details)
     if user_id is -1:
         abort(http_status_code=400, error_code=error_enum.user_id_duplicate)
     User.insert_user_activity_pref(user_id, activity_pref)
     BlockSessionModel.create_block_session(args['user_id'], {
         'day_of_week': 'All',
         'start_time': "00:00:00",
         'end_time': "05:59:59"
     })
     return {'user_id': user_id}
Exemplo n.º 36
0
    def setUp(self):
        """
        Sets up tests User object : 
            User(username, email, bio, password)

        The constructor of the Category class is; 
            self.username = username
            self.email = email
            self.bio = bio
            self.password = password
        """
        self.new_user = User('sylvance', 'sylvance@mail', 'I am good',
                             'Scifi4u*@')
Exemplo n.º 37
0
 def put(self):
     """
     Creates a new user
     """
     u = User.query.filter_by(username=request.json['username']).first()
     if u:
         return {'msg': 'User already exists'}, 400
     u = User(username=request.json['username'])
     if 'password' in request.json.keys():
         u.set_password(request.json['password'])
     db.session.add(u)
     db.session.commit()
     return {"id": u.id, "username": u.username}, 200
Exemplo n.º 38
0
    def test_register_user_assigns_user_role(self, apidb, testapi, role, invite):
        resp = self.test_register_user(apidb, testapi, role, invite=invite)
        resp.json['user']['roles'].should.have.length_of(1)

        u = User.first(email='*****@*****.**')
        u.roles.should.have.length_of(1)
        u.roles.should.contain(role)
Exemplo n.º 39
0
 def get(self, user_id):
     if not user_id:
         abort(http_status_code=404, error_code=error_enum.user_id_missing)
     result = User.get_user_activity_pref(user_id)
     if not result:
         abort(http_status_code=400, error_code=error_enum.user_id_not_found)
     return result
Exemplo n.º 40
0
    def reset_request(self):
        """Sends a reset password email"""

        schema = RELS['v1.AuthView:reset'][request.method]
        args = request_reset_password_options.parse_args()
        email = args.get('email')

        user = User.find(email=email).first()

        if not user:
            return dict(status=409, message="Invalid email address"), 409

        token = generate_reset_password_token(user)

        reset_link = urljoin(current_app.config['CLIENT_DOMAIN'], '/#/reset/'+token)

        #TODO this mail send should be performed asynchronously using celery, see issue #88850472
        send_message(
            subject='FogMine Reset Request',
            sender="*****@*****.**",
            recipients = [user.email],
            html_body=render_template('email/reset.html', user=user, reset_link=reset_link),
            text_body=render_template('email/reset.txt', user=user, reset_link=reset_link)
        )

        return dict(status=200, message="Reset instructions sent")
Exemplo n.º 41
0
 def get(self, user_id=None):
     if not user_id:
         abort(http_status_code=404, error_code=error_enum.user_id_missing)
     result = User.get_user(user_id)
     if result:
         for record in result:
             record['dob'] = str(record['dob'])
     else:
         abort(http_status_code=400, error_code=error_enum.user_id_not_found)
     return result
Exemplo n.º 42
0
def setup():
    userRole = Role.first(name='user') #Get the 'user' role or create it
    if not userRole:
       userRole = Role.create(name='user', description='provides basic system access', bitmask=2)

    adminRole = Role.first(name='admin') #Get the 'admin' role or create it
    if not adminRole:
       adminRole = Role.create(name='admin', description='provides admin level system access', bitmask=4)


    if not User.first(email="*****@*****.**"):
        mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('hello'),
                confirmed_at=datetime.now(), roles=[userRole])

    if not User.first(email="*****@*****.**"):
        mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('world'),
                roles=[userRole])

    if not User.first(email="*****@*****.**"):
        mixer.blend('app.models.users.User', email="*****@*****.**", password=encrypt_password('supersecret'),
                roles=[adminRole])
Exemplo n.º 43
0
def get_user(session):
    """
    Given a session (dict-like object), returns a user object, or None if
    not logged in
    """

    # check if we already have a user id in the session, if so attempt to pull
    # the user data from mongo
    user_id = session.get("user_id")
    try:
        user = User.objects.get(pk=user_id)
    except db.DoesNotExist:
        pass
    else:
        return user

    # if we don't already have user details stored then check if we have an
    # access token retrieved via the oauth process
    access_token = session.get("access_token")
    if access_token is None:
        return None

    # build the request object
    headers = {"Authorization": "OAuth " + access_token[0]}
    req = urllib2.Request("https://www.googleapis.com/oauth2/v1/userinfo", None, headers)

    # make the request, catching any http errors
    try:
        res = urllib2.urlopen(req)
    except urllib2.URLError:
        return None
    else:
        user_data = json.loads(res.read())
        user = User(user_id=user_data["id"], email=user_data["email"], name=user_data["name"])
        if "picture" in user_data:
            user.avatar = user_data["picture"]
        else:
            user.avatar = "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg"
        user = user.save()
        return user
Exemplo n.º 44
0
def login():
    data = request_to_dict(request.form)
    if request.method == 'POST':
        try:
            user = User.get(login=data['login'])
            user.log_in(password=data['password'])
            if not user.is_authenticated():
                user = None
        except DoesNotExist:
            user = None
    else:
        user = None
    return  render_template('login.html', user=user)
Exemplo n.º 45
0
    def get_invitation(self, userid, inviteid):
        """Returns a user's collection of Invitations"""
        #TODO replace boilerplate with decorator
        user = User.get(id)

        if not user:
            raise NotFound()

        if current_user.id != user.id:
            raise Unauthorized('user id does not match requesting user id')
        #END boilerplate

        raise NotImplemented('TODO')
Exemplo n.º 46
0
    def post_invitation(self, id):
        """Create a new invitation"""

        #TODO replace boilerplate with decorator
        user = User.get(id)

        if not user:
            raise NotFound()

        if current_user.id != user.id:
            raise Unauthorized('user id does not match requesting user id')
        #END boilerplate

        if len(user.invitations) >= current_app.config.get('MAX_INVITES'):
            raise Conflict("Maximum invitations reached")

        args = user_invitation_post_parser.parse_args()
        email = args.get('email')
        token = generate_invitation_token(user)

        try:
            invite = Invite.create(invitor_id=id, invitee_email=email, token=token)
        except IntegrityError as e:
            raise Conflict('%s has already been invited.' % email)

        invite_link = urljoin(current_app.config['CLIENT_DOMAIN'], '/#/register?token='+token)

        #TODO this mail send should be performed asynchronously using celery, see issue #88850472
        send_message(
            subject="You've been given early access to FogMine",
            sender="*****@*****.**",
            recipients = [user.email],
            html_body=render_template('email/invite.html', user=user, confirmation_link=invite_link),
            text_body=render_template('email/invite.txt', user=user, confirmation_link=invite_link)
        )

        schema = InviteSchema()
        jsonSerializableInvite = schema.dump(invite)[0]

        b = Builder(href=url_for('v1.UsersView:get_invitation', userid=id, inviteid=invite.id))\
            .add_curie('r', url_for('v1.LinkRelationsView:index')+"/{rel}")

        #TODO is there a simpler way to just add the whole dict here?
        for key, value in jsonSerializableInvite.iteritems():
            b.set_property(key, value)

        return b.o, 201
Exemplo n.º 47
0
    def test_confirm_user(self, apidb, testapi, mail, role, invite):
        m = self.test_register_user_sends_confirmation_email(apidb, testapi, mail, role, invite=invite)

        u = User.find(email='*****@*****.**').first()
        u.confirmed_at.should.be.none

        token = self.get_confirmation_token_from_email(m)
        href = url_for('v1.AuthView:confirm_email')

        resp = testapi.post_json(href, dict(token=token))

        # confirmed status should be set
        u.confirmed_at.should_not.be.none

        # confirmed user should receive a login credential set
        resp.status_code.should.equal(200)
        resp.json.get('user').should_not.be.none
Exemplo n.º 48
0
def findUser(zquery):
    from app.models import User
    from pymongo.objectid import ObjectId
    from bson.errors import InvalidId
    from app.helpers.utils import Enum
    import re, sys
    
    SearchTypes = Enum("email account inClass")
    searchType = None
    queryValue = None
    
    # Try to figure out what they're searching by
    if searchType is None:                    
        if re.match(".*@.*", zquery):
            searchType = SearchTypes.email
            queryValue = str(zquery)
        elif re.match("[A-Fa-f0-9]{24}$", zquery):
            searchType = SearchTypes.inClass
            queryValue = ObjectId(zquery)
        elif re.match("[0-2]$", zquery):
            searchType = SearchTypes.account
            queryValue = int(zquery)
    
    if searchType is None:
        print >> sys.stderr, "findUser: Cannot understand search query"
        return False
    else:
        print "findUser: Searching by", SearchTypes.getName(searchType)
    
    searchTypeToKey = {
        SearchTypes.email: "_id",
        SearchTypes.account: "accountType",
        SearchTypes.inClass: "classes"
    }
    
    results = \
        list(User.objects(__raw__ = {searchTypeToKey[searchType]: queryValue}))
    
    print "findUser: Found", len(results), "users matching your query:"
    for i in results:
        print "%s (%s)" % (i.email, User.accountTypes.getName(i.accountType))

    return True
Exemplo n.º 49
0
 def test_password_verification(self):
     u = User(email=u"*****@*****.**", username=u"u", password=u"cat")
     self.assertTrue(u.verify_password(u"cat"))
     self.assertFalse(u.verify_password(u"dog"))
Exemplo n.º 50
0
 def put(self, args, user_id):
     if User.update_user(args, user_id) is -1:
         abort(http_status_code=500, error_code=error_enum.database_error_updating)
     return None, 204
Exemplo n.º 51
0
def create_user(email):
    new_user = User(email=email)
    new_user.save()
Exemplo n.º 52
0
 def put(self, args, user_id):
     if not user_id:
         abort(http_status_code=404, error_code=error_enum.user_id_missing)
     if User.set_user_activity_pref(user_id, args) is -1:
         abort(http_status_code=500, error_code=error_enum.database_error_updating)
     return None, 204
Exemplo n.º 53
0
 def get(self, user_id):
     return {'connections': User.get_user_connections(user_id)}
Exemplo n.º 54
0
 def test_valid_confirmation_token(self):
     u = User(email=u"*****@*****.**", password=u"cat")
     db.session.add(u)
     db.session.commit()
     token = u.generate_confirmation_token()
     self.assertTrue(u.confirm(token))