Esempio n. 1
0
    def post(self):

        # Get POST data
        email = self.request.get("email")
        password = self.request.get("psw")

        # Check if user exists
        user = User.query(User.email == email).fetch()
        if not user:
            return self.write("Email or password is wrong")

        # Compare hashed password with value in database
        salt = "d9be95247"
        password = sha256(salt + password + salt).hexdigest()
        if password != user[0].password:
            return self.write("Email or password is wrong")

        # Create session token
        token = sha256(str(time.time()) + user[0].email).hexdigest()

        # Write new session in database
        new_session = Session(token=token, user_email=user[0].email)
        new_session.put()

        # Write token to cookie
        self.response.set_cookie("token", token)

        return self.redirect("/")
Esempio n. 2
0
def test_data():
    SQLModel.init_db()

    form = dict(
        username='******',
        password='******',
        role=UserRole.normal,
    )
    u, result = User.register(form)

    Session.add(u.id)

    form = dict(
        title='test todo',
        user_id=u.id,
    )
    t = TodoAjax.new(form)

    form = dict(
        content='test_weibo',
        user_id=u.id,
    )

    w = Weibo.new(form)

    form = dict(
        content='test_comment',
        user_id=u.id,
        weibo_id=1,
    )

    w = Comment.new(form)
Esempio n. 3
0
def test_session_data():
    form = dict(
        session_id='dsacbhdjshabzmsd',
        user_id=2,
        expired_time=time.time(),
    )
    Session.new(form)
Esempio n. 4
0
def login():
    """
    登录页面的路由函数
    """
    form = request.form
    log('FORM\n{}'.format(form))

    session_id = None
    u, result = User.login(form)
    if not u.is_guest():
        # session ID的生成使用uuid的伪随机字符串生成器
        session_id = str(uuid.uuid4())

        form = dict(
            session_id=session_id,
            user_id=u.id,
        )
        Session.new(form)
    log('USER\n{}'.format(u.username))
    # cookie 范围
    # /login
    # /login/user/view
    # /todo
    response = make_response(
        render_template('login.html', username=u.username, result=result))
    if session_id is not None:
        response.set_cookie('session_id', session_id)
    return response
Esempio n. 5
0
    def post(self):
        login = request.headers["X-Login"]
        password = request.headers["X-Password"]

        if (login or password) is None:
            return '', 404

        user_dict = mongo.db.users.find_one({
            "password":
            self.hash_password(password),
            "login":
            login
        })

        if user_dict is None:
            return '', 403

        session_dict = mongo.db.sessions.find_one({
            "user.login": login,
            "status": 0
        })
        """ we do not create a new session if already exists"""
        if session_dict is not None:
            return Session.session_from_dict(session_dict).format_http(), 201

        user_dict["_id"] = str(user_dict["_id"])
        user = User.user_from_dict(user_dict)

        session = Session.session_from_user(user)
        mongo.db.sessions.insert(session.format())

        return session.format_http(), 201
Esempio n. 6
0
def login(request):
    """
    登录页面的路由函数
    """
    form = request.form()

    u, result = User.login(form)
    # session 会话
    # token 令牌
    # 设置一个随机字符串来当令牌使用
    session_id = random_string()
    form = dict(
        session_id=session_id,
        user_id=u.id,
    )
    Session.new(form)
    # cookie 范围
    # /login
    # /login/user/view
    # /todo
    headers = {
        'Set-Cookie': 'session_id={}; path=/'.format(
            session_id
        )
    }

    return redirect('/user/login/view?result={}'.format(result), headers)
Esempio n. 7
0
def login():
    try:
        email = request.json['email']
        password = request.json['password']
    except KeyError as e:
        return jsonify({'error': 'Missing field(s).', 'details': str(e)}), 401

    try:
        if email != 'admin':
            user = User.find_one(email=email)
            if not user or not user.check_password(password):
                raise ValueError()
            role = user.role
        else:
            role = 'admin'
            if password != config.ADMIN_PASSWORD:
                raise ValueError()

        s = Session(email=email, role=role)
        s.save()

        session['token'] = s.token
        session['email'] = email

        return Response(status=200)
    except ValueError:
        return Response(status=401)
Esempio n. 8
0
    def post(self):
        login = request.headers["X-Login"]
        password = request.headers["X-Password"]

        if (login or password) is None:
            return '', 404

        user_dict = mongo.db.users.find_one({"password": self.hash_password(password), "login": login})

        if user_dict is None:
            return '', 403

        session_dict = mongo.db.sessions.find_one({"user.login": login, "status": 0})

        """ we do not create a new session if already exists"""
        if session_dict is not None:
            return Session.session_from_dict(session_dict).format_http(), 201

        user_dict["_id"] = str(user_dict["_id"])
        user = User.user_from_dict(user_dict)

        session = Session.session_from_user(user)
        mongo.db.sessions.insert(session.format())

        return session.format_http(), 201
Esempio n. 9
0
def create_posts(posts: [int, str, str]):
    tag = s.query(Tag).filter_by(name='Истории').one()
    for post in posts:
        post = Post(*post)
        post.tags.append(tag)
        s.add(post)
    s.commit()
Esempio n. 10
0
def login():
    """
    登录页面的路由函数
    """
    form = request.form

    u, result = User.login(form)
    # session 会话
    # token 令牌
    # 设置一个随机字符串来当令牌使用
    print('u== ', u)
    redirect_to_login_view = redirect(
        '/user/login/view?result={}'.format(result))
    response = current_app.make_response(redirect_to_login_view)

    if u.id is not None:
        print('session add')
        session_id = random_string()
        form = dict(
            session_id=session_id,
            user_id=u.id,
        )
        Session.new(form)

        response.set_cookie('session_id', value=session_id)
        response.set_cookie('path', value='/')

    return response
Esempio n. 11
0
def test():
    connection = pymysql.connect(host='localhost',
                                 user='******',
                                 password='******',
                                 db='web8',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    # with connection.cursor() as cursor:
    # cursor.execute('DROP DATABASE `web8`')
    # cursor.execute('CREATE DATABASE `web8` CHARACTER SET utf8mb4')
    # cursor.execute('USE `web8`')

    # cursor.execute(User.sql_create)
    # cursor.execute(Session.sql_create)
    # cursor.execute(Todo.sql_create)
    # cursor.execute(Comment.insert())
    # connection.commit()
    # connection.close()

    form = dict(
        username='******',
        password='******',
    )
    User.register_user(form)
    u, result = User.login_user(form)
    assert u is not None, result
    form = dict(
        username='******',
        password='******',
    )
    User.register_user(form)

    session_id = random_string()
    form = dict(
        session_id=session_id,
        user_id=u.id,
    )
    Session.new(form)
    s: Session = Session.one(session_id=session_id)
    assert s.session_id == session_id

    form = dict(
        title='test todo',
        user_id=u.id,
    )
    t = Todo.add(form, u.id)
    assert t.title == 'test todo'

    form = dict(content='123', user_id=u.id, weibo_id=1)
    c = Comment.new(form)
    assert c.content == '123'

    form = dict(
        content='123',
        user_id=u.id,
    )
    w = Weibo.new(form)
    assert w.user_id == 1
def signout():
    if request.cookies.get('session'):
        ses = Session()
        ses.delete(request.cookies.get("session"))
        res = make_response(redirect("/authen/signin"))
        res.set_cookie("session", "", max_age=-1)
        return res
    return redirect("/authen/signin")
Esempio n. 13
0
def route_logout(request):
    """
    注销登录
    """
    session = current_session(request)
    session_id = int(session.id)
    Session.delete(session_id)
    return redirect('/')
Esempio n. 14
0
class SessionStore(SessionBase):
    """
    A google appengine datastore based session store. 
    """
        
    def __init__(self, session_key=None):
        self._datastore_session = None
        
        if session_key:
            query = db.Query(Session)
            query = query.filter("session_key =", session_key)
            self._datastore_session = query.get()
        
        super(SessionStore, self).__init__(session_key)
    
    def load(self):
        session_data = {}
        if self._datastore_session:
            if self._datastore_session.expire_date > datetime.now():
                if self._datastore_session.session_data:
                    session_data = self.decode(self._datastore_session.session_data)
                else:
                    session_data = None
            else:
                self.delete()
            
        return session_data or {}

    def save(self):
        time_till_expire = timedelta(seconds=60*60*24*7*2)
        expire_date = datetime.now() + time_till_expire
        
        if self._datastore_session:
            self._datastore_session.session_data = self.encode(self._session)
        else:
            self._datastore_session = Session(session_key=self.session_key, session_data=self.encode(self._session), expire_date=expire_date)
        self._datastore_session.put()
        

    def exists(self, session_key):
        query = db.Query(Session)
        query = query.filter("session_key =", session_key)
        session = query.get()

        if session:
            exists = True
        else:
            exists = False
            
        return exists
        
    def delete(self, session_key):
        query = db.Query(Session)
        query = query.filter("session_key =", session_key)
        session = query.get()

        if session:
            session.delete()
Esempio n. 15
0
def signout():
    if request.cookies.get('session'):
        ses = Session()
        ret = ses.delete(request.cookies.get('session'))

        res = make_response(redirect('/authen/signin'))
        res.set_cookie('session', '', max_age= -1)
        return res
    return redirect('authen/signin')
Esempio n. 16
0
  def test_multiple_session(self):
    user = User.create()
    sessions = [
      Session.create(user = user),
      Session.create(user = user)
    ]

    for session in Session.find_by_user(user).all:
      assert session in sessions
Esempio n. 17
0
def bootstrap_database(environment='development'):
    """Create the database."""

    print green('Creating database')
    database.create()
    print green('Defining schema')
    with open('migrations/schema.sql') as f:
        sql = f.read().replace('\n', '')
    Session.execute(sql)
    Session.commit()
Esempio n. 18
0
def bootstrap_database(environment='development'):
    """Create the database."""

    print green('Creating database')
    database.create()
    print green('Defining schema')
    with open('migrations/schema.sql') as f:
        sql = f.read().replace('\n', '')
    Session.execute(sql)
    Session.commit()
Esempio n. 19
0
def change_password(**params):
    if request.method == "GET":
        token = request.cookies.get('my-simple-app-session')
        success, user, message = Session.verify_session(token)

        csrf_token = CSRFToken.generate_csrf_token(user)

        if success and csrf_token:
            params["current_user"] = user
            params["csrf_token"] = csrf_token
            return render_template("public/auth/change_password.html",
                                   **params)
        else:
            params["error_message"] = message
            return render_template("public/auth/error_page.html", **params)

    elif request.method == "POST":
        token = request.cookies.get('my-simple-app-session')
        success, user, message = Session.verify_session(token)

        current_email = user.email
        current_password = request.form.get("current_password")
        new_password = request.form.get("new_password")
        form_csrf_token = request.form.get("csrf_token")
        csrf_validation_success = CSRFToken.validate_csrf_token(
            form_csrf_token)

        if current_email and current_password and new_password and csrf_validation_success:
            # checks if user with this e-mail and password exists
            user = User.query.filter_by(email=current_email).first()

            if user and bcrypt.checkpw(current_password.encode("utf-8"),
                                       user.password.encode("utf-8")):
                success, message = User.update_password(
                    current_email, new_password)

                if success:
                    # if password was changed, logout the user so he has to login again
                    # prepare the response
                    message = "Your password has been changed, please login again."
                    response = redirect(
                        url_for("public.main.login", info_message=message))

                    # remove session cookie
                    response.set_cookie('my-simple-app-session', '', expires=0)

                    return response
                else:
                    params["error_message"] = message
                    return render_template("public/auth/error_page.html",
                                           **params)
            else:
                params[
                    "error_message"] = "You entered the wrong old password, please try again."
                return render_template("public/auth/error_page.html", **params)
Esempio n. 20
0
def login_valid():
    """
    验证登陆数据
    """
    # 接收POST数据
    form = dict()
    for k, v in request.form.items():
        form[k] = v
    log('FORM\n{}'.format(form))

    # 验证验证码
    vcode = form['code']
    vcode = hashlib.sha256(vcode.encode('ascii')).hexdigest()
    vcode = 'static/code/{}.png'.format(vcode)
    img = form['img']
    if img != vcode:
        return redirect(
            url_for('.log_info',
                    result='验证码不正确',
                    target=url_for('.login_view')))
    form.pop('code')
    form.pop('img')

    session_id = None
    u, result = User.login(form)

    if result != '登录成功':
        return redirect(
            url_for('.log_info',
                    result='用户名或者密码错误',
                    target=url_for('.login_view')))

    if not u.is_guest():
        session_id = uuid.uuid4().hex
        form = dict(
            session_id=session_id,
            user_id=u.id,
        )
        Session.new(form)
        # 生成csrf令牌
        u = current_user()
        if u.id > 0:
            generate_csrf_token()
            log('更新CSRF令牌')

    log('USER\n{}'.format(u.username))
    response = make_response(
        redirect(
            url_for('.log_info', result=result,
                    target=url_for('public.index'))))
    if session_id is not None:
        response.set_cookie('session_id', session_id)
    return response
Esempio n. 21
0
def set_contribution(contribution_info, politician):
    """
    Given a dict of contribution information, returns a contribution object
    created from that information.

    Returns True if the contribution object was successfully created and added
    to the database.
    TODO: Add validations/checking and error handling.
    """
    # First create the new contribution object and set its fields
    contribution = Contribution()
    contribution.date = datetime.strptime(contribution_info['date'], DATE_FORMAT)

    funder = Funder.get_by_name(contribution_info['funder'])
    if funder is not None:
        contribution.funder = funder
    else:
        # This funder doesn't exist yet, so we need to create it
        funder = Funder({'name': contribution_info['funder']})
        Session.add(funder)
        Session.commit()
        contribution.funder = funder
    contribution.politician = politician

    # If this funder is a new one for the given politician, add it to his/her
    # funders list
    if funder not in politician.funders:
        politician.funders.append(funder)

    Session.add(contribution)
    Session.commit()
    return True
def doEditPassword(id):
    acc = Account()
    v = acc.getAccountById(id)
    usr = v['usr']
    newpwd = request.form.get("pwd") + '#$%^&*$@' + usr
    newpwd = md5(newpwd.encode())
    a = (newpwd.digest(), id)
    ret = acc.editPassword(a)
    if ret > 0:
        if request.cookies.get('session'):
            ses = Session()
            ses.delete(request.cookies.get("session"))
            res = make_response(redirect("/authen/signin"))
            res.set_cookie("session", "", max_age=-1)
            return res
    return "Failed"
Esempio n. 23
0
    def get_session(self, user_key: str, session_key: str) -> Session:

        # Sets up a document reference to a specified session.
        ref = db.document(f'users/{user_key}/sessions/{session_key}')

        # Converts the entries stored within the referenced document
        # into a dictionary.
        session_dict: dict = ref.get().to_dict()

        # Builds up a reference to the performance document of a
        # specified session.
        ref = db.document(
            f'users/{user_key}/sessions/{session_key}/data/performance')

        # Adds the performance entries to the session dictionary,
        # enabling the convertion from a dictionary to a Session
        # object.
        performance: Performance = Performance.from_dict(ref.get().to_dict())

        # Creates a session which is based on the entries within the
        # previously updated dictionary.
        session: Session = Session.from_dict(session_dict, performance)

        # Return the newly created session.
        return session
Esempio n. 24
0
def oauth2_callback():
    if (request.args.get('error') == 'access_denied'):
        return 'You denied the access'
    token_data = fetch_access_token(request.args.get('code'),
                                    config.get("PROFILE_REDIRECT_URI"))

    headers = {'Authorization': 'Bearer {}'.format(token_data['access_token'])}
    url = 'https://www.googleapis.com/oauth2/v1/userinfo'
    res = urlfetch.fetch(url, headers=headers,
                         method='GET')  # Getting userinfo
    user_data = json.loads(res.content)
    email = user_data.get('email')
    user = User.get_by_id(email)
    if user:
        user.name = user_data.get('name')
        picture = user_data.get('picture')
        user.put()
    else:
        User.set_user(user_data)

    uuid = Session.set_session(user_data)

    res = redirect('/')
    res.set_cookie('sessionID', uuid)

    return res
Esempio n. 25
0
def login(request):
    """
    登录页面的路由函数
    """
    form = request.form()

    u, result = User.login(form)
    session_id = random_string()
    form = dict(
        session_id=session_id,
        user_id=u.id,
    )
    Session.new(form)
    headers = {'Set-Cookie': 'session_id={}; path=/'.format(session_id)}

    return redirect('/user/login/view?result={}'.format(result), headers)
Esempio n. 26
0
def list_contacts():
    session_id = request.cookies.get('sessionID')
    if not session_id or session_id == '':
        return jsonify(dict(success=False, error='unauthorized'))
    user = Session.get_by_id(session_id)
    if not user:
        return jsonify(dict(success=False, error='unauthorized'))

    email = user.email
    # logging.info('email : {}'.format(email))
    cursor = request.args.get('cursor')
    if not cursor: cursor = None
    cursor = Cursor(urlsafe=cursor)
    query = Contacts.query(Contacts.owner == email).order(Contacts.name_lc)
    contacts, next_cursor, more = query.fetch_page(10, start_cursor=cursor)
    # logging.info('cursor: {} more: {}'.format(next_cursor, more))
    if next_cursor:
        cursor = next_cursor.urlsafe()
    else:
        cursor = None
    data = [contact.to_dict() for contact in contacts]

    return jsonify({
        'cursor': cursor,
        'more': more,
        'contacts': data,
        'success': True
    })
Esempio n. 27
0
def route_login(request):
    """
    登录页面的路由函数
    """
    log('login, cookies', request.cookies)
    if request.method == 'POST':
        form = request.form()
        u = User(form)
        if u.validate_login():
            session_id = random_str()
            u = User.find_by(username=u.username)
            s = Session.new(dict(
                session_id=session_id,
                user_id=u.id,
            ))
            s.save()
            log('session', s)
            headers = {
                'Set-Cookie': 'sid={}'.format(session_id)
            }
            # 登录后定向到 /
            return redirect('/', headers)
    # 显示登录页面
    body = template('login.html')
    return http_response(body)
Esempio n. 28
0
def route_profile(request):
    headers = {
        'Content-Type': 'text/html',
    }
    session_id = request.cookies.get('session_id', None)
    s = Session.find_by(session_id=session_id)
    if s is None:
        header = 'HTTP/1.x 302 Moved Temporarily\r\nLocation:http://127.0.0.1:3000/login\r\n'
        header += ''.join([
            '{}: {}\r\n'.format(k, v) for k, v in headers.items()
        ])
        body = ''
        r = '{}\r\n{}'.format(header, body)
        log('login 的响应', r)
        return r.encode()
    else:
        s = User.find_by(username=s.username)
        body = route_template('profile.html')
        body = body.replace('{{id}}', str(s.id))
        body = body.replace('{{username}}', s.username)
        body = body.replace('{{note}}', s.note)
        header = formatted_with_headers(headers)
        r = '{}\r\n{}'.format(header, body)
        log('login 的响应', r)
        return r.encode()
Esempio n. 29
0
def registration(**params):
    if request.method == "GET":
        token = request.cookies.get('my-simple-app-session')
        success, user, message = Session.verify_session(token)

        if success:
            params["current_user"] = user
            return render_template("public/auth/logged_in.html", **params)
        else:
            return render_template("public/auth/registration.html", **params)

    elif request.method == "POST":
        email = request.form.get("email")
        password = request.form.get("password")

        if email and password:
            success, user, message = User.create(email=email, password=password)

            if success:
                send_success = User.send_verification_code(user)

                if send_success:
                    return render_template("public/auth/verify_email.html", **params)
            else:
                params["error_message"] = message
                return render_template("public/auth/error_page.html", **params)
Esempio n. 30
0
def import_contacts():
    uuid = request.cookies.get('sessionID')
    entity = Session.get_by_id(uuid)

    if entity:
        email = entity.email
    else:
        return redirect('/')

    if (request.args.get('error') == 'access_denied'):
        return 'You denied the access'

    token_data = fetch_access_token(request.args.get('code'),
                                    config.get("CONTACTS_REDIRECT_URI"))

    user = User.get_by_id(email)
    user.set_token(token_data)
    user.import_status = "importing"
    user.put()
    taskqueue.add(url='/fetch-contacts',
                  params={
                      'email': email,
                      'access_token': token_data.get('access_token')
                  },
                  method='GET')

    return render_template('popup.html', success='true')
Esempio n. 31
0
def current_user(request):
    session_id = request.cookies.get('user', '')
    sessions = Session.all()
    for s in sessions:
        if s.session_id == session_id:
            return s.username
    return '【游客】'
Esempio n. 32
0
def route_login(request):
    headers = {
        'Content-Type': 'text/html',
    }
    log('login, headers', request.headers)
    log('login, cookies', request.cookies)
    username = current_user(request)
    if request.method == 'POST':
        form = request.form()
        u = User.new(form)
        if u.validate_login():
            session_id = random_string()
            session_date['username'] = u.username
            session_date['session_id'] = session_id
            log('这个才是session', session_date)
            s = Session.new(session_date)
            s.save()
            headers['Set-Cookie'] = 'session_id={}'.format(session_id)
            result = '登录成功'
        else:
            result = '用户名或者密码错误'
    else:
        result = ''

    body = template('login.html')
    body = body.replace('{{result}}', result)
    body = body.replace('{{username}}', username)
    header = response_with_headers(headers)
    r = '{}\r\n{}'.format(header, body)
    log('login 的响应', r)
    return r.encode()
Esempio n. 33
0
def register():
    """
    接受注册信息, 写入数据库
    """
    # 获取注册相关数据
    form = dict()
    for k, v in request.form.items():
        form[k] = v

    # 执行注册数据
    user, result = User.register(form)
    log('Register result:', result, user)

    #  注册结果失败则返回到注册页面, 成功则自动登陆
    if result == '注册成功':
        log(f'自动登陆用表单\n{form}')
        form = dict(
            session_id=uuid.uuid4().hex,
            user_id=user.id,
        )
        s = Session.new(form)

        generate_csrf_token(user)
        response = make_response(redirect(url_for('public.index')))
        response.set_cookie('session_id', s.session_id)
        return response
    else:
        return redirect(
            url_for('.loginfo', result=result, target=url_for('users.login')))
Esempio n. 34
0
def current_user(request):
    if 'session_id' in request.cookies:
        session_id = request.cookies['session_id']
        u = Session.find_user(session_id=session_id)
        return u
    else:
        return User.guest()
    def query_sessions(self, request):
        """Query for sessions.

        This uses some filters to query the NDB Datastore, and applies
        other filters in memory. An arbitrary list of filters can be
        passed in, but the query won't work if the required indices
        for the query sent to NDB have not been created.

        Args:
            request (QueryForms):
                List of filters.

        Each filter has:
            - field: one of
                "TYPE" (type of session),
                "TIME" (in "HH:MM:SS" format)
            - operator: one of
                "EQ" (=),
                "GT" (>),
                "GTEQ" (>=),
                "LT" (<),
                "LTEQ" (<=),
                "NE" (!=)
            - value: the desired value to compare with

        Returns:
            SessionForms: List of sessions matching all the filters.
        """
        # Run query with filters applied in memory if necessary
        plain_query = Session.query()
        sessions = self._generic_query(plain_query, request.filters, QUERY_FIELDS)

        return SessionForms(
            items = [s.to_form() for s in sessions]
        )
Esempio n. 36
0
def user_role_change(user, params, token, device):
    uid = params.get("id", "")
    if device == "web":
        role, role_id = user.identify[0], int(user.identify[1:])
    else:
        role, role_id = user.app_identify[0], int(user.app_identify[1:])

    tmp_user = User.select().where(User.uuid==uid).first()
    identify = None
    if not tmp_user:
        tmp_team = Team.select().where(Team.uuid==uid).first()
        if not tmp_team or tmp_team.user != user:
            return {"error_code": 20332, "msg": "the role not change, not allowed"}
        if role == "f":
            identify = "c%s" % tmp_team.id
    else:
        if tmp_user.id != user.id:
            return {"error_code": 20332, "msg": "the role not change, not allowed"}
        if role == "c":
            identify = "f%s" % tmp_user.id

    if identify:
        if device == "web":
            user.identify = identify
            user.save()
        else:
            user.app_identify = identify
            user.save()

    if device in ("ios", "android"):
        qs = Session.delete().where(Session.user==user, Session.session_key!=token, Session.device << ("ios", "android"))
        qs.execute()
    return {"error_code": 0, "msg": "ok"}
Esempio n. 37
0
 def save(self):
     time_till_expire = timedelta(seconds=60*60*24*7*2)
     expire_date = datetime.now() + time_till_expire
     
     if self._datastore_session:
         self._datastore_session.session_data = self.encode(self._session)
     else:
         self._datastore_session = Session(session_key=self.session_key, session_data=self.encode(self._session), expire_date=expire_date)
     self._datastore_session.put()
 def get(self):
     """ Returns a list of available lobbies.
     """
     data = json.loads(self.request.body)
     cid = data["cid"]
     session = Session.query(Session.channel_id == cid).get()
     target_gold_amount = session.target_gold_amount
     print target_gold_amount
     response = {'target_gold_amount': target_gold_amount}
     self.response.out.write(json.dumps(response))
Esempio n. 39
0
    def initialize(self):
        token = self.get_cookie("session_token")

        self.is_mobile, self.is_desktop = False, False

        self.user = None
        if token:
            session = Session.select().where(Session.session_key==token, Session.expire_at>now()).first()
            if session:
                self.user = session.user

        self.params = {key: value[-1] for key, value in self.request.arguments.items()}
Esempio n. 40
0
    def parse_sesh(self):
        """Get the session form the cookie or the url"""

        sesh = Session()
        sid = ""

        # token in the request then use it
        sid = self.request.get(self.conf.URL_TOKEN_NAME, default_value="")
        # else get the token from the session
        if sid == "":
            if self.conf.TOKEN_NAME in self.request.cookies:
                sid = self.request.cookies[self.conf.TOKEN_NAME]


        if sid == "":
            # no sesion found so create one
            sesh.create()
        else:
            # got a session id so load from memcache or create a new one if its timed out
            sesh.load(sid)

        logging.debug("Session ID: " + sesh.id())
        self.response.headers['Set-Cookie'] = str('%s=%s;path=/;expires=Sat, 1-Jan-2050 00:00:00 GMT;'%(self.conf.TOKEN_NAME, sesh.id()))
        
        return sesh
Esempio n. 41
0
def client_login(params):
    code = params.get("code")
    if not code or len(code) != 36:
        return {"error_code":1, "msg":"params invalid"}
    key = "jump-%s" % code
    obj = misc.misc_get(key)
    if not obj:
        return {"error_code":1, "msg":"code not exists"}
    dic = utils.loads(obj.value)

    obj.delete_instance()
    if dic['expire_at'] < utils.stamp():
        return {"error_code":1, "msg":"code expire"}

    user = User.select().where(User.id==dic['user_id']).first()
    res = {"error_code":0, "msg":"ok"}
    res['session_token'] = generate_token()
    sess = Session()
    sess.user = user
    sess.session_key = res['session_token']
    sess.expire_at = utils.timedelta(utils.now(), days=1)
    res['expire_at'] = 0
    sess.save()
    res['identify'] = user.identify
    return res
Esempio n. 42
0
def im_session_verify(params):
    token = params.get("session_token")
    session = Session.select().where(Session.session_key==token, Session.expire_at>utils.now()).first()
    if not session:
        return {"error_code":1, "msg":"token not exist"}
    user = session.user
    role, tid = user.app_identify[0], int(user.app_identify[1:])
    if role == "f":
        return {"error_code":0, "msg":"ok", "id":user.id}
    team = Team.select().where(Team.id == tid).first()
    if not team:
        return {"error_code":1, "msg":"token error"}
    return {"error_code":0, "msg":"ok", "id":team.id}
Esempio n. 43
0
def store_politician(politician_data):
    """
    Given a dict of politician data, stores the given data into the database.

    The passed in dict is assumed to contain the following fields:
    name, the name of the politician
    funders, an array of dicts representing contributions made by a
    politician's funders

    Returns True if the politician has been successfully added to the database.

    TODO: Check if we've already encountered this politician - then how do we 
    respond? Assume we have new contributions/funders to add to its list?
    Also need to add validations
    Figure out how to respond to multiple politicians with the same name
    """
    new_politician = Politician({'name': politician_data['name']})
    if 'contributions' in politician_data:
        for contribution in politician_data['contributions']:
            set_contribution(contribution, new_politician)
    Session.add(new_politician)
    Session.commit()
    return True
    def get_conference_sessions(self, websafe_conference_key):
        """Given a conference, return all sessions.

        Args:
            websafe_conference_key (string)

        Returns:
            SessionForms
        """
        # Get Conference object
        conference = self.get_conference(websafe_conference_key)

        # Query sessions by ancestor conference
        sessions = Session.query(ancestor = conference.key)

        return SessionForms(
            items = [s.to_form() for s in sessions]
        )
    def create_session(self, websafe_conference_key, request):
        """Create new session. Open only to the organizer of the conference.

        Args:
            websafe_conference_key (string)
            request (SessionForm)

        Returns:
            SessionForm updated with the new object's key

        Raises:
            endpoints.ForbiddenException if the user is not the conference owner
        """
        # Get Conference object
        conference = self.get_conference(websafe_conference_key)

        # Verify that the user is the conference organizer
        user_id = self.get_user_id()
        if user_id != conference.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        # Allocate session ID and generate session key
        p_key = conference.key
        s_id = Conference.allocate_ids(size = 1, parent = p_key)[0]
        s_key = ndb.Key(Session, s_id, parent = p_key)

        # Create and store new session object
        session = Session.to_object(request)
        session.key = s_key # set the key since this is a new object
        session.put()

        # Check for featured speakers - delegate to a task
        if session.speakerKey:
            taskqueue.add(
                params={'websafeSpeakerKey': session.speakerKey.urlsafe(),
                        'websafeConferenceKey': conference.key.urlsafe()},
                url='/tasks/set_feature_speaker'
            )

        # Return form back
        return session.to_form()
    def get_sessions_by_speaker(self, websafe_speaker_key):
        """Given a speaker, return all sessions given by this particular speaker,
        across all conferences.

        Args:
            websafe_speaker_key (string)

        Returns:
            SessionForms
        """
        # Get Speaker object
        speaker = self.get_speaker(websafe_speaker_key)

        # Query sessions by speaker key property
        query = Session.query()
        sessions = query.filter(Session.speakerKey == speaker.key)

        return SessionForms(
            items = [s.to_form() for s in sessions]
        )
    def get_conference_sessions_by_type(self, websafe_conference_key, type_of_session):
        """Given a conference, return all sessions of a specified type
        (e.g. lecture, keynote, workshop).

        Args:
            websafe_conference_key (string)
            type_of_session (string)

        Returns:
            SessionForms
        """
        # Get Conference object
        conference = self.get_conference(websafe_conference_key)

        # Query sessions by ancestor and type property
        query = Session.query(ancestor = conference.key)
        sessions = query.filter(Session.typeOfSession == type_of_session)

        return SessionForms(
            items = [s.to_form() for s in sessions]
        )
    def _cache_featured_speaker(websafe_speaker_key, websafe_conference_key):
        """Create featured speaker announcement & assign to memcache.

        Only adds an announcement if the speaker has more than one session
        by the speaker at the conference.

        Args:
            websafe_speaker_key (string)
            websafe_conference_key (string)

        Returns:
            Announcement message (string)
        """
        # Get speaker
        speaker = ndb.Key(urlsafe = websafe_speaker_key).get()

        # Get conferenc e
        conference = ndb.Key(urlsafe = websafe_conference_key).get()

        # Get speaker sessions
        q = Session.query(ancestor = conference.key)
        sessions = q.filter(Session.speakerKey == speaker.key).fetch()

        # Only feature if the speaker has more than on session
        if len(sessions) > 1:
            announcement = "Featured speaker: " + speaker.name
            announcement += "\nSessions:"
            for s in  sessions:
                announcement += "\n- " + s.name
            memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY, announcement)
        else:
            # TODO: For a real app, do not replace the previous speaker with this
            announcement = "Not a featured speaker..."
            memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY, announcement)

        return announcement
    def get_sessions_by_conference_speaker(self, websafe_speaker_key, websafe_conference_key):
        """Given a speaker and a conference, return all sessions given by
        the speaker at the conference.

        Args:
            websafe_speaker_key (string)
            websafe_conference_key (string)

        Returns:
            SessionForms
        """
        # Get Speaker object
        speaker = self.get_speaker(websafe_speaker_key)

        # Get Conference object
        conference = self.get_conference(websafe_conference_key)

        # Load sessions
        query = Session.query(ancestor = conference.key)
        sessions = query.filter(Session.speakerKey == speaker.key)

        return SessionForms(
            items = [s.to_form() for s in sessions]
        )
    def get_conference_speakers(self, websafe_conference_key):
        """Given a conference, get the list of all speakers.

        Args:
            websafe_conference_key (string)

        Returns:
            SpeakerForms
        """
        # Get Conference object
        conference = self.get_conference(websafe_conference_key)

        # Get all sessions for the conference
        sessions = Session.query(ancestor = conference.key).fetch()

        # Only use valid keys and ignore duplicates
        speaker_keys = set([s.speakerKey for s in sessions if s.speakerKey])

        # Get the speakers
        speakers = ndb.get_multi(speaker_keys)

        return SpeakerForms(
            items = [s.to_form() for s in speakers]
        )
Esempio n. 51
0
def login(uname, password):
    if not uname or not password:
        return {"error_code":20001, "msg":"parameters required"}

    user = User.select().where(User.username == uname or User.email == uname or User.phone == uname).first()
    if not user:
        return {"error_code":20002, "msg":"user not exists"}
    if not check_password(password, user.password, user.salt):
        return {"error_code":20003, "msg":"username or password invalid"}

    res = {"error_code":0, "msg":"ok"}
    res['session_token'] = generate_token()
    sess = Session()
    sess.user = user
    sess.session_key = res['session_token']

    sess.expire_at = utils.timedelta(utils.now(), days=1)
    res['expire_at'] = 0
    sess.save()

    return res
Esempio n. 52
0
def logout(user):
    if user:
        Session.delete().where(Session.user==user)
    return {"error_code":0, "msg":"ok"}
Esempio n. 53
0
 def test_without_user(self):
   with pytest.raises(Exception):
     Session.create(user = None)
Esempio n. 54
0
 def test_duplicate_tokens(self):
   user = User.create()
   Session.create(user = user, token = 'test_token')
   with pytest.raises(Exception):
     Session.create(user = user, token = 'test_token')
Esempio n. 55
0
def cleanup_session(body):
    now = utils.now()
    qs = Session.delete().where(Session.expire_at <= now)
    qs.execute()
Esempio n. 56
0
 def test_with_user(self):
   user = User.create()
   result = Session.create(user = user)
   assert result.user == user
Esempio n. 57
0
 def decorated_function(*args, **kwargs):
     session_id = request.cookies.get('session_id')
     if not Session.verify_session(session_id):
         return redirect("/login/form", code=302)
     Session.refresh_session(session_id)
     return f(*args, **kwargs)
    def post(self):
        """ Start game by both users.
        Request
            uid - user_id
            lid - the game lobby both users are playing in
        Response
        """
        data = json.loads(self.request.body)
        response = {}

        try:
            uid = data['uid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing uid (User id)'
            return self.response.out.write(json.dumps(response))

        try:
            lobby_id = data['lid']
        except KeyError:
            self.error(400)
            response['status'] = 'error'
            response['msg'] = 'Missing lid (Lobby id)'
            return self.response.out.write(json.dumps(response))

        lobby = Lobby.query(Lobby.lobby_id == lobby_id).get()

        if lobby is None:
            logging.error(
                "User (" + str(uid) + ") attempted to join non-existent Lobby (" + str(lobby_id) + ").")
        else:
            ready = lobby.ready
            # This is a new user who is ready
            if uid not in ready:
                lobby.ready.append(uid)
                lobby.put()

        response = {}
        # The game is ready to be started
        if len(lobby.ready) == REQ_USERS:
            # TODO: Add logic for creating a Session here
            session = Session(channel_id=lobby_id, target_gold_amount="100",
                              user_ids=[])
            for i in range(len(lobby.ready)):
                session.user_ids.append(lobby.ready[i])
            session.put()
            response['type'] = "info"
            response['data'] = {"ready": "true"}
            pubnub.subscribe(lobby_id, callback)
            pubnub.publish(lobby_id, response)
            pubnub.unsubscribe(lobby_id)

            self.response.out.write(json.dumps(response))
        else:
            response['type'] = "info"
            response['data'] = {"ready": "false"}
            pubnub.subscribe(lobby_id, callback)
            pubnub.publish(lobby_id, callback)
            pubnub.unsubscribe(lobby_id)
            self.response.out.write(json.dumps(response))
Esempio n. 59
0
 def test_get_owner(self):
   user = User.create()
   session = Session.create(user = user)
   session = Session.find_by_id(session.id)
   assert user == session.fetch_user()