Beispiel #1
0
def refresh_token(device_type):
    if 'token' in session:
        '''認証済みの場合は有効性チェック'''
        my_api = sw.MyApi(
            sw.ApiClient(host=app.config.get('API_HOST'),
                         header_name='Authorization',
                         header_value='JWT %s' % session['token']))
        try:
            my_api.my_profile_get()
        except ApiException as err:
            '''有効でない場合はトークンを破棄'''
            if err.status == 401:
                session.pop('token')
            else:
                return render_template('plain.html', message='server error')
    '''セッションにトークンがない場合は匿名トークンを発行'''
    if 'token' not in session:
        auth_api = sw.AuthApi(sw.ApiClient(app.config.get('API_HOST')))
        auth = sw.Authenticate()
        auth.key = 'anonymous'
        auth.secret = 'anonymous'
        auth.device = device_type
        auth.trid = check_trid(cookies=request.cookies)
        result = auth_api.authenticate_post(authenticate=auth)
        session['token'] = result.access_token
    g.api = sw.ApiClient(host=app.config.get('API_HOST'),
                         header_name='Authorization',
                         header_value='JWT %s' % session['token'])
Beispiel #2
0
def profile_image() -> Response:
    """プロフィール編集"""
    image_form = ImageForm(request.form)
    if image_form.csrf_token.errors:
        abort(401)
    if 'image' in request.files and request.files['image']:
        image = request.files['image']
        if image.content_length < 1048577:  # 画像は1MB制限
            file_name = utils.upload_profile_image_to_tmp(file=image)
            if file_name:
                session['profile_image'] = file_name
            else:
                flash('画像ファイルを選択してください', category='error')
        else:
            flash('アップロード可能な画像サイズは1MBまでです', category='error')
    elif 'profile_image' in session:
        if 'width' in request.form and 'height' in request.form \
                and 'x' in request.form and 'y' in request.form:
            crop_size = (int(request.form['x']), int(request.form['y']),
                         (int(request.form['x']) + int(request.form['width'])),
                         (int(request.form['y']) +
                          int(request.form['height'])))
            file_path = utils.upload_profile_image_to_s3(
                src_file_name=session['profile_image'], crop_size=crop_size)
            my_api = sw.MyApi(api_client=g.api)
            profile_ = my_api.my_profile_get()
            profile_.image = file_path
            my_api.my_profile_put(user=profile_)
            flash('画像をアップロードしました', category='info')
        else:
            utils.delete_profile_tmp_image(
                src_file_name=session['profile_image'])
        session.pop('profile_image')
    return redirect_(url_for('front.profile_edit'))
Beispiel #3
0
def user_support_project_ids():
    """
    ログイン中のユーザのサポートしているプロジェクト一覧を取得します
    サポーターの判定などに利用できます。
    """
    my_api = sw.MyApi(api_client=g.api)
    supports = my_api.my_supports_get()
    return set([support.project_id for support in supports])
Beispiel #4
0
def api_my_card():
    if not current_user.is_authenticated:
        return jsonify({'login': False})
    my_api = sw.MyApi(g.api)
    cards = my_api.my_cards_get()
    for card in cards:
        return jsonify({'login': True, 'card': card.to_dict()})
    return jsonify({'login': True})
Beispiel #5
0
def api_email(category):
    if not current_user.is_authenticated:
        return jsonify({'login': False})
    mail_magazine = sw.MailMagazine()
    mail_magazine.category = category
    mail_magazine.checked = True
    my_api = sw.MyApi(g.api)
    mail = my_api.my_email_put(mail_magazine=mail_magazine)
    return jsonify({'login': True, category: mail.to_dict()})
Beispiel #6
0
def login_user_(access_token):
    session['token'] = access_token
    my_api = sw.MyApi(
        sw.ApiClient(host=current_app.config.get('API_HOST'),
                     header_name='Authorization',
                     header_value='JWT %s' % session['token']))
    login_user(LoginUser(profile=my_api.my_profile_get()))
    # ログイン時にアンデリの通知カウントをリセットする
    if 'notify_count' in session:
        session.pop('notify_count')
Beispiel #7
0
def load_user(user_id=None):
    try:
        if 'api' not in g:
            g.api = sw.ApiClient(host=app.config.get('API_HOST'))
        my_api = sw.MyApi(api_client=g.api)
        user = LoginUser(my_api.my_profile_get())
        if str(user.id) == user_id:
            return user
        else:
            return None
    except (HTTPError, URLError, ApiException) as detail:
        print(detail)
        return None
Beispiel #8
0
def profile_support() -> Response:
    """プロフィール"""
    my_api = sw.MyApi(api_client=g.api)
    profile_ = my_api.my_profile_get()
    supports = my_api.my_supports_get()
    for support in supports:
        project_api = sw.ProjectApi(api_client=g.api)
        project_ = project_api.projects_project_id_get(
            project_id=support.project_id)
        if project_:
            support.project_title = project_.title
            support.project_image = project_.image
            support.project_status = project_.public_status
            support.project_status_text = project_status_text(project_)
            support.project_end_time = project_.end_time
        item_ = project_api.projects_project_id_items_item_id_get(
            project_id=support.project_id, item_id=support.item_id)
        if item_:
            support.item_name = item_.name
        if item_.shipping:  # 配送ありの場合はお届け先を表示
            shipping = my_api.my_shippings_support_id_get(
                support_id=support.support_id)
            if shipping.zipcode:
                from web.modules.form import states
                pref_name = [
                    state[1] for state in states if state[0] == shipping.pref
                ]
                if pref_name and len(pref_name) > 0:
                    shipping.pref_name = pref_name[0]
                zipcode = shipping.zipcode
                if shipping.zipcode and len(shipping.zipcode) == 7:
                    zipcode = shipping.zipcode[:3] + '-' + shipping.zipcode[3:]
                support.shipping_address = '%s %s %s %s %s' % (
                    zipcode, shipping.pref_name, shipping.town,
                    shipping.address, shipping.building)
        if support.status == 1:  # 決済未完了の場合は支払い情報を表示
            order = my_api.my_orders_order_id_get(order_id=support.order_id)
            if order:
                if order.cust_id:
                    support.payment_code = order.cust_id + '-' + order.conf_no
                if order.receipt_no:
                    support.payment_code = order.receipt_no + '-' + order.conf_no
                    from web.modules.form import cvs_code
                    support.payment_cvs_name = [
                        code[1] for code in cvs_code
                        if str(code[0]) == order.cvs_code
                    ][0]
                support.payment_term = order.payment_term
    return render_template('profile_support.html',
                           profile=profile_,
                           supports=supports)
Beispiel #9
0
def api_my_address():
    if not current_user.is_authenticated:
        return jsonify({'login': False})
    my_api = sw.MyApi(g.api)
    addresses = my_api.my_addresses_get()
    for address in addresses:  # "fullname"を"first_name"と"last_name"に分割する
        address_data = address.to_dict()
        splitted_fullname = address.full_name.split(' ', 1)
        address_data['last_name'] = splitted_fullname[0] if len(
            splitted_fullname) > 1 else address.full_name
        address_data['first_name'] = splitted_fullname[1] if len(
            splitted_fullname) > 1 else None
        return jsonify({'login': True, 'address': address_data})
    return jsonify({'login': True})
Beispiel #10
0
def api_favorite(creator_id: int):
    if not current_user.is_authenticated:
        return jsonify({'login': False})
    my_api = sw.MyApi(g.api)
    if 'action' in request.args:
        favorite = sw.Favorite()
        favorite.creator_id = creator_id
        favorite.checked = (request.args['action'] == 'on')
        favorite = my_api.my_favorites_put(favorite=favorite)
        return jsonify({'login': True, 'favorite': favorite.to_dict()})
    else:
        favorite = my_api.my_favorites_creator_id_get(creator_id=creator_id)
        if favorite.creator_id:
            return jsonify({'login': True, 'favorite': favorite.to_dict()})
    return jsonify({'login': True})
Beispiel #11
0
def profile_favorite() -> Response:
    """お気に入り"""
    my_api = sw.MyApi(api_client=g.api)
    profile_ = my_api.my_profile_get()
    favorites = my_api.my_favorites_get()
    for favorite in favorites:
        project_api = sw.ProjectApi(api_client=g.api)
        projects_ = project_api.projects_get(creator=favorite.creator_id)
        for project_ in projects_:
            favorite.project_id = project_.id
            favorite.project_title = project_.title
            favorite.project_image = project_.image
            favorite.project_summary = project_.summary
    return render_template('profile_favorite.html',
                           profile=profile_,
                           favorites=favorites)
Beispiel #12
0
def get_project_items(project: sw.Project) -> list:
    """
    アイテムの一覧を取得する。サポート可能かどうかの判定も一緒に行う。
    :param project: プロジェクト情報
    :return: アイテム一覧
    """
    today = datetime.today()
    my_api = sw.MyApi(api_client=g.api)
    supports = my_api.my_supports_get()
    project_api = sw.ProjectApi(api_client=g.api)
    items = project_api.projects_project_id_items_get(project_id=project.id)
    for item in items:
        if project.public_status in (1, 3, 4):  # 1:公開前,2:公開中(募集終了),3:非公開
            item.error_message = '募集期間外'
        elif today < project.start_time or project.end_time < today:
            item.error_message = '募集期間外'
        elif -1 < item.limit <= item.expected_supports:
            item.error_message = '在庫切れ'
        elif -1 < item.limit_user <= len(
            [support for support in supports if support.item_id == item.id]):
            item.error_message = '購入制限超え'
    return items
Beispiel #13
0
def profile_edit() -> Response:
    """プロフィール編集"""
    my_api = sw.MyApi(api_client=g.api)
    profile_ = my_api.my_profile_get()
    basic_form = ProfileBasicForm(request.form)
    mail_form = MailMagazineForm(request.form)
    creator_form = CreatorProfileForm(request.form)
    password_form = CreatorPasswordForm(request.form)
    if request.method == 'POST':
        if basic_form.basic_submit.data and basic_form.validate_on_submit():
            profile_.nickname = basic_form.nickname.data
            profile_.introduction = basic_form.profile.data
            my_api.my_profile_put(user=profile_)
            flash('プロフィールを更新しました', category='info')
        elif mail_form.mail_submit.data and mail_form.validate_on_submit():
            for category in ['news', 'project', 'favorite']:
                mail_magazine = sw.MailMagazine()
                mail_magazine.category = category
                mail_magazine.checked = mail_form[category].data
                my_api.my_email_put(mail_magazine=mail_magazine)
            flash('メルマガ設定を更新しました', category='info')
        elif creator_form.creator_submit.data and creator_form.validate_on_submit(
        ):
            profile_.email = creator_form.email.data
            profile_.facebook = creator_form.facebook.data
            profile_.twitter = creator_form.twitter.data
            profile_.link = creator_form.link.data
            try:
                my_api.my_profile_put(user=profile_)
                flash('クリエイター情報を更新しました', category='info')
            except ApiException as ex:
                current_app.logger.warning('creator profile error: %s', ex)
                flash('クリエイター情報の更新に失敗しました', category='error')
        elif password_form.password_submit.data and password_form.validate_on_submit(
        ):
            # TODO パスワードの更新
            print(password_form.data)
            flash('パスワードを更新しました', category='info')
        utils.flash_errors(basic_form)
        utils.flash_errors(mail_form)
        utils.flash_errors(creator_form)
        utils.flash_errors(password_form)
        return redirect_(url_for('front.profile_edit'))
    else:
        if 'profile_image' in session and utils.profile_tmp_image_is_not_exists(
                session['profile_image']):
            utils.delete_profile_tmp_image(session['profile_image'])
            session.pop('profile_image')
        profile_ = my_api.my_profile_get()
        basic_form.nickname.data = profile_.nickname
        basic_form.profile.data = profile_.introduction
        emails_ = my_api.my_email_get()
        for email in emails_:
            mail_form[email.category].data = email.checked
        creator_form.email.data = profile_.email
        creator_form.facebook.data = profile_.facebook
        creator_form.twitter.data = profile_.twitter
        creator_form.link.data = profile_.link
    return render_template('profile_edit.html',
                           profile=profile_,
                           image_form=ImageForm(),
                           basic_form=basic_form,
                           mail_form=mail_form,
                           creator_form=creator_form,
                           password_form=password_form)