Пример #1
0
def user(username):
    u = User()
    user = u.get_user(username=username)

    title = request.form.get('new-title')
    body = request.form.get('new-body')

    if title and body:
        p = Post(title=title, body=body, user_id=user.id)
        p.add_post()

    posts = u.get_posts_by_user(user.id)

    if not posts:
        posts = [
            Post(id=2,
                 title="There's nothing here yet!",
                 body="There's nothing here yet!",
                 user_id=-1)
        ]

    if user:
        return render_template('user_page.html',
                               username=user.username,
                               posts=posts)

    return "user not found"  # TODO change the custom 404
Пример #2
0
    def post(self):
        """Handle POST request at /auth/register."""

        post_data = request.json
        email = post_data.get('email')
        password = post_data.get('password')
        # Query to see if the user already exists
        user = User.query.filter_by(email=email).first()

        if not user:
            # There is no user so we'll try to register them
            try:
                user = User(email=email, password=password)
                user.save()

                response = {
                    'message': 'You registered successfully. Please log in.'
                }
                return response, 201

            except Exception as e:
                response = {'message': str(e)}
                return response, 401
        else:
            # There is an existing user.
            response = {'message': 'User already exists. Please login.'}
            return response, 409
Пример #3
0
def test_delete_another_user_with_no_admin_user(testapp, db_handle):
    user_to_delete = User(email='*****@*****.**',
                          display_name='Se Borra',
                          phone_number='11111111111',
                          image_location='http://www.youtube.com',
                          admin=False)

    user = User(email='*****@*****.**',
                display_name='User',
                phone_number='2454564652',
                image_location='http://www.youtube.com',
                admin=False)

    db_handle.session.add(user_to_delete)
    db_handle.session.add(user)
    db_handle.session.commit()

    auth_service.setData({
        'email': user.email,
        'uid': '4cNAU9ovw6eD0KH5Qq7S91CXIZx2'
    })

    response = testapp.delete(f"/users/{user_to_delete.id}",
                              headers={'x-access-token': token})
    json_data = response.get_json()

    assert json_data['message'] == 'Only admins can delete other users.'
    assert response.status_code == 401
Пример #4
0
 def post(self):
     self.parser.add_argument('username',
                              type=str,
                              help='This username cannot be blank',
                              required=True)
     self.parser.add_argument('password',
                              type=str,
                              help='This password cannot be blank',
                              required=True)
     data = self.parser.parse_args(
         strict=True)  # 获取传输的值/strict=True代表设置如果传以上未指定的参数主动报错
     if User.query.filter_by(username=data['username']).filter_by(
             flag=1).first():
         return {
             'msg': 'user {} already exists'.format(data['username'])
         }, 400
     new_user = User(username=data['username'],
                     password=User.hash_password(data['password']))
     session_add(new_user)
     msg = session_commit()
     if msg:
         return {
             "errors":
             f"{msg}",
             'msg':
             "user add failed at {0}".format(
                 time.strftime("%Y-%m-%d %H:%M:%S"))
         }, 500
     else:
         return {
             "msg":
             "user add successfully at {0}".format(
                 time.strftime("%Y-%m-%d %H:%M:%S"))
         }
Пример #5
0
Файл: main.py Проект: sup/fill
def signup():
    if request.method == 'GET':
        # Display the Signup form
        return render_template('signup.html')
    else:
        # Signup the User
        name = request.form["name"]
        username = request.form["username"]
        email = request.form["email"]
        password = request.form["password"]

        # TODO: Verify user data
        available = User.is_username_available(username)
        if not available:
            return render_template('signup.html', error="User already exists!")
        else:
            # Add the user
            hashed_pw = make_pw_hash(str(username), str(password))
            user = User(name=name, 
                        username=username, 
                        email=email, 
                        password_hash=hashed_pw)
            user.put()
            response = make_response(redirect(url_for('home')))
            response.set_cookie("username", username)
            return response
Пример #6
0
    def generate(self):

        username = self.StringReq('User')

        try:
            user = User.get(User.username == username)
        except:
            user = User.get()

        self.headers.append(('DateTime', getDate() + ' ' + getTime()))
        self.headers.append(('UserName', user.fullname()))

        list = user.salelist
        list = [d for d in list]

        users = User.select()
        for user in users:
            self.Echo('<User>')
            self.EchoTag('Id', user.username)
            self.EchoTag('UserName', user.fullname())
            self.Echo('</User>')

        pages = split(list, _max_rows_)
        for list in pages:
            self.Echo('<Page>')
            for row in list:
                self.Echo('<Row>')
                self.EchoTag('Id', row.id)
                self.EchoTag('Time', row.time)
                self.EchoTag('Customer', row.customer.name)
                self.EchoTag('FullSale', row.fullsale)
                self.EchoTag('Prepaid', row.advance)
                self.EchoTag('Remain', row.remind())
                self.Echo('</Row>')
            self.Echo('</Page>')
Пример #7
0
 def run(self, dispatcher, tracker, domain):
     user = User(0)
     found_user = user.find()[0]
     recent_friends = user.find_most_recent_friend()
     friends_same_city = user.suggest_friends_by_location(found_user['location'])
     dispatcher.utter_message("Family action!")
     return []
Пример #8
0
def register_google():
    token = request.json["id_token"]
    try:
        id_info = id_token.verify_oauth2_token(token, requests.Request(),
                                               GOOGLE_CLIENT_ID)
        if id_info['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise ValueError('Wrong issuer.')
        user_id = id_info['sub']
        user = db.get_user(user_id)
        if user:
            logging.info("User ${user_name} with ID ${id} is logged in".format(
                user_name=user['name'], id=user['user_id']))
            return json.dumps(user), 200
        else:
            new_user = User(id_info['sub'], id_info['email'], id_info['name'])
            db.save_user(new_user)
            logging.info(
                "User ${user_name} with ID ${id} is being registered".format(
                    user_name=new_user.name, id=new_user.user_id))
            return json.dumps(new_user.serialize()), 201
    except ValueError:
        # Invalid token
        pass
Пример #9
0
def userModule(user: User):
    c = selectOptionInList("Escoge el numero de una de las opciones",
                           options=secondCriteria)
    if c == 0:
        secondaryModule(user.productsPurchasedByRating())
    elif c == 1:
        secondaryModule(user.productsPurchasedByQuantity())
Пример #10
0
        def arguments_wrapper(*args, **kwargs):
            try:
                changed = False
                user = User.get(telegram_user_id=args[0].from_user.id)
                if not user.has_messages_after_notification:
                    user.has_messages_after_notification = True
                    changed = True
                if user.username != args[0].from_user.username:
                    user.username = args[0].from_user.username
                    changed = True
                if user.first_name != args[0].from_user.first_name:
                    user.first_name = args[0].from_user.first_name
                    changed = True
                if user.surname != args[0].from_user.last_name:
                    user.surname = args[0].from_user.last_name
                    changed = True
                if changed:
                    user.save()
            except Exception as e:
                user = User.create(
                    username=args[0].from_user.username,
                    telegram_chat_id=args[0].chat.id,
                    first_name=args[0].from_user.first_name,
                    surname=args[0].from_user.last_name,
                    # phone=args[0].contact.phone_number,
                    telegram_user_id=args[0].from_user.id)

            obj = tele_func(*args, **kwargs, user=user)
            return obj
Пример #11
0
    async def post(self):
        result = {'success': False, 'reason': None, 'data': None}
        req_json = json.loads(self.request.body)
        username = req_json['user_name']
        email = req_json['email']
        password = req_json['password']
        phone = req_json['phone']
        occupation = req_json['occupation']
        address = req_json['address']

        same_name_user = User.objects(username=username).first()
        if same_name_user is not None:
            result['reason'] = 'Username %s has already been existed' % (
                username, )
            self.write(json.dumps(result))
            self.finish()

        same_email_user = User.objects(email=email).first()
        if same_email_user is not None:
            result['reason'] = 'Email addr %s has already been registered' % (
                email, )
            self.write(json.dumps(result))
            self.finish()

        password = self._md5(password)
        _ = await User.create(username=username,
                              email=email,
                              password=password,
                              phone=phone,
                              occupation=occupation,
                              address=address)
        result['success'] = True
        self.write(json.dumps(result))
        self.finish()
Пример #12
0
def test_delete_user_as_admin(testapp, db_handle):
    user_to_delete = User(email='*****@*****.**',
                          display_name='Se Borra',
                          phone_number='11111111111',
                          image_location='http://www.youtube.com',
                          admin=False)

    user_admin = User(email='*****@*****.**',
                      display_name='Admin',
                      phone_number='25642346456',
                      image_location='http://www.youtube.com',
                      admin=True)

    db_handle.session.add(user_to_delete)
    db_handle.session.add(user_admin)
    db_handle.session.commit()

    auth_service.setData({
        'email': user_admin.email,
        'uid': '4cNAU9ovw6eD0KH5Qq7S91CXIZx2'
    })

    response = testapp.delete(f"/users/{user_to_delete.id}",
                              headers={'x-access-token': token})
    json_data = response.get_json()

    db.session.delete(user_admin)
    db_handle.session.commit()

    assert json_data['message'] == 'User deleted.'
    assert response.status_code == 200
Пример #13
0
def test_get_users_data_filtered_by_display_name(testapp, db_handle):
    """Should return users data filtered by display name 
    (users which names contains indicated display name)"""

    user_a = User(email='*****@*****.**',
                  display_name='Armando Estaban Quito',
                  phone_number='11533223536',
                  image_location='http://www.google.com.ar',
                  admin=False)
    user_b = User(email='*****@*****.**',
                  display_name='Martin Armando Quito',
                  phone_number='12121555530',
                  image_location='http://www.facebook.com',
                  admin=False)
    user_c = User(email='*****@*****.**',
                  display_name='Carlos Gutierrez',
                  phone_number='1125553512',
                  image_location='http://www.youtube.com',
                  admin=False)
    db_handle.session.add(user_a)
    db_handle.session.add(user_b)
    db_handle.session.add(user_c)
    db_handle.session.commit()

    response = testapp.get('/users?name=Armando',
                           headers={'x-access-token': token})
    json_data = response.get_json()

    assert len(json_data['users']) == 2

    for user in json_data['users']:
        assert ('Armando' in user['display_name'])

    assert response.status_code == 200
Пример #14
0
def add_user():
    data = request.get_json() or {}
    if 'username' not in data:
        return bad_request('错误的参数')
    user = User(username=data['username'])
    db.session.add(user)
    db.session.commit()
    return jsonify(user.to_dict())
Пример #15
0
def test_create_user(db):
    user = User.create("test", "password")
    assert user.name == "test"
    assert User.exists("test")

    with pytest.raises(User.UserExistsError) as excinfo:
        user = User.create("test", "password")
        assert "test" in str(excinfo)
Пример #16
0
 def run(self, dispatcher, tracker, domain):
     user_id = 0
     user = User(user_id)
     found_user = user.find()[0]
     #dispatcher.utter_message("Greetings, %s!" % (name))
     return [
         SlotSet(
             "username",
             found_user['name'] if found_user['name'] is not None else [])
     ]
Пример #17
0
def register_function():
    post_data = json.loads(request.data)
    username = post_data["username"]
    email = post_data["email"]
    password = post_data["password"]

    if not userutils.check_mail(email):
        return json.dumps(
            {
                "status": "error",
                "result": "please check your email"
            }
        )

    if len(str(password)) < 4:
        return json.dumps(
            {
                "status": "error",
                "result": "please get some serious password"
            }
        )

    user = User.objects(username=username).first()
    if user:
        return json.dumps(
            {
                "status": "error",
                "result": "this username already taken, sorry"
            }
        )

    if not username:
        return json.dumps(
            {
                "status": "error",
                "result": "please provide a username, it's required'"
            }
        )

    user = User.objects(email=email).first()
    if user:
        return json.dumps(
            {
                "status": "error",
                "result": "this email address already registered, sorry"
            }
        )

    user = User(username=username, email=email)
    user.password = userutils.encrypt(password)
    user.slug = userutils.make_slug(username)
    user.register_date = datetime.now()
    user.save()
    login_user(user)
    return json.dumps(
        {
            "status": "success",
            "result": "registeration successful"
        }
    )
Пример #18
0
def reg():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        password = request.form.get('password')
        u = User(name=name, email=email)
        u.set_password(password)
        db.session.add(u)
        db.session.commit()
        return redirect(url_for('homePage.index'))
    return render_template('registration.html')
Пример #19
0
def init_user_db(user_info):
    try:
        user = User(chat_id=user_info.id,
                    username=user_info.username,
                    name=user_info.first_name)
        user.connected_date = datetime.today()
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        raise Exception("'init_user_db' error with '{}'".format(e))
    return user
Пример #20
0
    def done(self):
        # make sure the user doesn't already exist
        u = User.by_name(self.username)
        if u:
            msg = 'That user already exists.'
            self.render('signup-form.html', error_username=msg)
        else:
            u = User.register(self.username, self.password, self.email)
            u.put()

            self.login(u)
            self.redirect('/blog/welcome')
Пример #21
0
    def done(self):
        # make sure the user doesn't already exist
        u = User.by_name(self.username)
        if u:
            msg = 'Name taken!'
            self.render('signup-form.html', error_username=msg)
        else:
            u = User.register(self.username, self.password, self.email)
            u.put()

            self.login(u)
            self.redirect('/backbone-test')
Пример #22
0
def index():
    myForm = LoginForm()
    if myForm.validate_on_submit():
        if session['recaptcha'].lower() == myForm.recaptcha.data.lower():
            user = User(myForm.username.data, myForm.password.data)
            session['username'] = myForm.username.data
            if (user.isExisted()):
                return redirect(url_for('home'))
            else:
                flash(u'出错啦,登录失败,请检查用户名和密码是否正确!')
        else:
            flash(u'Hi, 验证码错误, 请重输!')
    return render_template('index.html', form=myForm)
Пример #23
0
    def Process(self, section):

        if section == 'instulments':
            today = datetime.today()
            enddate = today + timedelta(days=7)
            insts = SaleInstallment.select() \
                .where((SaleInstallment.dateback.is_null(True)) & (SaleInstallment.date < enddate))
            i = 1
            for inst in insts:
                inst.index = i
                i += 1
            self.RenderFile('dashboard/instulments.htm', {
                'insts': insts,
                '_': config.i18n,
                'today': today
            })

        elif section == 'charts':
            users = User.select()
            storages = Storage.select()

            order = Order()
            inst = SaleInstallment()
            sale = Sale()

            self.RenderFile(
                'dashboard/charts.htm', {
                    'users': users,
                    'storages': storages,
                    'order': order,
                    'inst': inst,
                    'sale': sale,
                    '_': config.i18n
                })
        else:
            users = User.select()
            storages = Storage.select()

            order = Order()
            inst = SaleInstallment()
            sale = Sale()

            self.RenderFile(
                'dashboard/home.htm', {
                    'users': users,
                    'storages': storages,
                    'order': order,
                    'inst': inst,
                    'sale': sale,
                    '_': config.i18n
                })
Пример #24
0
 def post(self):
     username = request.json.get('username', None)
     password = request.json.get('password', None)
     code = request.json.get('code', None)
     mail = request.json.get('mail', None)
     if username is None or password is None or code is None or mail is None or not re.match(
             r'[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+', mail):
         return jsonify(code=ResponseCode.FORMAT_ERROR, msg="用户名密码格式错误")
     cache_email = cache.get(code)
     if cache_email != mail:
         return ResponseClass.warn(ResponseCode.FORMAT_ERROR)
     else:
         cache.delete(code)
         cache.delete(mail)
     session = AppUtils.get_session()
     try:
         # 验证用户名
         AppUtils.validate_username(username)
         from models.models import User
         user = User()
         user.username = username
         user.mail = mail
         user.hash_password(password)
         user.credits = 0
         session.add(user)
         session.commit()
         # 数据库
         from app_config import SQLSession
         return jsonify(code=0, data=user.get_self_data())
     except Exception as e:
         return jsonify(code=-1, msg=e.args[0])
     finally:
         session.close()
Пример #25
0
Файл: main.py Проект: sup/fill
def check_requests(id=None):
    # Check ID
    if id is None:
        return redirect(url_for('admin'))

    # Get user
    username = request.cookies.get('username')
    user = User.get_user(username)
    if not user:
        return redirect(url_for('home'))

    # Get Event
    event = Event.get_event_by_id(id)

    # Handle Render Form Template
    if request.method == 'GET' and event.admin.id() == user.key.id():
        # Check for GET Parameters
        user_id = request.args.get("user")
        if not user_id:
            return render_template('check_requests.html', event=event)
        user = User.get_user_by_id(user_id)
        volunteer = request.args.get("volunteer")
        driver = request.args.get("driver")
        translator = request.args.get("translator")
        accept = int(request.args.get("accept"))
        # Accept the User
        if accept:
            if volunteer:
                event.volunteer_requests = [x for x in event.volunteer_requests if x != user.key]
                event.volunteers.append(user.key)
            if driver:
                event.driver_requests = [x for x in event.driver_requests if x != user.key]
                event.drivers.append(user.key)
            if translator:
                event.translator_requests = [x for x in event.translator_requests if x != user.key]
                event.translators.append(user.key)
            event.put()
            return render_template('check_requests.html', event=event, success="User successfully accepted!")
        # Reject the User
        else:
            if volunteer:
                event.volunteer_requests = [x for x in event.volunteer_requests if x != user.key]
            if driver:
                event.driver_requests = [x for x in event.driver_requests if x != user.key]
            if translator:
                event.translator_requests = [x for x in event.translator_requests if x != user.key]
            event.put()
            return render_template('check_requests.html', event=event, success="User successfully rejected.")
    else:
        return redirect(url_for('admin'))
Пример #26
0
def add_users(course_id):
    ''' Generate a form to add a student '''
    add_form = AddStudentForm(request.form)
    if request.method == 'POST':
        for new_email in add_form.new_users.data.split("\n"):
            new_user = User.find_student(email=new_email)
            if new_user is None:
                new_user = User.new_from_instructor(email=new_email)
            if not new_user.is_student():
                new_user.add_role('learner', course_id=course_id)
            # TODO: Send an email
        flash('New students added')
        return redirect(url_for('courses.manage_users', course_id=course_id))
    return render_template('courses/add_users.html', add_form=add_form, course_id=course_id)
Пример #27
0
def seed_users():
    user1 = User('joe', 'shmoe', '*****@*****.**', '123-123-4321', 'password')
    user2 = User('jane', 'shmoe', '*****@*****.**', '123-123-4321', 'password')
    user3 = User('foo', 'bar', '*****@*****.**', '123-123-4321', 'password')
    user4 = User('chuck', 'norris', '*****@*****.**', '123-123-4321', 'password')
    user5 = User('donald', 'duck', '*****@*****.**', '123-123-4321', 'password')

    db_session.add(user1)
    db_session.add(user2)
    db_session.add(user3)
    db_session.add(user4)
    db_session.add(user5)

    db_session.commit()
Пример #28
0
 def save_user(cls, user_name, password):
     try:
         user = User(_id=str(uuid4()),
                     username=user_name,
                     password=password,
                     created=datetime.now(),
                     updated=datetime.now())
         db.session.add(user)
         db.session.commit()
         logging.info(user)
         logging.info(user.__repr__())
         return True, 'dfdf'
     except Exception as e:
         logging.info(format_exc())
         return False, ''
Пример #29
0
    def testCRUD(self):
        # Insert user
        user1 = User(name='user1', fullname='USER1', password='******')
        self.session.add(user1)
        self.session.commit()

        # Check if inserted
        user = self.session.query(User).filter_by(name='user1').first()
        self.assertEquals(user.name, user1.name)

        # Check for non insertion
        user = self.session.query(User).filter_by(name='userFake').first()
        self.assertTrue(user is None)

        # Check Update
        user = self.session.query(User).filter_by(name='user1').first()
        user.password = '******'
        self.session.commit()
        userTst = self.session.query(User).filter_by(name='user1').first()
        self.assertEquals(userTst.password, 'pwdChg')

        # Check printout (to see this you have to run nosetest --nocapture
        user = self.session.query(User).filter_by(name='user1').first()
        print('User = %s' % user)

        # Insert a second record and check insertion
        user2 = User(name='user2', fullname='USER2', password='******')
        self.session.add(user2)
        self.session.commit()
        user = self.session.query(User).filter_by(name='user2').first()
        self.assertEquals(user.name, user2.name)

        # Rollback test
        user3 = User(name='user3', fullname='USER3', password='******')
        self.session.add(user3)
        self.session.rollback()
        user = self.session.query(User).filter_by(name='user3').first()
        self.assertTrue(user is None)

        # Delete record
        user = self.session.query(User).filter_by(name='user2').first()
        self.session.delete(user)
        self.session.commit()
        self.assertTrue(
            self.session.query(User).filter_by(name='user2').count() == 0)

        # Json format of Data (not working)
        user = self.session.query(User).filter_by(name='user1').first()
Пример #30
0
def login():
    user_info = Sso.user_info_by_token()
    if Sso.valid_user_info(user_info):
        """
        通过sso鉴权该用户是否合法
        """
        user_id = user_info.get("user_id")
        user = user_info.get("fullname")
        email = user_info.get("email")
        name = email[:-10]
        role_id = 1
        current_user = User(user_id=user_id, name=name, email=email, role_id=role_id)
        session["user_id"] = user_id
        session["username"] = user
        session["role"] = get_user_role()

        if not user_id_exists(user_id):
            """
            通过userid判断用户是否存在
            """
            try:
                db.session.add(current_user)
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                print(e)
                raise
            finally:
                db.session.close()

        return redirect(url_for('noclist'))
    return redirect(app.config['SSO_URL'] + app.config.get('LOGIN_RETURN_URL') + app.config.get('NOC_URL'))