Exemplo n.º 1
0
def search_item_coupons():
    paged = get_param('paged', Struct.Int, default=1)
    perpage = get_param('perpage', Struct.Int, default=60)
    keyword = get_param('keyword', Struct.Attr, default=u'')
    categories = get_param('categories')

    paged = parse_int(paged, 1, 1)
    perpage = parse_int(perpage, 1, 1)

    if not keyword:
        return []

    perpage = _safe_perpage(paged, perpage)
    if perpage <= 0:
        return []

    taoke = connect_taoke()

    try:
        coupons = taoke.list_coupons(search_key=keyword,
                                     categories=categories,
                                     paged=paged,
                                     perpage=perpage)
    except Exception as e:
        current_app.logger.error(StoreCouponError(e))
        coupons = []

    return [output_coupon(coupon) for coupon in coupons]
Exemplo n.º 2
0
def search_view_contents(app_id):
    keywords = get_param('keywords', list, default=[])
    content_type = get_param('content_type', unicode, default=None)
    perpage = get_param('perpage', int, default=0)
    paged = get_param('paged', int, default=0)

    theme_opts = g.curr_app['theme_meta'].get('options', {})

    if not perpage:
        perpage = theme_opts.get('perpage')

    perpage, paged = _safe_paging(perpage, paged)

    limit = perpage
    offset = max(perpage * (paged - 1), 0)

    results, total_count = search_by_files(content_type=content_type,
                                           keywords=keywords,
                                           offset=offset,
                                           limit=limit)

    max_pages = max(int(math.ceil(total_count / float(perpage))), 1)
    paged = min(max_pages, paged)

    pages = [parse_page_metas(p) for p in results]
    run_hook('get_pages', pages=pages, current_page_id=None)

    return output_result(contents=pages, perpage=perpage, paged=paged,
                         total_pages=max_pages, total_count=total_count)
Exemplo n.º 3
0
def get_oauth_access_token(open_id):
    Struct.Id(open_id)

    state = get_param('state', Struct.Sid, True)
    code = get_param('code', Struct.Sid, True)

    if not current_app.sup_oauth.match_random_string(state, open_id):
        raise UserStateInvalid

    ExtUser = current_app.mongodb_conn.ExtUser

    user = ExtUser.find_one_by_open_id(open_id)

    if not user:
        user = ExtUser()
        user['open_id'] = open_id

    try:
        resp = current_app.sup_oauth.get_access_token(code)
        print resp
        assert 'access_token' in resp
    except Exception as e:
        raise RequestAccessTokenFailed('access')

    try:
        profile = current_app.sup_oauth.get_profile(resp['access_token'])
    except current_app.sup_oauth.OAuthInvalidAccessToken as e:
        raise RequestAccessTokenFailed('profile')
    except Exception as e:
        raise UserProfileFailed(str(e))

    try:
        ext_token = current_app.sup_oauth.generate_ext_token(open_id)
    except Exception as e:
        raise UserTokenFailed(str(e))
    

    user['access_token'] = resp['access_token']
    user['refresh_token'] = resp['refresh_token']
    user['expires_at'] = resp['expires_in']+now()
    user['token_type'] = resp['token_type']
    user['status'] = ExtUser.STATUS_ACTIVATED

    user['display_name'] = profile['display_name']
    user['title'] = profile['title']
    user['locale'] = profile['locale']
    user['description'] = profile['description']
    user['type'] = profile['type']
    user['snapshot'] = profile['snapshot']
    user['scope'] = pre_process_scope(profile['owner_alias'],
                                      profile['app_alias'])
    user.save()
    
    logged_user = output_user(user)
    logged_user['token'] = ext_token

    return logged_user
Exemplo n.º 4
0
def get_oauth_access_token(open_id):
    Struct.Id(open_id)

    state = get_param('state', Struct.Sid, True)
    code = get_param('code', Struct.Sid, True)

    if not current_app.sup_oauth.match_random_string(state, open_id):
        raise UserStateInvalid

    ExtUser = current_app.mongodb_conn.ExtUser

    user = ExtUser.find_one_by_open_id(open_id)

    if not user:
        user = ExtUser()
        user['open_id'] = open_id

    try:
        resp = current_app.sup_oauth.get_access_token(code)
        print resp
        assert 'access_token' in resp
    except Exception as e:
        raise RequestAccessTokenFailed('access')

    try:
        profile = current_app.sup_oauth.get_profile(resp['access_token'])
    except current_app.sup_oauth.OAuthInvalidAccessToken as e:
        raise RequestAccessTokenFailed('profile')
    except Exception as e:
        raise UserProfileFailed(str(e))

    try:
        ext_token = current_app.sup_oauth.generate_ext_token(open_id)
    except Exception as e:
        raise UserTokenFailed(str(e))

    user['access_token'] = resp['access_token']
    user['refresh_token'] = resp['refresh_token']
    user['expires_at'] = resp['expires_in'] + now()
    user['token_type'] = resp['token_type']
    user['status'] = ExtUser.STATUS_ACTIVATED

    user['display_name'] = profile['display_name']
    user['title'] = profile['title']
    user['locale'] = profile['locale']
    user['description'] = profile['description']
    user['type'] = profile['type']
    user['snapshot'] = profile['snapshot']
    user['scope'] = pre_process_scope(profile['owner_alias'],
                                      profile['app_alias'])
    user.save()

    logged_user = output_user(user)
    logged_user['token'] = ext_token

    return logged_user
Exemplo n.º 5
0
def create_post():
    user = g.curr_user
    open_id = user.get('open_id')

    title = get_param('title', Struct.Attr, required=True)
    content = get_param('content', Struct.Text, required=True)

    post = current_app.mongodb_conn.Post()
    post["open_id"] = open_id
    post["title"] = title
    post["content"] = content
    post.save()
    return output_post(post)
Exemplo n.º 6
0
def create_post():
    user = g.curr_user
    open_id = user.get('open_id')

    title = get_param('title', Struct.Attr, required=True)
    content = get_param('content', Struct.Text, required=True)

    post = current_app.mongodb_conn.Post()
    post["open_id"] = open_id
    post["title"] = title
    post["content"] = content
    post.save()
    return output_post(post)
Exemplo n.º 7
0
def update_profile():
    host = get_param("host", Struct.Domain, required=True)
    port = get_param("port", Struct.Int, required=True)
    username = get_param("username", Struct.Email, required=True)
    use_tls = get_param("use_tls", Struct.Bool, default=False)

    profile = current_app.mongodb_conn.Profile.\
        find_one_by_open_id(g.curr_user["open_id"])
    if not profile:
        raise ProfileNotFound
    profile["host"] = host
    profile["port"] = port
    profile["username"] = username
    profile["use_tls"] = use_tls
    profile.save()
    return output_profile(profile)
Exemplo n.º 8
0
def update_post(post_id):
    Struct.ObjectId(post_id)
    title = get_param('title', Struct.Attr, required=True)
    content = get_param('content', Struct.Text, required=True)

    post = current_app.mongodb_conn.Post.\
        find_one_by_id_and_open_id(post_id, g.curr_user["open_id"])
    if not post:
        raise PostNotFound

    post["title"] = title
    post["content"] = content
    post["update_time"] = now()
    post.save()

    return output_post(post)
Exemplo n.º 9
0
def update_profile():
    meta = get_param('meta', Struct.Dict, default={})

    user = g.user
    user['meta'] = meta
    user.save()
    return output_profile(user)
Exemplo n.º 10
0
def update_post(post_id):
    Struct.ObjectId(post_id)
    title = get_param('title', Struct.Attr, required=True)
    content = get_param('content', Struct.Text, required=True)

    post = current_app.mongodb_conn.Post.\
        find_one_by_id_and_open_id(post_id, g.curr_user["open_id"])
    if not post:
        raise PostNotFound

    post["title"] = title
    post["content"] = content
    post["update_time"] = now()
    post.save()

    return output_post(post)
Exemplo n.º 11
0
def update_profile():
    host = get_param("host", Struct.Domain, required=True)
    port = get_param("port", Struct.Int, required=True)
    username = get_param("username", Struct.Email, required=True)
    use_tls = get_param("use_tls", Struct.Bool, default=False)

    profile = current_app.mongodb_conn.Profile.\
        find_one_by_open_id(g.curr_user["open_id"])
    if not profile:
        raise ProfileNotFound
    profile["host"] = host
    profile["port"] = port
    profile["username"] = username
    profile["use_tls"] = use_tls
    profile.save()
    return output_profile(profile)
Exemplo n.º 12
0
def admin_update_comment_extension():
    allowed_origins = get_param('allowed_origins', )
    title = get_param('title', )
    style = get_param('style', )
    thumbnail = get_param('thumbnail', )
    require_login = get_param('require_login', )

    # print data
    comment_extension = _get_current_comment_extension()
    comment_extension['allowed_origins'] = allowed_origins
    comment_extension['title'] = title
    comment_extension['style'] = style
    comment_extension['thumbnail'] = thumbnail
    comment_extension['require_login'] = require_login
    comment_extension.save()

    return output_extension(comment_extension)
Exemplo n.º 13
0
def admin_update_comment_extension():
    allowed_origins = get_param('allowed_origins', )
    title = get_param('title', )
    style = get_param('style', )
    thumbnail = get_param('thumbnail', )
    require_login = get_param('require_login', )

    # print data
    comment_extension = _get_current_comment_extension()
    comment_extension['allowed_origins'] = allowed_origins
    comment_extension['title'] = title
    comment_extension['style'] = style
    comment_extension['thumbnail'] = thumbnail
    comment_extension['require_login'] = require_login
    comment_extension.save()

    return output_extension(comment_extension)
Exemplo n.º 14
0
def visit_add_comment(group_key):
    content = get_param('content', validator=Struct.Text, required=True)
    author_id = get_param('author_id')
    author_token = get_param('author_token')

    # todo
    # verify member
    if not author_id:
        author_id = _get_default_author_id()
        anonymous_author = True
    else:
        anonymous_author = False

    comment_extension = _get_current_comment_extension()

    def limit_comments(max_comment, min_time):
        comments = current_app.mongodb_conn.\
            Comment.find_by_gkey_eid_aid(group_key,
                                         comment_extension['_id'],
                                         author_id,
                                         max_comment)

        _comm_cursor = comments.skip(max_comment-1)
        _comm = next(_comm_cursor, None)

        if current_app.debug:
            min_time = 60
        if _comm:
            if now() - _comm['creation'] < min_time:
                raise RequestBlocked("overrun")

    limit_comments(5, 3600)

    comment_group = _visit_get_comment_group(group_key)

    comment = current_app.mongodb_conn.Comment()
    comment['content'] = content
    comment['anonymous'] = anonymous_author
    comment['author_id'] = author_id
    comment['extension_id'] = comment_extension['_id']
    comment['group_id'] = comment_group['_id']
    comment['group_key'] = unicode(group_key)
    comment.save()

    return output_comment(comment, author_id)
Exemplo n.º 15
0
def visit_add_comment(group_key):
    content = get_param('content', validator=Struct.Text, required=True)
    author_id = get_param('author_id')
    author_token = get_param('author_token')

    # todo
    # verify member
    if not author_id:
        author_id = _get_default_author_id()
        anonymous_author = True
    else:
        anonymous_author = False

    comment_extension = _get_current_comment_extension()

    def limit_comments(max_comment, min_time):
        comments = current_app.mongodb_conn.\
            Comment.find_by_gkey_eid_aid(group_key,
                                         comment_extension['_id'],
                                         author_id,
                                         max_comment)

        _comm_cursor = comments.skip(max_comment - 1)
        _comm = next(_comm_cursor, None)

        if current_app.debug:
            min_time = 60
        if _comm:
            if now() - _comm['creation'] < min_time:
                raise RequestBlocked("overrun")

    limit_comments(5, 3600)

    comment_group = _visit_get_comment_group(group_key)

    comment = current_app.mongodb_conn.Comment()
    comment['content'] = content
    comment['anonymous'] = anonymous_author
    comment['author_id'] = author_id
    comment['extension_id'] = comment_extension['_id']
    comment['group_id'] = comment_group['_id']
    comment['group_key'] = unicode(group_key)
    comment.save()

    return output_comment(comment, author_id)
Exemplo n.º 16
0
def register():
    captcha = get_param('captcha', Struct.Attr, True)
    login = get_param('login', Struct.Login, True)
    passwd = get_param('passwd', Struct.Pwd, True)
    slug = get_param('slug', Struct.Attr, True)
    meta = get_param('meta', Struct.Dict, default={})

    login = login.lower()
    slug = process_slug(slug)

    User = current_app.mongodb.User

    user = User.find_one_by_login(login)
    if user is not None:
        raise UserLoginOccupied

    if not check_captcha(CAPTCHA_REGISTER, login, captcha):
        raise UserCaptchaError

    if User.find_one_by_slug(slug) is not None:
        raise UserNameOccupied

    del_captcha(CAPTCHA_REGISTER, login)

    user = User()
    user['login'] = login
    user['slug'] = slug
    user['meta'] = meta
    user['password_hash'] = generate_hashed_password(passwd)
    user['status'] = User.STATUS_ACTIVATED
    user.save()

    token = generate_token({
        'user_id': str(user['_id']),
        'sha': get_user_hmac_sha(user),
    })

    return {
        'login': user['login'],
        'slug': user['slug'],
        'token': token,
        'id': user['_id'],
        'updated': user['updated'],
        'status': user['status'],
    }
Exemplo n.º 17
0
def send_test_post(post_id):
    Struct.ObjectId(post_id)
    test_email = get_param('test_mail', Struct.Email, required=True)
    password = get_param('password', Struct.Pwd, required=True)

    profile = current_app.mongodb_conn.Profile.\
        find_one_by_open_id(g.curr_user["open_id"])
    if not profile:
        raise ProfileNotFound

    post = current_app.mongodb_conn.Post.\
        find_one_by_id_and_open_id(post_id, g.curr_user["open_id"])
    if not post:
        raise PostNotFound

    _send_mail(post, profile, password, test_email)

    return output_post(post)
Exemplo n.º 18
0
def send_test_post(post_id):
    Struct.ObjectId(post_id)
    test_email = get_param('test_mail', Struct.Email, required=True)
    password = get_param('password', Struct.Pwd, required=True)

    profile = current_app.mongodb_conn.Profile.\
        find_one_by_open_id(g.curr_user["open_id"])
    if not profile:
        raise ProfileNotFound

    post = current_app.mongodb_conn.Post.\
        find_one_by_id_and_open_id(post_id, g.curr_user["open_id"])
    if not post:
        raise PostNotFound

    _send_mail(post, profile, password, test_email)

    return output_post(post)
Exemplo n.º 19
0
def recovery():
    captcha = get_param('captcha', Struct.Attr, True)
    login = get_param('login', Struct.Login, True)
    passwd = get_param('passwd', Struct.Pwd, True)

    user = helper_get_user_by_login(login)
    if not check_captcha(CAPTCHA_RECOVERY, user['login'], captcha):
        raise UserCaptchaError

    del_captcha(CAPTCHA_RECOVERY, user['login'])

    new_hash = generate_hashed_password(passwd)
    user['password_hash'] = new_hash
    user.save()

    return {
        'id': user['_id'],
        'updated': user['updated'],
    }
Exemplo n.º 20
0
def recovery_captcha():
    login = get_param('login', Struct.Login, True)
    locale = get_param('locale', Struct.Attr)

    user = helper_get_user_by_login(login)

    expires_in = current_app.config.get('RESET_PWD_EXPIRATION')
    captcha = set_captcha(CAPTCHA_RECOVERY, user['login'], expires_in, 24)

    # email
    helper_send_recovery_email(user, captcha, expires_in, locale)

    if current_app.debug is True:
        recovered = captcha
    else:
        recovered = True

    return {
        'login': user['login'],
        'recovered': recovered,
    }
Exemplo n.º 21
0
def generate_coupon_code():
    text = get_param('text', Struct.Attr, True)
    url = get_param('url', Struct.Url, True)
    logo = get_param('logo', Struct.Url)
    item = get_param('item', Struct.Dict)

    store = g.store

    if not store['allow_tpwd']:
        return {
            'code': False,
            'msg': store['tpwd_msg'],
        }

    taoke = connect_taoke()
    converted_url = _convert_url_pid(taoke, store['pid'], url, item)
    to_url = converted_url or url

    try:
        code = taoke.create_code(text=text, url=to_url, logo=logo)
    except Exception as e:
        raise StoreCouponGenerateFailed(e)

    current_app.sa_mod.record_customer()

    if current_app.debug:
        print 'url:', url
        print 'converted_url:', converted_url
        print item.get('id')

    if converted_url or store['default']:
        msg = store['tpwd_msg']
    else:
        msg = u'{}~'.format(store['tpwd_msg'])

    return {
        'code': code,
        'msg': msg,
        'converted': bool(converted_url),
    }
Exemplo n.º 22
0
def login():
    login = get_param('login', Struct.Login, True)
    passwd = get_param('passwd', Struct.Pwd, True)

    user = helper_get_user_by_login(login)

    pass_checked = check_hashed_password(str(user['password_hash']), passwd)
    if pass_checked is not True:
        raise UserWrongPassword

    token = generate_token({
        'user_id': str(user['_id']),
        'sha': get_user_hmac_sha(user),
    })

    return {
        'id': user['_id'],
        'login': user['login'],
        'slug': user['slug'],
        'updated': user['updated'],
        'status': user['status'],
        'token': token
    }
Exemplo n.º 23
0
def send_post(post_id):
    Struct.ObjectId(post_id)
    roles = get_param('selected_roles', Struct.List, required=True)
    password = get_param('password', Struct.Pwd, required=True)

    profile = current_app.mongodb_conn.Profile.\
        find_one_by_open_id(g.curr_user["open_id"])
    if not profile:
        raise ProfileNotFound

    post = current_app.mongodb_conn.Post.\
        find_one_by_id_and_open_id(post_id, g.curr_user["open_id"])
    if not post:
        raise PostNotFound

    to = []
    for role in roles:
        to.extend(_get_member_email_by_role(role))

    if to:
        _send_mail(post, profile, password, to)

    return output_post(post)
Exemplo n.º 24
0
def send_post(post_id):
    Struct.ObjectId(post_id)
    roles = get_param('selected_roles', Struct.List, required=True)
    password = get_param('password', Struct.Pwd, required=True)

    profile = current_app.mongodb_conn.Profile.\
        find_one_by_open_id(g.curr_user["open_id"])
    if not profile:
        raise ProfileNotFound

    post = current_app.mongodb_conn.Post.\
        find_one_by_id_and_open_id(post_id, g.curr_user["open_id"])
    if not post:
        raise PostNotFound

    to = []
    for role in roles:
        to.extend(_get_member_email_by_role(role))

    if to:
        _send_mail(post, profile, password, to)

    return output_post(post)
Exemplo n.º 25
0
def update_password():
    passwd = get_param('passwd', Struct.Pwd, True)
    old_passwd = get_param('old_passwd', Struct.Pwd, True)

    user = g.user
    pass_checked = check_hashed_password(str(user['password_hash']),
                                         old_passwd)
    if pass_checked is not True:
        raise UserWrongPassword

    user['password_hash'] = generate_hashed_password(passwd)
    user.save()

    token = generate_token({
        'user_id': str(user['_id']),
        'sha': get_user_hmac_sha(user),
    })

    return {
        'id': user['_id'],
        'token': token,
        'updated': user['updated'],
    }
Exemplo n.º 26
0
def query_view_contents(app_id):
    attrs = get_param('attrs', list, False, [])
    content_type = get_param('content_type', unicode, default=u'')
    sortby = get_param('sortby', list, False, [])
    perpage = get_param('perpage', int, False, 1)
    paged = get_param('paged', int, False, 0)
    with_content = get_param('with_content', bool, default=False)
    term = get_param('term')
    tag = get_param('tag')

    theme_meta = g.curr_app['theme_meta']
    theme_opts = theme_meta.get('options', {})

    # set default params
    if not sortby:
        sortby = theme_opts.get('sortby', 'updated')

    if not perpage:
        perpage = theme_opts.get('perpage')

    perpage, paged = _safe_paging(perpage, paged)

    # position
    limit = perpage
    offset = max(perpage * (paged - 1), 0)

    # query content files
    results, total_count = query_by_files(attrs=attrs,
                                          content_type=content_type,
                                          term=term,
                                          tag=tag,
                                          offset=offset,
                                          limit=limit,
                                          sortby=sortby)
    pages = []
    for p in results:
        p_content = p.get('content', u'')
        p = parse_page_metas(p)
        if with_content:
            p['content'] = parse_page_content(p_content)
        pages.append(p)
    run_hook('get_pages', pages=pages, current_page_id=None)

    max_pages = max(int(math.ceil(total_count / float(perpage))), 1)

    return output_result(contents=pages, perpage=perpage, paged=paged,
                         total_pages=max_pages, total_count=total_count)
Exemplo n.º 27
0
def admin_remove_comments(group_id):
    Struct.ObjectId(group_id, 'group_id')

    def deal_comments(comment_id, group_id):
        Struct.ObjectId(comment_id, 'comment_id')
        comment = _admin_get_comment(comment_id, group_id)
        comment.delete()
        return output_comment(comment)

    comment_ids = get_param('comment_ids', Struct.List)

    return {
        "deleted":
        [deal_comments(comment_id, group_id) for comment_id in comment_ids],
    }
Exemplo n.º 28
0
def register_captcha():
    login = get_param('login', Struct.Login, True)
    locale = get_param('locale', Struct.Attr)

    login = login.lower()
    user = current_app.mongodb.User.find_one_by_login(login)
    if user is not None:
        raise UserLoginOccupied

    expires_in = current_app.config.get('REGISTER_EXPIRATION')
    captcha = set_captcha(CAPTCHA_REGISTER, login, expires_in)

    # email
    helper_send_register_email(login, captcha, expires_in, locale)

    if current_app.debug is True:
        checked = captcha
    else:
        checked = True

    return {
        'login': login,
        'checked': checked,
    }
Exemplo n.º 29
0
def search_commodities():
    paged = get_param('paged', Struct.Int, default=1)
    perpage = get_param('perpage', Struct.Int, default=60)
    keywords = get_param('keywords', Struct.List, default=[])
    timestamp = parse_int(get_args('timestamp'))
    categories = get_args('categories')

    store = g.store

    cids = _convert_categories(categories)

    paged = parse_int(paged, 1, 1)
    perpage = parse_int(perpage, 1, 1)

    if not keywords:
        return []
    items = current_app.mongodb.\
        Commodity.search(keywords, cids, timestamp, store['sort_type'])
    p = make_paginator(items, paged, perpage)

    return attach_extend(
        [output_commodity(item) for item in items],
        {'_more': p.has_next, '_count': p.count}
    )
Exemplo n.º 30
0
def admin_remove_comments(group_id):
    Struct.ObjectId(group_id, 'group_id')

    def deal_comments(comment_id, group_id):
        Struct.ObjectId(comment_id, 'comment_id')
        comment = _admin_get_comment(comment_id, group_id)
        comment.delete()
        return output_comment(comment)

    comment_ids = get_param('comment_ids', Struct.List)

    return {
        "deleted": [deal_comments(comment_id, group_id)
                    for comment_id in comment_ids],
    }