示例#1
0
    def test_db_object(self):
        '''
		Makes sure that __eq__ method overide works
		'''
        user1 = User()
        user2 = User()
        self.assertEqual(user1, user2)
示例#2
0
def api_login():
    id = request.values.get('id') if "id" in request.form else None
    pw = request.values.get('pw') if "pw" in request.form else None
    logger.info("id : "+id)

    cursor = db.get_conn().cursor()    # cursor 객체를 얻는다.
    cursor.callproc('get_user_by_id', (id,))    #argument 1개일 때도 ,하나 붙여줘야 제대로 인식함.
    r = cursor.fetchall()
    cursor.close()
    logger.info( "login user info : " + str(r))
    if r:
        #id 존재
        logger.info("pw 체크) DB에 있는 hashedpw: %s, 입력한pw:%s,  check_password_hash():%s" % (r[0][4], pw, check_password_hash(str(r[0][4]), pw)))
        #if r[0][4] == pw:
        if check_password_hash(r[0][4], pw):

            # 아이디와 비밀번호가 일치하면 로그인 처리
            # 직접 정의한 'User'클래스의 객체를 인자로 넘겨준다.
            login_user(User(id, name=r[0][2], auth=True))

            flash("로그인 되었습니다.")
            return redirect(url_for('main_view.index'))
        else:
            flash("아이디 또는 비밀번호를 확인하세요.")
            return redirect(url_for('auth_view.login'))
    else:
        flash("아이디 또는 비밀번호를 확인하세요.")
        return redirect(url_for('auth_view.login'))
示例#3
0
 def get(self):  #assumes: id doesn't change for user
     id = str(request.headers.get('Authorization'))
     users = read_parquet("/app/users.parquet")
     if id not in users.id.values:
         newuser = {
             "id": id,
             "recipes_viewed": empty(0),
             "recipes_made": empty(0),
             "recipes_liked": empty(0),
             "ingredients_owned": empty(0),
             "weights": empty(0)
         }
         #add user to data
         users = users.append(newuser, ignore_index=True)
         users.to_parquet("/app/users.parquet")
     #recommend something
     u = users.query("id == @id")
     user = User(id, u["recipes_viewed"].to_list(),
                 u["recipes_made"].to_list(), u["recipes_liked"].to_list(),
                 u["ingredients_owned"].to_list(), u["weights"].to_list())
     recipes = read_parquet("/app/recipes.parquet")
     results = get_recommendations(user, recipes, 30)
     formatted_results = [{
         **lookup.query("id == @i").to_dict('records')[0], 'confidence':
         float(confidence)
     } for i, confidence in results]
     return jsonify(formatted_results)
示例#4
0
文件: init_db.py 项目: rcosm/PS-2020
def init_db():
    db.create_tables()

    session = db.create_session()
    with open('db_data.json') as f:
        data = json.load(f)
        for user in data['user']:
            u = User(username=user['username'], password=user['password'], name=user['name'])
            session.add(u)
        for tag in data['tag']:
            t = Tag(name=tag['name'])
            session.add(t)
        for product in data['product']:
            p = Product(name=product['name'])
            session.add(p)
    session.commit()

    i = Issue(description="Updater doesn't work on linux", reporter_id=1, product_id=1)
    session = db.create_session()
    session.add(i)
    session.commit()

    s = Screenshot(issue_id=1, path_to_screenshot=r'db_diagram.png')
    session = db.create_session()
    session.add(s)
    session.commit()

    c = Comment(issue_id=1, user_id=2, message="Are you sure? I ran it last week on a CentOS and it seemed to be working just fine")
    session = db.create_session()
    session.add(c)
    session.commit()
示例#5
0
def loadUser(data, image):
    """Loads a user for the current session.

    Attempts to retrieve a user based on his email address.
    If a record cannot be found, create a new user with the data that is
    returned from the oAuth provider.
    If a user name cannot be found, the user is assigned a default user name
    consisting of the word user and a date & time string.

    Args:
        data    : a list of user values returned by the oAuth provider.
        image   : an image url for the current user.

    Return:
        A User object.
    """

    user = getOne(User, 'email', data['email'])
    if not user:
        if data['name'] == '':
            data['name'] = 'User %s' % datetime.datetime.now()

        user = User(email=data['email'], name=data['name'], image=image)
        User.save(user)
    return user
示例#6
0
def make_user(login, nickname):
    try:
        return User.objects(test_login=login).get()
    except User.DoesNotExist:
        u = User(test_login=login, nickname=nickname)
        u.save()
        return u
示例#7
0
def callback():
    # Get authorization code Google sent back to you
    code = request.args.get("code")

    # Find out what URL to hit to get tokens that allow you to ask for
    # things on behalf of a user
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send a request to get tokens! Yay tokens!
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code)
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )

    # Parse the tokens!
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Now that you have tokens (yay) let's find and hit the URL
    # from Google that gives you the user's profile information,
    # including their Google profile image and email
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    # You want to make sure their email is verified.
    # The user authenticated with Google, authorized your
    # app, and now you've verified their email through Google!
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return "User email not available or not verified by Google.", 400

    # Create a user in your db with the information provided
    # by Google
    user = User(id_=unique_id,
                name=users_name,
                email=users_email,
                profile_pic=picture,
                address="")

    # Doesn't exist? Add it to the database.
    if not User.get(unique_id):
        User.create(unique_id, users_name, users_email, picture, "")

    # Begin user session by logging the user in
    login_user(user)

    # Send user back to homepage
    return redirect("/dashboard/users/" + unique_id)
示例#8
0
def login(conn, info, repo):
    username, password = info.split(" ")
    user = User(username, password)

    # 构造响应
    resp_dict = {
        "command": 5,
        "from": "server",
        "to": username
    }
    resp_info = json.dumps(resp_dict)

    try:
        repo.login(user)
        conn_list.append(conn)
        if username in user_dict.values():
            raise ValueError("该用户已登陆")
        user_dict[conn] = username
        resp_content = "success"
        put_block(conn, resp_content, resp_info)
        return True
    except ValueError as e:
        (resp_content, ) = e.args
        put_block(conn, resp_content, resp_info)
        return False
示例#9
0
def create_user():
    data = request.values
    if data is None or len(data) == 0:
        data = request.get_json(force=True)

    email = data.get('email').lower()
    if email == "":
        email = None
    phone_number = data.get('phone')
    if phone_number == "":
        phone_number = None

    name = data.get('firstname')
    surname = data.get('lastname')
    password = data.get('password')

    if (email is None or email == "") and (phone_number is None
                                           or phone_number == ""):
        return jsonify(status='fail', message='Email or phone number required')

    if len(email) > 200:
        return jsonify(
            stauts='fail',
            message='Email is too long (please use less than 200 characters)')

    if name is None or name == "":
        return jsonify(status='fail', message='Name cannot be blank')

    if password is None:
        return jsonify(status='fail', message='Password cannot be blank')

    if len(name) > 50:
        return jsonify(status='fail',
                       message='Name cannot be longer than 50 characters')

    session = get_db_session()
    user = session.query(User).filter_by(email=email).first()

    if user is not None:
        return jsonify(status='fail', message='User already exists')

    user = session.query(User).filter_by(phone_number=phone_number).first()

    if user is not None:
        return jsonify(status='fail', message='User already exists')

    user = User(name, surname, phone_number, email)
    # def __init__(self, first_name, last_name, phone_number=None, email=None, password=None, salt=None):
    user.status = 'user'
    user.confirmed = 1

    user.salt = bcrypt.gensalt().decode()
    user.password = bcrypt.hashpw(password.encode(),
                                  user.salt.encode()).decode()

    session.add(user)
    session.commit()

    return jsonify(status='ok')
示例#10
0
def check_mail(request):
    user_db = User()
    mail = request.params['mail']
    user = user_db.get_user_by_mail(mail)
    if user:
        return {'status': 'nok'}
    else:
        return {'status': 'ok'}
示例#11
0
def check_user(request):
    user_db = User()
    name = request.params['name']
    user = user_db.get_user_by_name(name)
    if user:
        return {'status': 'nok'}
    else:
        return {'status': 'ok'}
示例#12
0
 def test_delete_user(self):
     u = User(name='Jeff Bridges',
              email='*****@*****.**',
              status='inactive')
     _id = u.save()
     self.assertIsNotNone(_id, 'User id')
     u.delete()
     u = User.get(id=_id)
     self.assertIsNone(u, "Delete user")
示例#13
0
 def test_user_create(self):
     user = User()
     result = User.create(username='******',
                          password='******',
                          description='Hi my name is James',
                          location='Sydney',
                          birthdate='DD/MM/YYYY',
                          image='/file/img.png')
     self.assertEqual(user, result)
示例#14
0
 def test_create_user(self):
     u = User(name='Gary Busey', email='*****@*****.**', status='active')
     _id = u.save()
     self.assertIsNotNone(_id, 'User id')
     u = User.get(id=_id)
     self.assertEqual(u.name, 'Gary Busey', 'User name')
     self.assertEqual(u.email, '*****@*****.**', 'User email')
     self.assertEqual(u.status, 'active', 'User status')
     u.delete()
示例#15
0
def login_action():
    email = request.values["email"] if "email" in request.form else ""
    pw = request.values["pwd"] if "pwd" in request.form else ""
    notice_no = request.values[
        "notice_no"] if "notice_no" in request.values else ''
    rmb = request.values["rmb"] if "rmb" in request.form else ""

    print "rmb:" + str(rmb)

    cursor = dao.get_conn().cursor()
    cursor.execute("select * from recruit_user where user_email like '%s'" %
                   (email))
    result = cursor.fetchone()
    cursor.close()

    logger.info("login_action, check email : " + str(result))

    try:
        if result:
            if check_password_hash(result[3], pw):
                login_user(
                    User(email,
                         name=result[2].decode('utf-8'),
                         auth=True,
                         no=result[0]))

                if notice_no != '':
                    return redirect(
                        url_for('notice_view.notice_post', p_no=notice_no))
                else:

                    response = make_response(
                        redirect(url_for("main_view.index")))
                    if rmb == 'on':
                        from aes_cipher import encrypt
                        expire_date = datetime.now() + timedelta(days=90)
                        enc_email = encrypt(current_app.config['SECRET_KEY'],
                                            email)
                        response.set_cookie('rmber',
                                            value=enc_email,
                                            expires=expire_date)
                    else:
                        response.set_cookie('rmber', expires=0)

                    flash("로그인 되었습니다.")
                    return response
            else:
                flash("아이디 또는 비밀번호가 일치하지 않습니다.")
                return redirect(url_for("auth_view.login_form"))
        else:
            flash("아이디 또는 비밀번호가 일치하지 않습니다.")
            return redirect(url_for("auth_view.login_form"))

    except Exception as e:
        logger.info(str(e))
        raise e
示例#16
0
def get_or_create_user(claims):
    user_email = claims.get('email')
    user = User.load(db, user_email)

    if user is None:
        user_id = claims['sub']
        user_name = claims.get('name')
        user = User(id=user_id, email=user_email, name=user_name)
        user.save(db)
    return user
示例#17
0
def register(request):
    name = request.params['name']
    mail = request.params['mail']
    password = request.params['password']
    print password
    m = hashlib.md5()
    m.update(password)
    passwordStr = m.hexdigest()
    user_db = User()
    user_db.add_user(name, passwordStr, mail, ['user'])
    return {'status': 'ok'}
示例#18
0
def load_user(email):
    logger.info("load_user(%s)" % (email))
    cursor = dao.get_conn().cursor()
    cursor.execute("select * from recruit_user where user_email like '%s'" %
                   (email))
    result = cursor.fetchone()

    if result[1] == email:
        return User(email, name=result[2], auth=True, no=result[0])
    else:
        return None
示例#19
0
 def __init__(self, **kwargs):
     self.register_event_type('on_confirm')
     super(UserWidget, self).__init__(**kwargs)
     self.user = self.obj
     if self.user:
         self.user = self.user.clone()
     else:
         self.user = User(name='John Doe',
                          weight=75,
                          height=175,
                          male=True,
                          birthday=0)
示例#20
0
def register_user(session: Session, **kwargs):
    kwargs['id'] = None  # Задётся автоинкрементом
    check_email = session.query(User).filter(User.login == kwargs['login']).first()
    if check_email:
        return 'Этот адрес почты уже используется'
    check_username = session.query(User).filter(User.username == kwargs['username']).first()
    if check_username:
        return 'Это имя уже занято'
    user = User(**kwargs)
    session.add(user)
    session.commit()
    return user
示例#21
0
 def test_update_courses(self):
     u = User(name="unknown", email="*****@*****.**", status="inactive")
     _id = u.save()
     u = User.get(_id)
     self.assertFalse(u.courses, "Courses count")
     courses = [Course.get(1), Course.get(2), Course.get(3)]
     u.courses = courses
     u.update()
     u = User.get(_id)
     self.assertTrue(u.courses, "Courses count")
     self.assertEqual(u.courses, courses, "Update courses")
     u.delete()
示例#22
0
def load_user(id):
        logger.info("load_user(), session:"+str(session))

        cursor = db.get_conn().cursor()
        cursor.callproc('get_user_by_id', (id,))  # argument 1개일 때도 ,하나 붙여줘야 제대로 인식함.
        r = cursor.fetchall()
        cursor.close()

        if r : #id가 존재
            return User(id, name=r[0][2], auth=True)
        else:
            return None
示例#23
0
    def form_valid(self, form, **kwargs):
        user = User()
        user.name = form.cleaned_data['name']
        user.email = form.cleaned_data['email']
        user.phone = form.cleaned_data['phone']
        user.mobile_phone = form.cleaned_data['mobile_phone']
        user.status = form.cleaned_data['status']
        user.save()

        context = self.get_context_data(**kwargs)
        messages.add_message(self.request, messages.INFO, 'User created successfully')

        return render(self.request, self.get_template_names(), context=context)
示例#24
0
    def test_added_category(self):
        u = User(name="unknown", email="*****@*****.**", status="inactive")

        courses = [Course.get(1), Course.get(2), Course.get(3)]

        u.courses = courses

        _id = u.save()

        u = User.get(id=_id)
        self.assertEqual(len(u.courses), len(courses), "Count courses")
        self.assertEqual(u.courses, courses, "Saving courses")
        u.delete()
示例#25
0
def get_all_users(request):
    user_db = User()
    users = user_db.get_all_users()
    data = []
    for user in users:
        print user['name']
        data.append([user['name'], user['password'], ','.join(user['roles'])])
    print data
    str = json.dumps(data, encoding="UTF-8", ensure_ascii=False)
    print str
    return json.dumps({
        'status': 'ok',
        'data': str
    },
                      encoding="UTF-8",
                      ensure_ascii=False)
    def __init__(self, payload, responder, db):
        super().__init__()

        self.payload = payload
        self.responder = responder
        self.db = db
        self.user = User(db)
        self.shop = Shop(db)
        self.page_id = ''
        self.page_sender_id = ''
        self.page_recipient_id = ''
        self.sent_text = ''
        self.recipient_reaction = None
        self.latitude = 0.0
        self.longitude = 0.0
        self.recipient_id = ''
        self.quick_reply_payload = ''
示例#27
0
文件: test.py 项目: rodobre/smarthack
def test_index():
    session = Session()
    q = session.query(User).filter_by(name = 'misu').first()

    msg = "not found"
    if q == None:
        session.add(User(name = "misu"))
        session.commit()
    else:
        msg = str(q)

    if "cached" not in Cache:
        Cache["cached"] = True
    else:
        msg += " cached"

    return jsonify({'message': msg})
示例#28
0
def login(request):
    name = request.params['name']
    password = request.params['password']
    user_db = User()
    user = user_db.get_user(name)
    if user is None:
        return {'status': 'nok', 'data': '该用户不存在!'}
    m = hashlib.md5()
    m.update(password)
    passwordStr = m.hexdigest()
    print passwordStr
    if passwordStr == user['password']:
        print 'before session'
        request.session['name'] = name
        roles = user['roles']
        print 'ok'
        return {'status': 'ok', 'roles': roles}
    else:
        return {'status': 'nok', 'data': '密码错误!'}
示例#29
0
    def test_update_user(self):
        u = User(name="unknown", email="*****@*****.**", status="inactive")
        _id = u.save()

        u = User.get(id=_id)
        self.assertEqual(u.name, 'unknown', 'User name')
        self.assertEqual(u.email, '*****@*****.**', 'User email')
        self.assertEqual(u.status, 'inactive', 'User status')

        u.name = 'Michael Cimino'
        u.update()
        u = User.get(id=_id)
        self.assertEqual(u.name, 'Michael Cimino', 'Update user name')
        self.assertEqual(u.email, '*****@*****.**', 'Update user email')
        self.assertEqual(u.status, 'inactive', 'Update user status')

        u.email = "*****@*****.**"
        u.update()
        u = User.get(id=_id)
        self.assertEqual(u.name, 'Michael Cimino', 'Update user name')
        self.assertEqual(u.email, '*****@*****.**', 'Update user email')
        self.assertEqual(u.status, 'inactive', 'Update user status')

        u.status = 'active'
        u.update()
        u = User.get(id=_id)
        self.assertEqual(u.name, 'Michael Cimino', 'Update user name')
        self.assertEqual(u.email, '*****@*****.**', 'Update user email')
        self.assertEqual(u.status, 'active', 'Update user status')

        self.assertIsNone(u.phone, "User phone is not null")
        u.phone = '+380123456789'
        u.update()
        u = User.get(id=_id)
        self.assertEqual(u.phone, '+380123456789', 'Update user phone')

        self.assertIsNone(u.mobile_phone, "User mobile phone is not null")
        u.mobile_phone = '+389876543210'
        u.update()
        u = User.get(id=_id)
        self.assertEqual(u.mobile_phone, '+389876543210',
                         'Update user mobile phone')
示例#30
0
def admin_login():
    id = request.form['id'] if 'id' in request.form else ''
    pwd = request.form['pwd'] if 'pwd' in request.form else ''

    ###############
    cursor = dao.get_conn().cursor()
    query_str = "select * from recruit_user where user_email like '%s'" % (id)
    cursor.execute(query_str)
    result = cursor.fetchone()
    cursor.close()
    ###############
    if result:
        if result[3] == pwd:
            login_user(User(id, name=result[2], auth=True, no=result[0]))
            flash("로그인 완료")
            return redirect(url_for('admin_view.admin_main'))
        else:
            flash("아이디 또는 비밀번호가 잘못되었습니다.")
            return redirect(url_for('admin_view.admin_main'))
    else:
        flash("아이디 또는 비밀번호가 잘못되었습니다.")
        return redirect(url_for('admin_view.admin_main'))