Exemple #1
0
def lookup_current_user():
    """Set the g.user variable to the User in the database that shares
    openid with the session, if one exists.

    Note that it gets called before all requests, but not before decorators.
    """
    g.user = None
    if not app.config.get('GOOGLE_AUTH_ENABLED'):
        # bypass auth by mocking a super user
        session['gplus_id'] = SUPER_USER_GPLUS_ID
        try:
            g.user = User.objects.get(gplus_id=SUPER_USER_GPLUS_ID)
        except DoesNotExist:
            user = User(name='Super User',
                        gplus_id=SUPER_USER_GPLUS_ID,
                        user_type='admin',
                        email='*****@*****.**')
            user.save()

    if 'gplus_id' in session:
        gplus_id = session['gplus_id']
        try:
            g.user = User.objects().get(gplus_id=gplus_id)
        except DoesNotExist:
            pass  # Fail gracefully if the user is not in the database yet
Exemple #2
0
def reset_password(payload):
    form = ResetPasswordForm()
    pageTitle = "reset password"

    # disallows password reset link to be reused
    unhashed_payload = User.check_password_reset_link(payload)
    user_email = unhashed_payload[0]
    oldhash = unhashed_payload[1]

    if user_email:
        user_oldhash = User.get(email=user_email).pwdhash[:10]
        if oldhash != user_oldhash:
            flash("Token has been used previously.  Please try again.")
            return redirect(url_for('.forgotPassword'))

    if not user_email:
        flash("Token incorrect or has expired.  Please try again.")
        return redirect(url_for('.forgotPassword'))

    if request.method == 'POST':
        if not form.validate():
            return render_template('users/resetPassword.html',
                                   form=form,
                                   pageTitle=pageTitle)
        else:
            user = User.get(email=user_email)
            user.set_password(form.password.data)
            user.save()
            #email password reset
            flash("Password has been reset, please login")
            return redirect(url_for('.login'))
    elif request.method == 'GET':
        return render_template('users/resetPassword.html',
                               form=form,
                               pageTitle=pageTitle)
Exemple #3
0
def signup(request):

    print '\n\nsignup'

    if request.method == 'POST':

        email = request.POST['email']
        pwd = request.POST['pwd']
        temp = ""

        print email+ " "+pwd

        try:
            temp = User.objects.get(email=email).email
        except Exception as e:
            print e

        if not temp == email:
            user = User(email=email, pwd=pwd)
            user.save()
            msg = "Signup Success"
            status = 1
        else:
            msg = "Email is already taken"
            status = 0
            #return HttpResponse(json.dumps(dict), mimetype="application/json", status=500)
        print "asd"

        dict = {'email': email, 'msg': msg, 'status': status}

        return HttpResponse(json.dumps(dict), mimetype="application/json")
Exemple #4
0
    def test_token_auth(self):
        # add a user
        u = User(username='******', email='*****@*****.**', confirmed=True)
        u.password = '******'
        u.save()

        # issue a request with bad token
        response = self.client.get(
            url_for('api.get_user', username='******'),
            headers=self.get_api_headers('badtoken', ''))
        self.assertTrue(response.status_code == 401)

        # get a token
        response = self.client.get(
            url_for('api.get_token'),
            headers=self.get_api_headers('*****@*****.**', 'dog'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))
        self.assertIsNotNone(json_response.get('token'))
        token = json_response['token']

        # issue a request with the token
        response = self.client.get(
            url_for('api.get_user', username='******'),
            headers=self.get_api_headers(token, ''))
        self.assertTrue(response.status_code == 200)
Exemple #5
0
def forgotPassword():
    form = ForgotPasswordForm()
    pageTitle = "forgot password"

    if request.method == 'POST':
        if not form.validate():
            return render_template('users/forgotPassword.html',
                                   form=form,
                                   pageTitle=pageTitle)
        else:
            try:
                user = User.get(email=form.email.data.lower().strip())
            except:
                flash("That email does not exist, please try another.")
                return render_template('users/forgotPassword.html',
                                       form=form,
                                       pageTitle=pageTitle)

            # # disallows password reset link to be reused
            # oldhash = user.pwdhash[:10]
            # payload = User.get_password_reset_link(user) + oldhash

            payload = User.get_password_reset_link(user)
            email_password_reset(user, payload)

            flash("Password reset email has been sent. \
                   Link is good for 24 hours.")
            return redirect(url_for('index'))
    elif request.method == 'GET':
        return render_template('users/forgotPassword.html',
                               form=form,
                               pageTitle="Forgot Password")
 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 == "*****@*****.**")
 def test_dashboard_user_list_resource_get_with_valid_token_and_role(self):
     r = Role(name='admin')
     u = User(username='******', email='*****@*****.**')
     u.set_password('test')
     u.roles.append(r)
     u1 = User(username='******', email='*****@*****.**')
     u2 = User(username='******', email='*****@*****.**')
     db.session.add(r)
     db.session.add(u)
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     response = self.client.post(api.url_for(LoginResource),
                                 data=json.dumps({'username': '******', 'password': '******'}),
                                 headers=self.get_headers())
     json_data =  json.loads(response.data.decode('utf-8'))
     token = json_data['token']
     response = self.client.get(self.url, headers=self.get_headers(token))
     self.assertEqual(response.status_code,200)
     users = json.loads(response.data.decode('utf-8'))
     self.assertEqual(len(users),3)
     self.assertEqual(users[0]['username'],'test')
     self.assertEqual(users[1]['username'],'foo')
     self.assertEqual(users[2]['username'],'bar')        
     self.assertTrue('email' in users[0])
     self.assertTrue('registered_at' in users[0])
     self.assertTrue('last_seen' in users[0])
     self.assertTrue('id' in users[0])
     self.assertTrue('roles' in users[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_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'))
Exemple #10
0
def api_register():
    try:
        username = request.form['username']
        password = request.form['password']
    except:
        username = None
        password = None
    if username is None or password is None:
        return jsonify({
            "status": "error",
            "error": "Missing arguments",
            "message": "Not username or password sent"
        })
    if User.query.filter_by(username=username).first() is not None:
        return jsonify({
            "status": "error",
            "error": "Existing user",
            "message": "User already exists, username is already taken"
        })
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return jsonify(
        {'username': user.username,
         "status":"success",
         "id":user.id}),\
           201,\
           {'Location': url_for('get_user', id = user.id, _external=True)}
Exemple #11
0
def initialize_database():
    sys.stderr.write("Initializing the first user\n\n")

    field_names = {
        'email' : 'Email address',
        'first_name' : 'First name',
        'last_name' : 'Last name',
        'cb_username' : 'Mapped Carbon Black username'
    }

    field_order = ('email', 'first_name', 'last_name', 'cb_username')

    u = User()
    for field in field_order:
        sys.stderr.write(field_names[field] + ': ')
        sys.stderr.flush()
        response = sys.stdin.readline().strip()
        setattr(u, field, response)

    # capture password
    password_mismatch = True
    while password_mismatch:
        try:
            pass1 = getpass.getpass("Password: "******"Confirm : ")
            if pass1 == pass2:
                password_mismatch = False
            else:
                sys.stderr.write("Passwords don't match\n")
        except getpass.GetPassWarning:
            sys.exit(1)

    u.password = pass1

    app.create_base_data(u)
Exemple #12
0
    def setUpClass(cls):
        try:
            cls.client = webdriver.Firefox()
        except:
            pass

        if cls.client:
            cls.app = create_app('testing')
            cls.app_context = cls.app_context()
            cls.app_context.push()

            import logging
            logger = logging.getLogger('werkzeug')
            logger.setLevel("ERROR")

            db.create_all()
            Role.insert_roles()
            User.generate_fake(10)
            Post.generate_fake(10)

            admin_role = Role.query.filter_by(permissions=0xff).first()
            admin = User(email='*****@*****.**',
                         username='******', password='******',
                         role=admin_role, confirmed=True)
            db.session.add(admin)
            db.session.commit()

            threading.Thread(target=cls.app.run).start()
            time.sleep(1)
	def test_take(self):
		u1 = User(full_name = 'Alex', netid = 'd302304')
		u2 = User(full_name = 'Santiago', netid = 'd30st04')
		db.session.add(u1)
		db.session.add(u2)
		db.session.commit()

		d1 = Department(name = "Dept 1", abbr = "DEPT")
		db.session.add(d1)
		db.session.commit()

		c1 = Course(name = 'Course', number = "1", department = d1.id)
		db.session.add(c1)
		db.session.commit()

		t1 = Term(year = 2013, season = "F")
		db.session.add(t1)
		db.session.commit()

		h1 = Hour(period = "3A")
		db.session.add(h1)
		db.session.commit()

		o1 = Offering(course = c1.id, term = t1.id, hour = h1.id)
		db.session.add(o1)
		db.session.commit()

		u = u1.take(o1)
		db.session.add(u)
		db.session.commit()
		assert u1.take(o1) == None
		assert u1.is_taking(o1)
 def test_avatar(self):
     # create a user
     u = User(nickname='john', email='*****@*****.**')
     avatar = u.avatar(128)
     expected = 'http://www.gravatar.com/avatar/' + \
         'd4c74594d841139328695756648b6bd6'
     assert avatar[0:len(expected)] == expected
 def test_album_children_list_resource_get_with_valid_token(self):
     u = User(username='******', email='*****@*****.**')
     u.set_password('test')
     a1 = Album(path='/album1')
     a2 = Album(path='/album2')
     a3 = Album(path='/album3')
     a4 = Album(path='/album4')
     a1.children.append(a2)
     a1.children.append(a3)
     a1.children.append(a4)
     db.session.add(u)
     db.session.add(a1)
     db.session.add(a2)
     db.session.add(a3)
     db.session.add(a4)
     db.session.commit()
     album_id = a1.id
     response = self.client.post(api.url_for(LoginResource),
                                 data=json.dumps({'username': '******', 'password': '******'}),
                                 headers=self.get_headers())
     json_data =  json.loads(response.data.decode('utf-8'))
     token = json_data['token']
     response = self.client.get(api.url_for(AlbumChildrenListResource,album_id=album_id), headers=self.get_headers(token))
     self.assertEqual(response.status_code,200)
     albums = json.loads(response.data.decode('utf-8'))
     self.assertEqual(len(albums),3)
     self.assertTrue('id' in albums[0])
     self.assertTrue('title' in albums[0])
     self.assertTrue('description' in albums[0])
     self.assertTrue('timestamp_from' in albums[0])
     self.assertTrue('timestamp_to' in albums[0])
     self.assertFalse('path' in albums[0])
     self.assertFalse('created_at' in albums[0])
Exemple #16
0
    def post(self, reciepent, text):
        reciepent = User.get_by_key_name(reciepent)
        sender = User.get_by_key_name(self.fb_uid)

        chatjoin = ChatJoin.get_chat(sender.fb_uid, reciepent.fb_uid)

        message = Message(chatjoin = chatjoin, sender = sender, text = text)
        message.put()

        chatjoin.put()

        chat = Chat(key_name = sender.fb_uid + '|' + reciepent.fb_uid,
                    chatjoin = chatjoin,
                    user = sender,
                    other = reciepent,
                    date = message.date,
                    last_message_text = message.text,
                    read = True)
        chat.put()

        chat = Chat(key_name = reciepent.fb_uid + '|' + sender.fb_uid,
                    chatjoin = chatjoin,
                    user = reciepent,
                    other = sender,
                    date = message.date,
                    last_message_text = message.text,
                    read = False)
        chat.put()

        self.send_message(reciepent.fb_uid, {
            'type' : 'new-chat',
            'chat' : chat,
        })
        return True
Exemple #17
0
def delete(user_id):
    """Delete the user with id `user_id`

    If the `revoke` property is set to true,
    then the user will be removed from the whitelist, and not be
    allowed to make an account again.
    """
    object_id = ObjectId(user_id)
    if User.objects(id=object_id).count() != 1:
        abort(401)
    user = User.objects().get(id=object_id)

    # Update whitelist
    try:
        wl = Whitelist.objects().get(email=user.email)
        wl.redeemed = False
        wl.save()
    except DoesNotExist:
        pass
    user.delete()

    # Log out if a user is attempting to delete themselves
    if 'gplus_id' in session and user.gplus_id == session['gplus_id']:
        flash('You deleted yourself successfully. Logging out.')
        return redirect(url_for('.logout'), 303)
    flash('User deleted successfully.')

    return redirect(url_for('.index'), code=303)
Exemple #18
0
def add_fake_data(number_users):
    """
    Adds fake data to the database.
    """
    User.generate_fake(count=number_users)
    WashingMachine.generate_fake(count=2)
    DryingMachine.generate_fake(count=1)
 def setUpClass(cls):
     try:
         cls.client = webdriver.Firefox()
     except:
         pass
     if cls.client:
         # create app
         cls.app = create_app('testing')
         cls.app_context = cls.app.app_context()
         cls.app_context.push()
         # create log
         import logging
         logger = logging.getLogger('werkzeug')
         logger.setLevel(logging.ERROR)
         # create database
         db.create_all()
         Role.init_roles()
         User.generate_fake(count=10)
         Post.generate_fake(count=10)
         # add admin
         admin_role = Role.query.filter_by(permissions=0xff).first()
         admin = User(email='*****@*****.**', username='******',
                      password='******', role=admin_role, confirmed=True)
         db.session.add(admin)
         db.session.commit()
         # run server in child thread
         Thread(target=cls.app.run).start()
	def setUpClass(cls):
		#launch Firefox
		try:
			cls.client = webdriver.Chrome()
		except:
			pass

		if cls.client:
			cls.app = create_app('testing')
			cls.app_context = cls.app.app_context()
			cls.app_context.push()

			import logging
			logger = logging.getLogger('werkzeug')
			logger.setLevel('ERROR')

			# create database, and fill it up with some faked data
			db.create_all()
			Role.insert_roles()
			User.generate_fake(10)
			Post.generate_fake(10)

			# add administrater
			admin_role = Role.query.filter_by(permissions=0xff).first()
			admin = User(email='*****@*****.**',
						 username='******', password='******',
						 role=admin_role, confirmed=True)
			db.session.add(admin)
			db.session.commit()

			# launch Flask server in a thread
			threading.Thread(target=cls.app.run).start()

			# give the server a second to ensure it is up
			time.sleep(1)
def register():
    form = RegisterForm()
    thepassword = generate_password()
    if form.validate_on_submit():
        username = request.form['username']
        invitecode = request.form['invitecode'].strip()
        invite = db.session.query(Invites).filter(Invites.invite_code == invitecode, Invites.active == True).first()
        if invite:
            newuser = User()
            newuser.username = username
            if bleach.clean(username) != username:
                flash("Bad user name")
                return render_template("register.html", form=form)
            newuser.password = bcrypt.hashpw(thepassword.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            newuser.role = 'User'
            try:
                # Add user
                db.session.add(newuser)
                db.session.commit()
                # Invalidate user code
                invite.active = False
                db.session.merge(invite)
                db.session.commit()
                flash('User {} created.'.format(username))
                success_data = {'username': username, 'password': thepassword}
                return render_template("register.html", form=form, success_data=success_data)
            except Exception as e:
                flash('Failed to create user {}'.format(username))
                db.session.rollback()
                return render_template("register.html", form=form)
        flash("Invalid invite code.")
        return render_template("register.html", form=form)
    return render_template("register.html", form=form)
Exemple #22
0
def recreate_data():
    """Generate fake data for development and testing"""
    print 'dropping existing tables...'
    db.drop_all()
    print 'creating tables...'
    db.create_all()
    print 'inserting roles...'
    Role.insert_roles()
    print 'creating admin user...'
    u1 = User(username='******', email='*****@*****.**', password='******',
              name='Ralph Wen', location='Hangzhou, China',
              about_me='This is the creator of everything', confirmed=True)
    db.session.add(u1)
    print 'creating moderate user...'
    u2 = User(username='******', email='*****@*****.**', password='******',
              name='Yadong Wen', location='Hangzhou, China',
              about_me='Yeah', confirmed=True)
    db.session.add(u2)
    db.session.commit()
    print 'generating 50 normal users...'
    User.generate_fake(50)
    print 'generating 500 posts...'
    Post.generate_fake(500)
    print 'generating follows...'
    User.generate_following()
    print 'generating comments...'
    Comment.generate_comments()
    print '...done'
Exemple #23
0
def deploy():
    """Run development tasks."""
    from flask.ext.migrate import upgrade
    from app.models import Role, User
    upgrade()
    Role.insert_roles()
    User.add_self_follows()
Exemple #24
0
    def test_delete(self):
        u1 = User(login='******', password='******')
        u2 = User(login='******', password='******')
        p = Product(type=1234567890, serial=123456, week=45, year=15)
        c = Comment(body='comment body', author_id=u1.id, product_id=p.get_product_id())
        db.session.add_all([u1, u2, p, c])
        db.session.commit()

        # wrong user --> 403
        token = u2.get_api_token()
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='DELETE',
                data=json.dumps({'token': token}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 403)

        token = u1.get_api_token()
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='DELETE',
                data=json.dumps({'token': token}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200)
            c = Comment.query.get(c.id)
            self.assertIsNone(c)
Exemple #25
0
    def test_user_password(self, testapp):
        """ Test password hashing and checking """

        admin = User('admin', 'supersafepassword')

        assert admin.username == 'admin'
        assert admin.check_password('supersafepassword')
Exemple #26
0
    def parse_content(self):
        title = self.html.xpath('//h1[@class="article-title"]/text()')
        if title:
            self.title = title[0]

        author = self.html.xpath('//a[@class="author-item"]/text()')
        if author:
            self.author = author[0]

        rate = self.html.xpath('//span[@class="rating-average"]/text()')
        if rate:
            self.rate = float(rate[0])

        img_url = self.html.xpath('//div[@class="cover shadow-cover"]/img/@src')
        if img_url:
            self.img_url = img_url[0]

        self.detail = self.html.xpath('//div[@class="article-profile-section article-profile-intros"]//p/text()')
        self.tags = self.html.xpath('//*[@class="tags"]//span[1]/text()')
        self.category = ''

        if not BookInfo.objects(title=self.title, author=self.author):
            new_book = self.save()
            new_book.update(push__owner=User.objects.get(id=self.owner_id))
            User.objects(id=self.owner_id).first().update(push__owned_book=new_book)
            return True
        else:
            exist_book = BookInfo.objects(title=title)
            add_book = exist_book.update(push__owner=User.objects.get(id=self.owner_id), inc__num=1)
            User.objects(id=self.owner_id).first().update(push__owned_book=exist_book.first())
            return True
Exemple #27
0
def activity():
    '''
    View for the activity feed of recent events.
    '''

    events = get_latest_events()
    shared_message_form = SharedMessageForm()

    if request.method == 'POST':
        if not current_user.is_authenticated():
            flash(gettext(u'You must log in to post a message.'), 'error')
        elif not current_user.display_in_search:
            flash(gettext(u'We need your name before you can post a message.'), 'error')
        elif shared_message_form.validate():
            data = shared_message_form.message.data
            msg = SharedMessageEvent.from_user(
                current_user,
                message=data
            )
            db.session.add(msg)
            db.session.commit()
            flash(gettext(u'Message posted!'))
            return redirect(url_for('views.activity'))

    return render_template('activity.html', **{
        'user': current_user,
        'events': events,
        'blog_posts': get_blog_posts(),
        'page_config_json': json_blob(
            LOADING_TEXT=gettext("Loading...")
        ),
        'most_complete_profiles': User.get_most_complete_profiles(limit=5),
        'most_connected_profiles': User.get_most_connected_profiles(limit=5)
    })
Exemple #28
0
def initdb():
    """Initialize MySQL databse."""
    from app.libs.db import init_db
    from app.models import Permission, User, Topic
    from app.base.roles import Roles
    from app.settings import Admins, Topics
    from app.libs.utils import encrypt_password

    click.echo('[2L] {0}..'.format(initdb.__doc__))
    init_db()

    click.echo('\n\n[2L] init permisions...')
    for attr, role in Roles.__dict__.items():
        if (not attr.startswith('__') and '{0}' not in role and
                role != 'root'):
            click.echo(' -> {0}'.format(role))
            Permission.create(role)

    click.echo('\n\n[2L] init master chief...')
    bit_sum = Permission.root_permission()
    for admin in Admins:
        click.echo(' -> {0}'.format(admin))
        if admin['role'] == 'root':
            admin['role'] = bit_sum
        else:
            admin['role'] = (Permission.get_by_role(admin['role']).bit |
                             Permission.get_by_role('comment').bit |
                             Permission.get_by_role('vote').bit)
        admin['password'] = encrypt_password(admin['password'])
        User.create(**admin)

    click.echo('\n\n[2L] create default topics...')
    for topic in Topics:
        click.echo(' -> {0}'.format(topic))
        Topic.create(**topic)
Exemple #29
0
    def parse_content(self):
        title = self.html.xpath('//h1/span/text()')
        if title:
            self.title = title[0]

        author = self.html.xpath('//div[@id="info"]//a/text()')
        if author:
            self.author = author[0]

        rate = self.html.xpath('//div[@class="rating_wrap"]//strong/text()')  # float
        if rate:
            if '.' in rate[0]:  # 匹配少于10人评分
                self.rate = float(rate[0])

        img_url = self.html.xpath('//div[@class="article"]//a[@class="nbg"]/@href')
        if img_url:
            self.img_url = img_url[0]

        self.detail = self.html.xpath('//div[@class="intro"]/p/text()')  # paragraph, lists
        self.tags = self.html.xpath('//div[@class="indent"]/span/a/text()')  # lists
        if not BookInfo.objects(title=self.title, author=self.author):
            new_book = self.save()
            new_book.update(push__owner=User.objects.get(id=self.owner_id))
            User.objects(id=self.owner_id).first().update(push__owned_book=self.new_book)
            return True
        else:
            exist_book = BookInfo.objects(title=self.title).first()
            add_book = exist_book.update(push__owner=User.objects.get(id=self.owner_id), inc__num=1)
            User.objects(id=self.owner_id).first().update(push__owned_book=exist_book)
            return True
Exemple #30
0
def deploy():
    from flask_migrate import upgrade
    from app.models import Role, User

    upgrade()
    Role.insert_roles()
    User.add_self_follows()
Exemple #31
0
 def add_user(self, username='******', password='******', admin=False):
     user = User(username=username, admin=admin)
     user.set_password(password)
     db.session.add(user)
     db.session.commit()
     return user
Exemple #32
0
 def test_password_verification(self):
     u = User(password='******')
     self.assertTrue(u.verify_password('cat'))
     self.assertFalse(u.verify_password('dog'))
Exemple #33
0
    def test_follow_posts(self):
        # create four users
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        u3 = User(username='******', email='*****@*****.**')
        u4 = User(username='******', email='*****@*****.**')
        db.session.add_all([u1, u2, u3, u4])

        # create four posts
        now = datetime.utcnow()
        p1 = Post(body="post from john",
                  author=u1,
                  timestamp=now + timedelta(seconds=1))
        p2 = Post(body="post from susan",
                  author=u2,
                  timestamp=now + timedelta(seconds=4))
        p3 = Post(body="post from mary",
                  author=u3,
                  timestamp=now + timedelta(seconds=3))
        p4 = Post(body="post from david",
                  author=u4,
                  timestamp=now + timedelta(seconds=2))
        db.session.add_all([p1, p2, p3, p4])
        db.session.commit()

        # setup the followers
        u1.follow(u2)  # john follows susan
        u1.follow(u4)  # john follows david
        u2.follow(u3)  # susan follows mary
        u3.follow(u4)  # mary follows david
        db.session.commit()

        # check the followed posts of each user
        f1 = u1.followed_posts().all()
        f2 = u2.followed_posts().all()
        f3 = u3.followed_posts().all()
        f4 = u4.followed_posts().all()
        self.assertEqual(f1, [p2, p4, p1])
        self.assertEqual(f2, [p2, p3])
        self.assertEqual(f3, [p3, p4])
        self.assertEqual(f4, [p4])
Exemple #34
0
 def test_avatar(self):
     u = User(username='******', email='*****@*****.**')
     self.assertEqual(u.avatar(128), ('https://gravatar.com/avatar/'
                                      'd4c74594d841139328695756648b6bd6'
                                      '?d=identicon&s=128'))
Exemple #35
0
 def test_password_hashing(self):
     u = User(username='******')
     u.set_password('cat')
     self.assertFalse(u.check_password('dog'))
     self.assertTrue(u.check_password('cat'))
Exemple #36
0
 def get(self):  # 判断是否已经关注
     current_user = User.get_current_user()
     user_id = request.args.get('user_id')
     target_user = User.query.get(user_id)
     return current_user.is_following(target_user)
Exemple #37
0
#

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import csv
from app import db
from app.models import League, Team, Record, User

print('Test data base...')
db.session.remove()
db.drop_all()
db.create_all()

print('Adding users...')
u1 = User('husthsz')
u2 = User('namiszh')
db.session.add(u1)
db.session.add(u2)

print('Adding leagues...')
l1 = League(573, 'Never Ending')
l2 = League(id=818, name='Alpha')
db.session.add(l1)
db.session.add(l2)

print('Adding teams...')
t1 = Team(1, "A1", l1, u1)
t2 = Team(2, "AA", l1)
t3 = Team(1, "A1", l2, u1)
t4 = Team(2, "AA", l2, u2)
Exemple #38
0
 def test_confirm_confirmation_token(self):
     u = User()
     token = u.generate_confirmation_token()
     self.assertTrue(u.confirm(token))
Exemple #39
0
 def test_password_salts_are_random(self):
     u = User(password='******')
     u2 = User(password='******')
     self.assertTrue(u.password_hash != u2.password_hash)
Exemple #40
0
    def test_follow_and_unfollow_user_using_is_folling_and_is_followed_byr(
            self):
        u1 = User()
        u2 = User()

        u1.follow(u2)
        db.session.add_all([u1, u2])
        db.session.commit()

        self.assertTrue(u1.is_following(u2))
        self.assertTrue(u2.is_followed_by(u1))

        u1.unfollow(u2)
        db.session.commit()
        self.assertFalse(u1.is_following(u2))
Exemple #41
0
 def test_password_setter(self):
     u = User(password='******')
     self.assertTrue(u.password_hash is not None)
Exemple #42
0
 def test_generate_confirmation_token(self):
     u = User()
     token = u.generate_confirmation_token()
     self.assertTrue(token is not None)
Exemple #43
0
 def setUp(self):
     self.user_kets = User(username = '******',email = '*****@*****.**',secure_password = '******',bio= 'The greatest minds are capable of the greatest vices as well as of the greatest virtues. ', profile_pic_path='https://cdn.britannica.com/s:250x250,c:crop/62/176962-050-4BC9F588/Rene-Descartes.jpg')
     self.new_pitch = Pitch(id=12,title='Psychic',pitch="philosophy is all about perspective",category='hobbies',user_id= self.user_kets.id, time="2010/2/3 13:20" )
Exemple #44
0
 def test_no_password_getter(self):
     u = User(password='******')
     with self.assertRaises(AttributeError):
         u.password
Exemple #45
0
 def setUp(self):
     self.new_user = User(password='******')
 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))
Exemple #47
0
def admin():
    if current_user.username != "admin":
        return redirect(url_for("logout"))
    category = request.args["cat"] if "cat" in request.args.keys() else None
    if category == "users_add":
        form = UserAddForm()
        if form.validate_on_submit():
            userlist = form.userlist.data
            userlist = userlist.splitlines()
            document = Document()
            for user in userlist:
                u = User()
                u.name = user.replace("\n\r", "").strip()
                u.username = user.strip().replace(" ", "_").replace("\n\r", "")
                letters = string.ascii_lowercase
                password = "".join(random.choice(letters) for i in range(10))
                u.set_password(password)
                document.add_paragraph(
                    f"Voici vos informations pour accéder à Cantina :\n"
                    "Adresse du site : https://cantina.sivu-2vallees.fr/\n"
                    f"Nom d'utilisateur : {u.username}\n"
                    f"Mot de passe : {password}\n")
                db.session.add(u)
                db.session.commit()
            document.save("/tmp/Liste.docx")
            return send_file(
                "/tmp/Liste.docx",
                mimetype=
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                attachment_filename="Liste.docx",
                as_attachment=True,
            )
        return render_template("admin.html", category=category, form=form)
    elif category == "user_mod":
        form = UserModForm()
        if request.method == "GET":
            return render_template("admin.html",
                                   category=category,
                                   user=current_user,
                                   form=form)
        elif request.method == "POST":
            if form.validate_on_submit():
                new_password = request.form["userpass"]
                if ("delete_user" in request.form.keys()
                        and request.form["delete_user"] == "y"):
                    user_name = request.args["user"]
                    user = User.query.filter(
                        User.username == user_name).all()[0]
                    db.session.delete(user)
                    db.session.commit()
                    flash("Utilisateur supprimé !")
                elif len(new_password) > 6:
                    user_name = request.args["user"]
                    user = User.query.filter(
                        User.username == user_name).all()[0]
                    user.set_password(new_password)
                    db.session.add(user)
                    db.session.commit()
                    flash(f"Mot de passe mis à jour pour {user.username}")
                else:
                    flash("Le mot de passe doit faire au minimum 6 caractères")
                return redirect(request.referrer)
    elif category == "users_del":
        if request.method == "POST":
            for user in request.form:
                to_delete = db.session.query(User).filter(
                    User.username == user).first()
                db.session.delete(to_delete)
            db.session.commit()
        userlist = [
            u for u in User.query.filter(User.username != "admin").all()
        ]
        return render_template("admin.html",
                               category=category,
                               userlist=userlist)
    elif category == "export":
        if request.method == "GET":
            return render_template("admin.html",
                                   category=category,
                                   periods=calendar.periods)
        if "period" not in request.form.keys():
            flash("Veuillez sélectionner une période")
            return render_template("admin.html",
                                   category=category,
                                   periods=calendar.periods)
        if "booking_type" not in request.form.keys():
            flash("Veuillez sélectionner un type de réservation")
            return render_template("admin.html",
                                   category=category,
                                   periods=calendar.periods)
        period = int(request.form.get("period"))
        date_begin = arrow.get(calendar.periods[period]["begin"], "YYYYMMDD")
        date_end = arrow.get(calendar.periods[period]["end"], "YYYYMMDD")
        data = {}
        booking = CATEGORIES[request.form.get("booking_type")].query.all()
        for db_line in booking:
            for date_str in db_line.booked.split():
                date = arrow.get(date_str, "YYYYMMDD")
                if date_begin < date < date_end:
                    date_string = date.format("YYYY-MM-DD")
                    if date_string not in data.keys():
                        data[date_string] = []
                    data[date_string].append(db_line.username)
        if data == {}:
            flash("Aucune donnée pour la période demandée")
            return render_template("admin.html",
                                   category=category,
                                   periods=calendar.periods)
        create_xls(data)
        cat = request.form.get("booking_type")
        return send_file(
            "/tmp/workbook.xlsx",
            attachment_filename=f"Réservations_{cat}_période_{period}.xlsx",
            as_attachment=True,
        )
    elif category == "configuration":
        if request.method == "GET":
            data = db.session.query(Configuration).order_by("config_order")
            return render_template("admin.html", category=category, data=data)
        elif request.method == "POST":
            for item in request.form:
                c = (db.session.query(Configuration).filter(
                    Configuration.config_key == item).first())
                c.value = request.form.get(item)
                db.session.commit()
                if item in ["mail_cantine_time", "mail_garderie_time"]:
                    hour, minute = c.value.split(":")
                    conf_name = c.config_key.replace("_time", "")
                    m = (db.session.query(Configuration).filter(
                        Configuration.config_key == conf_name).first())
                    args = {"mail_list": m.value.split()}
                    if arrow.now().isoweekday() == 5:
                        day = arrow.now().shift(days=+3).format("YYYYMMDD")
                    else:
                        day = arrow.now().shift(days=+1).format("YYYYMMDD")
                    args["day"] = day
                    if "cantine" in item:
                        data = db.session.query(BookingCantine)
                        booked = [
                            d.username for d in data.all() if day in d.booked
                        ]
                        args["book_cantine"] = booked
                    elif "garderie" in item:
                        booked = {}
                        data = db.session.query(BookingGarderieMatin)
                        book = [
                            d.username for d in data.all() if day in d.booked
                        ]
                        booked["Garderie Matin"] = book
                        data = db.session.query(BookingGarderieSoir)
                        book = [
                            d.username for d in data.all() if day in d.booked
                        ]
                        booked["Garderie Soir"] = book
                        args["book_garderie"] = booked

    return render_template("admin.html")
 def setUp(self):
     self.new_user = User(password="******")
Exemple #49
0
 def test_follows(self):
     u1 = User(email='*****@*****.**', password='******')
     u2 = User(email='*****@*****.**', password='******')
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     self.assertFalse(u1.is_following(u2))
     self.assertFalse(u1.is_followed_by(u2))
     timestamp_before = datetime.utcnow()
     u1.follow(u2)
     db.session.add(u1)
     db.session.commit()
     timestamp_after = datetime.utcnow()
     self.assertTrue(u1.is_following(u2))
     self.assertFalse(u1.is_followed_by(u2))
     self.assertTrue(u2.is_followed_by(u1))
     self.assertTrue(u1.followed.count() == 2)
     self.assertTrue(u2.followers.count() == 2)
     f = u1.followed.all()[-1]
     self.assertTrue(f.followed == u2)
     self.assertTrue(timestamp_before <= f.timestamp <= timestamp_after)
     f = u2.followers.all()[-1]
     self.assertTrue(f.follower == u1)
     u1.unfollow(u2)
     db.session.add(u1)
     db.session.commit()
     self.assertTrue(u1.followed.count() == 1)
     self.assertTrue(u2.followers.count() == 1)
     self.assertTrue(Follow.query.count() == 1)
     u2.follow(u1)
     db.session.add(u1)
     db.session.add(u2)
     db.session.commit()
     db.session.delete(u2)
     db.session.commit()
     self.assertTrue(Follow.query.count() == 1)
Exemple #50
0
def admin():
    id = request.get_json()['id']
    User.give_admin(id)
    return {}, 200
Exemple #51
0
 def test_roles_and_permissions(self):
     Role.insert_roles()
     u = User(email='*****@*****.**', password='******')
     self.assertTrue(u.can(Permission.WRITE_ARTICLES))
     self.assertFalse(u.can(Permission.MODERATE_COMMENTS))
Exemple #52
0
 def validate_username(self, username):
     if User.objects(username=username.data).first():
         raise ValidationError('用户名已存在')
from app import *
from app.models import User, Post, Tag, Comment

user1 = User(username='******', password_hash='user1', permission=1)
user2 = User(username='******', password_hash='user2', permission=0)
user3 = User(username='******', password_hash='user3')
db.session.add(user1)
db.session.add(user2)
db.session.add(user3)
db.session.commit()
u = User.query.get(1)
post1 = Post(title='my first post', content='my first post!',tag='tag1,tag2,tag3', username=u)
post2 = Post(title='my first post', content='my first post!',tag='tag2,tag3,tag4', username=u)
db.session.add(post1)
db.session.add(post2)
db.session.commit()

tag1 = Tag(tag='tag1')
tag2 = Tag(tag='tag2')
tag3 = Tag(tag='tag3')
db.session.add(tag1)
db.session.add(tag2)
db.session.add(tag3)
db.session.commit()

p = Post.query.get(1)
comment1 = Comment(content='nice', title=p, username=u)
comment2 = Comment(content='nice', title=p, username=u)
db.session.add(comment1)
db.session.add(comment2)
db.session.commit()
Exemple #54
0
 def validate_email(self, email):
     user = User.get_by_email(email.data)
     if user is not None:
         raise ValidationError('Please use a different email address.')
Exemple #55
0
from app import app, db, mqtt, photos
from flask import render_template, redirect, url_for, flash, request
from app.forms import RegisterRunnerForm, AddCheckpointForm, SignInForm, SignUpForm, RegisterRaceForm, EditRaceForm, EditCheckpointForm, RegisterForRace, SignUpForm
from app.models import User, Event, Race, Runner, Checkpoint
from flask_login import current_user, login_user, logout_user
from bson.objectid import ObjectId
from werkzeug.urls import url_parse

races_col = db.races
users_col = db.users
events_col = db.events
runners_col = db.runners
checkpoints_col = db.checkpoints

user = User(username = '******')
user.set_password('admin')
users_col.insert_one(user.__dict__)


@app.route('/')
def index():
	list = [race for race in races_col.find()]
	return render_template('index.html', races=list)


@app.route('/sign_in', methods=['GET', 'POST'])
def login():
	title = "Login"
	if current_user.is_authenticated:
		return redirect(url_for('index'))
	form = SignInForm()
Exemple #56
0
def api_add_user():
    """Add new user
    Will receive data like this
    {
        "email": "*****@*****.**",
        "date_of_birth": "1999-06-18",
        "role": "patient" or "doctor" "super_admin"
        "password": "******",
        "full_name": "Farhad Hossain",
        "address": "Stadium para, Maijdee court",
        "contact_no": "01983495680",
        "age": 21,
        "profile_pic": "base64 encoded image string"
    }
    """
    data = request.get_json()

    username = secrets.token_hex(8)

    email = data['email'].lower()

    password = bcrypt.generate_password_hash(data['password']).decode('utf-8')
    date_of_birth = data['date_of_birth']

    if 'role' not in data:
        role = 'patient'
    else:
        role = data['role']

    full_name = data['full_name']
    address = data['address']
    contact_no = data['contact_no']
    age = data['age']

    if 'profile_pic' in data:
        profile_pic = data['profile_pic']
        imgdata = base64.b64decode(profile_pic.split(',')[1])
        filename = save_picture(img=imgdata, folder="profile_pics")

    # check if email already exists
    user = User.query.filter_by(email=email).first()

    if user:
        return jsonify({"message": "user exists"}), 403

    user = User(username=username,
                email=email,
                password=password,
                date_of_birth=date_of_birth,
                role=role)

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

    if role == "patient":
        # now add the patient infos
        if 'profile_pic' in data:
            # now add the patient infos
            patient = Patient(full_name=full_name,
                              address=address,
                              contact_no=contact_no,
                              age=age,
                              profile_pic=filename,
                              user_id=user.id)
        else:
            patient = Patient(full_name=full_name,
                              address=address,
                              contact_no=contact_no,
                              age=age,
                              user_id=user.id)

        db.session.add(patient)
        db.session.commit()

    elif role == "doctor":
        # now add the doctor infos
        if 'profile_pic' in data:
            # now add the patient infos
            doctor = Doctor(full_name=full_name,
                            address=address,
                            contact_no=contact_no,
                            age=age,
                            profile_pic=filename,
                            user_id=user.id)
        else:
            doctor = Doctor(full_name=full_name,
                            address=address,
                            contact_no=contact_no,
                            age=age,
                            user_id=user.id)

        db.session.add(doctor)
        db.session.commit()

    elif role == "super_admin":
        # now add the super_admin infos
        if 'profile_pic' in data:
            # now add the patient infos
            super_admin = SuperAdmin(full_name=full_name,
                                     address=address,
                                     contact_no=contact_no,
                                     age=age,
                                     profile_pic=filename,
                                     user_id=user.id)
        else:
            super_admin = SuperAdmin(full_name=full_name,
                                     address=address,
                                     contact_no=contact_no,
                                     age=age,
                                     user_id=user.id)

        db.session.add(super_admin)
        db.session.commit()
    else:
        return jsonify({"message": "invalid role"}), 403

    return jsonify({"message": "success"}), 201
Exemple #57
0
def register():
    form = RegisterForm()
    if form.validate_on_submit() and (int(form.membertype.data) in [
            1, 2
    ]) and (int(form.persontype.data) in [0, 1, 2]):
        passwordReal = ''.join(
            (random.choice(chars)) for x in range(app.config['PWS_SIZE']))
        passwordTemp = bcrypt.generate_password_hash(passwordReal)
        form.membertype.data = int(form.membertype.data)
        form.persontype.data = int(form.persontype.data)
        image_url = None
        if form.image_url and is_image_url(form.image_url.data):
            image_url = form.image_url.data
        if (form.persontype.data == 1):
            userObj = User(email=form.email.data,
                           password=passwordTemp,
                           membertype=form.membertype.data,
                           persontype=form.persontype.data,
                           fee=form.fee.data,
                           company=form.company.data,
                           firstname=form.firstname.data,
                           lastname=form.lastname.data,
                           bday=form.bday.data,
                           town=form.town.data,
                           road=form.road.data,
                           postcode=form.postcode.data,
                           phone=form.phone.data,
                           mobile=form.mobile.data,
                           image_url=image_url)
        else:
            userObj = User(email=form.email.data,
                           password=passwordTemp,
                           membertype=form.membertype.data,
                           persontype=form.persontype.data,
                           fee=form.fee.data,
                           firstname=form.firstname.data,
                           lastname=form.lastname.data,
                           bday=form.bday.data,
                           town=form.town.data,
                           road=form.road.data,
                           postcode=form.postcode.data,
                           phone=form.phone.data,
                           mobile=form.mobile.data,
                           image_url=image_url)

        userObj.town = (userObj.town).encode('utf-8')
        bankObj = Bankdetails()
        bankObj.account_holder = (form.firstname.data + " " +
                                  form.lastname.data).title()
        iban = form.iban.data.replace(" ", "")
        ibanobj = IBAN(iban)
        bic = form.bic.data
        bankObj.blz = ibanobj.bank_code
        bankObj.account_no = ibanobj.account_code
        digits = len(iban)
        if not (digits >= 16 and digits <= 34):
            flash('Invalid IBAN Number', 'error')
            return redirect(url_for('register'))
        iban_visible = iban[:6] + 'X' * (digits - 10) + iban[-4:]
        digits = len(bic)
        bic_visible = bic[:2] + 'X' * (digits - 4) + bic[-2:]
        bankObj.iban_visible = iban_visible
        bankObj.bic_visible = bic_visible
        bankObj.iban = EncodeAES(cipher, iban)
        bankObj.bic = EncodeAES(cipher, bic)
        rows = User.query.count()
        bankObj.sepa_ref = 'FraKeKueV'
        if not form.membertype.data:
            bankObj.sepa_ref += 'OrdM'
        else:
            bankObj.sepa_ref += 'FoeM'
        bankObj.sepa_ref += iban_visible[:6]
        bankObj.sepa_ref += str((5 - len(str(rows))) * '0') + str(rows)
        userObj.bankdetails.append(bankObj)

        # Sending Email
        msg = Message('Anmeldung Frankfurter Kelterei Kultur e.V.',
                      sender=ADMINS[0],
                      recipients=[userObj.email])

        body = 'Halle ' + userObj.firstname + endl
        body += 'Login Details:' + endl + 'Email:' + userObj.email + endl + 'Password: '******'Wir freuen uber dein Interesse an der Frankfurter Kelterei Kultur! Du hast folgende Daten fur die Anmeldungubermittelt. Aus Grunden des Datenschutzes, musst du diese Daten ein zweites Mal aktiv bestatigen (double opt-in):'
        ) + endl
        body += ('Mitgliedsart: ' + str(userObj.membertype)) + endl
        if userObj.company:
            body += 'Firma:' + userObj.company + endl
        body += 'Name: ' + (userObj.firstname + ' ' +
                            userObj.lastname).title() + endl
        body += 'Addresse: ' + userObj.town.decode("windows-1252").encode(
            'utf-8') + endl + 'Zipcode: ' + str(userObj.postcode) + endl
        body += 'Alter: ' + userObj.bday.strftime("%Y-%m-%d") + endl * 3
        body += 'Kontodaten' + endl * 4 + '================='
        body += 'Kontoinhaber :' + bankObj.account_holder + endl
        body += 'IBAN :' + bankObj.iban_visible + endl
        body += 'BIC :' + bankObj.bic_visible + endl
        body += 'Monatsbeitrag:' + str(userObj.fee) + 'Euros' + endl
        body += 'Please confirm the correctness of the data by clicking on the following link:' + endl
        confirmationSequence = ''.join(
            (random.choice(chars)) for x in range(50))
        while Confirmation.query.filter_by(
                confirmation_code=confirmationSequence).count() > 0:
            confirmationSequence = ''.join(
                (random.choice(chars)) for x in range(50))
        body += app.config[
            'BASE_URL'] + 'verifyaccount/' + confirmationSequence + endl * 3
        body += 'Loschen der Anmeldung ' + endl
        body += app.config[
            'BASE_URL'] + 'deleteaccount/' + confirmationSequence + endl * 3
        body += 'Beste Grube'
        msg.html = body.encode('utf-8')
        confirmobj = Confirmation(confirmation_code=confirmationSequence)
        try:
            db.session.add(userObj)
            db.session.add(bankObj)
            db.session.add(confirmobj)
            userObj.confirmation.append(confirmobj)
            db.session.commit()
            mail.send(msg)
            flash(
                'Registered Id Successfully! Please verify using link sent to your email',
                'success')
            return redirect(url_for('index'))
        except exc.IntegrityError as e:
            db.session().rollback()
            flash('SQLAlchemy Integrity Error!', 'error')
            return redirect(url_for('register'))
    return render_template('forms/register.html', form=form)
Exemple #58
0
def test_add_user_to_db(db):
    test_user = User(email='*****@*****.**',username = '******', password_hash='1234')
    db.session.add(test_user)
    db.session.commit()
    assert len(User.query.all()) == 1    
Exemple #59
0
 def adduser(u, p):
     new_user = UserModel(name=u, password_hash=UserModel.set_password(p))
     db.session.add(new_user)
     db.session.commit()
     click.echo("Successful!")
Exemple #60
0
    deleteItems(Book.query.all())
    deleteItems(Category.query.all())
    deleteItems(User.query.all())
    # Add items to the db
    addItems(users)
    addItems(categories)
    addItems(books)


# lists
users = []
categories = []
books = []

# USERS
users.append(User(name="Jeffrey L. Jones", email="*****@*****.**"))
users.append(User(name="Robert N. Goley", email="*****@*****.**"))
users.append(User(name="Eric A. Fleming", email="*****@*****.**"))

# CATEGORIES
categories.append(Category(name="Biography"))
categories.append(Category(name="Children"))
categories.append(Category(name="Cooking"))
categories.append(Category(name="Fantasy"))
categories.append(Category(name="History"))
categories.append(Category(name="Horror"))
categories.append(Category(name="Mysteries"))
categories.append(Category(name="Romance"))
categories.append(Category(name="Teen"))

# BOOKS