def setUpFactories(self):
        """This runs when the test class first starts up.
        This does not run before every test case. Use this method to
        set your database up.
        """
        User.create({
            'username': '******',
            'email': '*****@*****.**',
            'password': password('secret'),
            'bio': 'This is a bio',
            'image': '',
            'token': None
        })

        User.create({
            'username': '******',
            'email': '*****@*****.**',
            'password': password('secret')
        })

        Follow.first_or_create(user_id=1, follower_id=2)

        Article.create({
            'title': 'this is a title',
            'slug': 'this-is-a-title',
            'description': 'This is a description',
            'body': 'this is a body',
            'author_id': 1
        })

        Tag.create({'name': 'Python'})
    def store(self, request: Request, auth: Auth, validate: Validator,
              view: View):
        user = User.all()

        email = User.lists('email')
        pw = User.lists('password')

        errors = request.validate(validate.required(['email', 'password']),
                                  validate.email('email'))

        #checks for errors in login inputs and redirects user back to login page.
        if errors:
            return request.back().with_errors(errors).with_input()

        elif request.input('email') not in email and request.input(
                'password') not in pw:
            return request.back().with_errors(
                {'email': ["Email and password not found. Please register."]})

        #check to see if user already had an account which they may have closed/cancelled and need to register for a new account or reactivate account.
        if user.where('email',
                      request.input('email')).where('cancelled', 'Yes'):
            # cancelled = True
            user_id = User.where('email',
                                 request.input('email')).get().pluck('id')
            return request.redirect('/reregister/' + str(user_id[0]))

        #logins user if no errors and account has not been closed/cancelled before
        if auth.login(request.input('email'), request.input('password')):
            return request.redirect('/')

        # returns back to login page if email or password are incorrect
        return request.back().with_errors(
            {'email': ["Email or password is incorrect"]})
Exemple #3
0
def create():
    if request.method == 'POST':
        name = request.form.get('name')
        password = request.form.get('password')
        repeatpd = request.form.get('repeatpd')
        avatar = request.files.get('avatar')
        email = request.form.get('email')
        if User.query.filter_by(name=name).first() is not None:  #用户名存在,返回错误
            return jsonify(Event1003())
        if User.query.filter_by(email=email).first() is not None:  #邮箱存在,返回错误
            return jsonify(Event1005('邮箱已被注册'))
        if password == repeatpd:
            user = User(name=name, password=password, email=email)
            db.session.add(user)
            db.session.commit()
            if avatar and avatar.filename != '':
                avatar.filename = random_filename(avatar.filename)
                avatar.save(
                    os.path.join(current_app.config['UPLOAD_PATH'],
                                 avatar.filename))
                user.avatar = 'http://127.0.0.1:5000/user/image/' + avatar.filename
            db.session.commit()
            send_email('注册成功', user.email, '注册成功欢迎加入我们')
            token = user.make_token()
            r.set(token, str(user.id), ex=3600)
            return jsonify(Event0(token=token))
        return jsonify(Event1005('密码不一致'))
    return jsonify(Event1004())
    def index(self):
        articles = Article.with_('author', 'favorites')

        if self.request.has('author'):
            user = User.where('username', self.request.input('author')).first()

            if user:
                articles.where('author_id', user.id)

        if self.request.has('favorited'):
            user = User.where('username', self.request.input('favorited')).first()
            
            if user:
                articles.where_in('id', user.favorites.pluck('article_id'))

        if self.request.has('tag'):
            tag = Tag.where('name', self.request.input('tag')).first()
            
            if tag:
                articles.where_in('id', tag.articles.pluck('id'))

        articles = articles.order_by('created_at', 'desc').paginate(
            self.request.input('limit', 20),
            self.request.input('offset', 0)
        )

        list_of_articles = [article.payload(self.request.user()) for article in articles]
        return {'articles': list_of_articles, 'articlesCount': articles.count()}
Exemple #5
0
def stopRent():
	user = User(current_user.get_id())
	if not user.is_authenticated():
		return ''
	sid = request.args.get("id")
	station = Station(sid)
	station.stopRent(user.id)
	return render_template("station.html", station=station, user=user)
    def test_user_can_unfollow(self):
        self.actingAs(User.find(2)).json('DELETE',
                                         '/api/profiles/Joe123/follow')

        self.assertTrue(
            self.actingAs(User.find(2)).json(
                'POST',
                '/api/profiles/Joe123/follow').hasJson('profile.following',
                                                       False))
Exemple #7
0
def brokenBike():
	user = User(current_user.get_id())
	if not user.is_authenticated():
		return ''
	sid = request.args.get("id1")
	bid = request.args.get("id2")
	station = Station(sid)
	station.brokenBike(bid)
	return render_template("station.html", station=station, user=user)
    def test_can_get_article_feed(self):
        self.assertTrue(
            self.actingAs(User.find(1)).json(
                'GET', '/api/articles/feed').hasJson({'articles': []}))

        self.assertTrue(
            self.actingAs(User.find(2)).json('GET',
                                             '/api/articles/feed').hasAmount(
                                                 'articles', 2))
Exemple #9
0
def rentVillo():
	user = User(current_user.get_id())
	if not user.is_authenticated():
		return ''
	sid = request.args.get("id1")
	vid = request.args.get("id2")
	station = Station(sid)
	station.rentVillo(vid,user.id)
	return render_template("station.html", station=station, user=user)
Exemple #10
0
def login():
	if current_user.get_id() in User.users:
		return redirect(url_for("index"))
	form = LoginForm(request.form)
	if (request.method=='POST') and (form.validate()):
		u = User(form.uid.data)
		User.login(u)
		login_user(u,remember=True)
		return redirect(url_for("index"))
	else:
		return render_template("login.html", form=form, user=User(current_user.get_id()), map=Map())
    def update(self, request: Request, validate: Validator, auth: Auth,
               view: View):
        user = User.all()
        customer = request.user()

        email = User.lists('email')
        user_name = User.lists('username')

        #Checks to see if updated email or username already exists
        if request.input('email') != customer.email:
            if request.input('email') in email:
                return request.back().with_errors({
                    'error':
                    ['{} already exists'.format(request.input('email'))]
                })
        elif request.input('username') != customer.username:
            if request.input('username') in user_name:
                return request.back().with_errors({
                    'error':
                    ['{} already exists'.format(request.input('username'))]
                })

        #Inputs to update customer information
        user.where(
            'id',
            customer.id).first().update(firstname=request.input('firstname'))
        user.where(
            'id',
            customer.id).first().update(lastname=request.input('lastname'))
        user.where(
            'id', customer.id).first().update(address=request.input('address'))
        user.where(
            'id',
            customer.id).first().update(cell_phone=request.input('cell_phone'))
        user.where('id',
                   customer.id).first().update(email=request.input('email'))
        user.where(
            'id',
            customer.id).first().update(username=request.input('username'))

        #Checks that all information is filled out properly
        errors = request.validate(
            validate.required(
                ['firstname', 'lastname', 'address', 'email', 'username']),
            validate.email('email'))

        if errors:
            return request.back().with_errors(errors).with_input()
        else:
            request.session.flash(
                'success', 'Your account has been successfully updated.')
            return request.redirect('account')
    def update(self, view: View, request: Request, auth: Auth,
               validate: Validator):
        user = User.all()
        pws = User.lists('password')

        customer = request.user()
        pw = customer.password

        if bcrypt.checkpw(bytes(request.input('password'), 'utf-8'),
                          bytes(pw, 'utf-8')) == False:
            return request.back().with_errors(
                {'error': ['Please enter correct old password']})

        new_password = request.input('new_password')
        confirm_password = request.input('confirm_password')

        for pws in pws:
            if bcrypt.checkpw(bytes(request.input('new_password'), 'utf-8'),
                              bytes(pws, 'utf-8')):
                return request.back().with_errors({
                    'error': [
                        'Password already exists.  Please create a new password.'
                    ]
                })

        errors = request.validate(
            validate.required(['password', 'new_password',
                               'confirm_password']),
            validate.strong('new_password',
                            length=8,
                            special=1,
                            uppercase=1,
                            breach=False)
            # breach=True checks if the password has been breached before.
            # Requires 'pip install pwnedapi'
        )

        if errors:
            return request.back().with_errors(errors).with_input()
        elif new_password != confirm_password:
            return request.back().with_errors({
                'error':
                ['New password and confirm new password do not match!']
            })
        else:
            user.where(
                'id',
                customer.id).first().update(password=password(new_password))
            request.session.flash(
                'success', 'Your password has been successfully updated.')
            return request.redirect('account')
 def setUpFactories(self):
     """This runs when the test class first starts up.
     This does not run before every test case. Use this method to
     set your database up.
     """
     User.create({
         'username': '******',
         'email': '*****@*****.**',
         'password': password('secret')
     })
     User.create({
         'username': '******',
         'email': '*****@*****.**',
         'password': password('secret')
     })
Exemple #14
0
    def reset(self):
        if not request().has('v'):
            raise Exception

        user = User.where('remember_token', request().input('v')).first()
        if user:
            return view('auth/reset')
 def posts_factory(self, faker):
     user_id = random.randint(1, 20)
     return {
         'title':  'Name:' + User.find(user_id).name + '--- id:'+ str(user_id) + '///' + self.faker.sentences(nb=1, ext_word_list=None)[0],
         'posts': self.faker.text(max_nb_chars=200, ext_word_list=None),
         'user_id': user_id
     }
    def test_can_create_article(self):
        self.assertTrue(self.get('/api/articles').hasJson('articlesCount', 1))

        self.actingAs(User.find(1)).json(
            'POST', '/api/articles', {
                "article": {
                    "slug": "how-to-train-your-dragon",
                    "title": "How to train your dragon",
                    "description": "Ever wonder how?",
                    "body": "It takes a Jacobian",
                    "tagList": ["dragons", "training"],
                    "createdAt": "2016-02-18T03:22:56.637Z",
                    "updatedAt": "2016-02-18T03:48:35.824Z",
                    "favorited": False,
                    "favoritesCount": 0,
                    "author": {
                        "username": "******",
                        "bio": "I work at statefarm",
                        "image": "https://i.stack.imgur.com/xHWG8.jpg",
                        "following": False
                    }
                }
            })

        self.assertTrue(Article.all().count())
 def test_can_get_accessor(self):
     user = User.hydrate(
         {"name": "joe", "email": "*****@*****.**", "is_admin": 1}
     )
     self.assertEqual(user.email, "*****@*****.**")
     self.assertEqual(user.name, "Hello, joe")
     self.assertTrue(user.is_admin is True, f"{user.is_admin} is not True")
    def test_can_correct_incorrect_pagination_page(self):
        users = User.all()
        (self.get('/paginator').assertHasJson('count', 10).assertHasJson(
            'per_page',
            10).assertHasJson('current_page',
                              1).assertHasJson('from',
                                               1).assertHasJson('to', 10))

        (self.get('/paginate', {
            'page': 'hey',
            'page_size': 'hey'
        }).assertHasJson('total', len(users)).assertHasJson(
            'count', 10).assertHasJson('per_page', 10).assertHasJson(
                'current_page', 1).assertHasJson('from',
                                                 1).assertHasJson('to', 10))

        (self.get('/length_aware', {
            'page': 'hey',
            'page_size': 'hey'
        })
         # .assertHasJson('total', len(User.find(1)))
         # .assertHasJson('count', len(User.find(1)))
         .assertHasJson('per_page',
                        10).assertHasJson('current_page', 1).assertHasJson(
                            'from', 1).assertHasJson('to', 10))

        (self.get('/single_paginator', {
            'page': 'hey',
            'page_size': 'hey'
        }).assertHasJson('count',
                         1).assertHasJson('per_page', 10).assertHasJson(
                             'current_page',
                             1).assertHasJson('from',
                                              1).assertHasJson('to', 10))
Exemple #19
0
 def mount(self):
     self.loggedIn = False
     self.username = ''
     self.password = ''
     self.loggedInMessage = ''
     self.failed = False
     self.users = User.all().serialize()
    def send(self, view: View, request: Request, auth: Auth,
             validate: Validator, mail: Mail):
        email_list = User.lists('email')
        email = request.input('email')
        encoded_jwt = jwt.encode(
            {
                'email': email,
                'httpMethod': 'GET'
            },
            'secret',
            algorithm='HS256',
        ).decode('utf-8')

        errors = request.validate(validate.required('email'),
                                  validate.email('email'))

        if errors:
            return request.back().with_errors(errors)

        if email not in email_list:
            return request.back().with_errors({
                'error':
                ['We can not find your email.  Please enter correct email']
            })

        else:
            message = 'Please visit {}/password/reset/get/{} to reset your password'.format(
                env('APP_URL', 'http://localhost:8000'), encoded_jwt)
            mail.subject('Reset Password Instructions').to(email).send(message)
            request.session.flash(
                'success',
                'An email has been sent. Please follow the instructions in the email to reset your password.'
            )
            return request.redirect('login'), email
Exemple #21
0
 def test_can_use_global_scopes_on_delete(self):
     sql = "UPDATE `users` SET `users`.`deleted_at` = 'now' WHERE `users`.`name` = 'joe'"
     self.assertEqual(
         sql,
         User.apply_scope(SoftDeletes).where(
             "name", "joe").delete(query=True).to_sql(),
     )
    def store(self, request: Request, view: View):
        """
        Generate a new token, return to chess/@token/ @show
        """
        cur_user = request.user()

        friend = request.input('friend', clean=True).strip()
        friend_email = User.where('email', friend).limit(1).first()

        if not friend_email:
            return view.render("invalid",
                               {"message": 'Username is not exists'})

        friend_email = friend_email.email
        user_email = cur_user.email

        if friend_email == user_email:
            return view.render("invalid", {"message": 'You cannot play alone'})

        token = token_hex(16)

        Table.create(
            owner=user_email,
            user_id=user_email,
            oppo_id=friend_email,
            token=token,
            completed=False,
            last_move_timestamp=current_time(),
            next_id=user_email,
            move='',
        )
        return request.redirect("/play/@token", {'token': token})
Exemple #23
0
    def data_get_contacts(self, request: Request, view: View, auth: Auth):
        user_id = auth.user().id
        user = json.loads(User.find(user_id).to_json())
        nylasController = NylasController()
        data = nylasController.getContacts(user['access_token'])

        return data
    def getCalendarAccounts(self, request:Request, auth:Auth):
        authed_id = auth.user().id
        user = User.find(authed_id)
        email_accounts = Account.where('user_id', user.id).where('type', 'connect_calendar').get()
        if email_accounts != None:
            return email_accounts

        return []
Exemple #25
0
 def login(self, request: Request):
     user_data = request.input('user')
     print(user_data)
     if Auth(request).once().login(user_data['email'],
                                   user_data['password']):
         user = User.where('email', user_data['email']).first()
         user.generate_token()
         return {'user': user.serialize()}
Exemple #26
0
    def get_inbox_messages(self, request:Request, auth:Auth):
        user_id = auth.user().id
        user = json.loads(User.find(user_id).to_json())

        nylasController = NylasController()
        messages = nylasController.getMessagesFromInbox(user['access_token'])

        return messages
Exemple #27
0
    def data_get_thread(self, request: Request, view: View, auth: Auth):
        user_id = auth.user().id
        user = json.loads(User.find(user_id).to_json())
        message_id = request.param('message_id')
        nylasController = NylasController()
        data = nylasController.getMessagesForThread(user['access_token'], message_id)

        return data
Exemple #28
0
 def login(self, request: Request, auth: Auth):
     email = request.input('user.email')
     password = request.input('user.password')
     if auth.once().login(email, password):
         user = User.where('email', email).first()
         user.generate_token()
         return {'user': user.serialize()}
     request.status(400)
     return {'error': 'username or password incorrect'}
    def getPersonaldetails(self,request:Request, auth:Auth):
        authed_id = auth.user().id
        user = json.loads(User.find(authed_id).to_json())
        if user['open_hours'] is None or user['open_hours'] == '':
            user['open_hours'] = {}
        else:
            user['open_hours'] = json.loads(user['open_hours'])

        return user
Exemple #30
0
 def check_old_encryption(self, request):
     user = User.where('email', request.input('username')).where(
         'password',
         hashlib.sha1(request.input('password').encode(
             'utf-8')).hexdigest()).first()
     if user:
         # login successful
         user.password = bcrypt_password(request.input('password'))
         user.save()
Exemple #31
0
    def revoke_edit_permissions(self, request: Request, response: Response):
        subject = User.where("gov_id", request.input("gov_id")).first()
        grantor = User.where("gov_id", request.param("user")).first()

        if subject is None:
            return response.json({"error": "No such user"})
        blockchain_status = self.ibc.revoke_edit_permissions(subject)
        iroha_message = iroha_messages.revoke_set_account_detail_perms_failed(
            blockchain_status)
        if iroha_message is not None:
            return response.json(iroha_message)

        (Consent.where("requestor_id", f"{subject.gov_id}@afyamkononi").where(
            "grantor_id",
            f"{grantor.gov_id}@afyamkononi").update(status="revoked"))

        return response.json(
            {"success": "The requested permissions were revoked"})
Exemple #32
0
        def test_serialize_with_appends(self):
            user = User.hydrate({"name": "Joe", "id": 1})

            user.set_appends(["meta"])

            serialized = user.serialize()
            self.assertEqual(serialized["id"], 1)
            self.assertEqual(serialized["name"], "Joe")
            self.assertEqual(serialized["meta"]["is_subscribed"], True)
    def test_view_should_return_a_json_response_when_returning_paginator_instance(
            self):

        users = User.all()
        (self.get('/paginator').assertHasJson('count', 10).assertHasJson(
            'per_page',
            10).assertHasJson('current_page',
                              1).assertHasJson('from',
                                               1).assertHasJson('to', 10))
Exemple #34
0
    def data_get_message_clean(self, request: Request, view: View, auth: Auth):
        user_id = auth.user().id
        user = json.loads(User.find(user_id).to_json())
        message_id = request.param('message_id')
        nylasController = NylasController()
        data = nylasController.getCleanMessage(user['access_token'], [message_id])
        pprint(data)

        return data