示例#1
0
def tournament_register(tournament_id, register_flag):
  tournament_db = model.Tournament.get_by_id(tournament_id)
  if not tournament_db:
    flask.abort(404)

  # TODO: Check if it's open for registrations first - george -> should we add an [open_for_registration] field ???

  user_tournament_db = model.UserTournament.get_or_insert(
      str(auth.current_user_id()),
      parent=tournament_db.key,
      tournament_key=tournament_db.key,
      user_key=auth.current_user_key(),
  )

  body = 'name: %s\nusername: %s\nemail: %s' % (
      auth.current_user_db().name,
      auth.current_user_db().username,
      auth.current_user_db().email,
  )
  creator_user_db = model.User.get_by_id(tournament_db.user_key.id())

  if register_flag == 'register':
    user_tournament_db.put()
    flask.flash('Awesome! You are in..', category='success')
    # how to send an email to -> creator_user_db.email
    # task.send_mail_notification('%s entered tournament %s' % (auth.current_user_db().name, tournament_db.name), body)
  elif register_flag == 'unregister':
    user_tournament_db.key.delete()
    flask.flash('Bummer! You are out..', category='info')
    # how to send an email to -> creator_user_db.email
    # task.send_mail_notification('%s left tournament %s' % (auth.current_user_db().name, tournament_db.name), body)

  return flask.redirect(flask.url_for('tournament_view', tournament_id=tournament_id))
示例#2
0
def feedback():
  if not config.CONFIG_DB.feedback_email:
    return flask.abort(418)

  form = FeedbackForm(obj=auth.current_user_db())
  if form.validate_on_submit():
    mail.send_mail(
        sender=config.CONFIG_DB.feedback_email,
        to=config.CONFIG_DB.feedback_email,
        subject='[%s] %s' % (
            config.CONFIG_DB.brand_name,
            form.subject.data,
          ),
        reply_to=form.email.data or config.CONFIG_DB.feedback_email,
        body='%s\n\n%s' % (form.message.data, form.email.data)
      )
    flask.flash('Thank you for your feedback!', category='success')
    return flask.redirect(flask.url_for('countdown'))
  if not form.errors and auth.current_user_id() > 0:
    form.email.data = auth.current_user_db().email

  return flask.render_template(
      'feedback.html',
      title='Feedback',
      html_class='feedback',
      form=form,
    )
示例#3
0
def profile():
  user_db = auth.current_user_db()
  form = ProfileUpdateForm(obj=user_db)

  if form.validate_on_submit():
    email = form.email.data
    if email and not user_db.is_email_available(email, user_db.key):
      form.email.errors.append('This email is already taken.')

    if not form.errors:
      send_verification = not user_db.token or user_db.email != email
      form.populate_obj(user_db)
      if send_verification:
        user_db.verified = False
        task.verify_email_notification(user_db)
      user_db.put()
      return flask.redirect(flask.url_for('welcome'))

  if flask.request.path.startswith('/_s/'):
    return util.jsonify_model_db(user_db)

  return flask.render_template(
      'profile.html',
      title=user_db.name,
      html_class='profile',
      form=form,
      user_db=user_db,
      has_json=True,
    )
示例#4
0
文件: filter.py 项目: manshar/birwaz
def filter_update(filter_id=''):
  if filter_id:
    filter_db = model.Filter.get_by_id(filter_id)
  else:
    filter_db = model.Filter(
      id='{}-{}'.format(util.param('filter_value'), util.param('filter_value')),
      label='')

  if not filter_db or not auth.current_user_db().admin:
    return flask.abort(404)

  form = FilterUpdateForm(obj=filter_db)
  if form.validate_on_submit():
    form.populate_obj(filter_db)
    filter_db.put()
    return flask.redirect(flask.url_for('admin_filter_list'))

  return flask.render_template(
    'filter/filter_update.html',
    html_class='filter-update',
    title='%s' % (filter_db.label or 'فلتر جديد'),
    filter_db=filter_db,
    form=form,
    api_url=flask.url_for('api.filter', key=filter_db.key.urlsafe()) if filter_db.key else '',
  )
示例#5
0
def inject_user():
    """Injects 'user' variable into jinja template, so it can be passed into angular. See base.html"""
    user = False
    if auth.is_logged_in():
        user = auth.current_user_db().to_dict(
            include=User.get_private_properties())
    return {'user': user}
示例#6
0
def profile():
  form = ProfileUpdateForm()
  user_db = auth.current_user_db()
  if form.validate_on_submit():
    user_db.name = form.name.data.strip()
    user_db.email = form.email.data.strip().lower()
    user_db.locale = form.locale.data.strip()
    user_db.put()
    return flask.redirect(flask.url_for(
        'set_locale', locale=user_db.locale, next=flask.url_for('welcome')
      ))

  if not form.errors:
    form.name.data = user_db.name
    form.email.data = user_db.email or ''
    form.locale.data = user_db.locale or auth.get_locale()

  if flask.request.path.startswith('/_s/'):
    return util.jsonify_model_db(user_db)

  return flask.render_template(
      'profile.html',
      title=_('Profile'),
      html_class='profile',
      form=form,
      user_db=user_db,
    )
示例#7
0
def profile():
  user_db = auth.current_user_db()
  form = ProfileUpdateForm(obj=user_db)

  if form.validate_on_submit():
    send_verification = not user_db.token or user_db.email != form.email.data
    form.populate_obj(user_db)
    if send_verification:
      user_db.verified = False
      task.verify_email_notification(user_db)
    user_db.put()
    return flask.redirect(flask.url_for(
        'set_locale', locale=user_db.locale, next=flask.url_for('welcome')
      ))

  if flask.request.path.startswith('/_s/'):
    return util.jsonify_model_db(user_db)

  return flask.render_template(
      'profile.html',
      title=user_db.name,
      html_class='profile',
      form=form,
      user_db=user_db,
      has_json=True,
    )
示例#8
0
 def delete(self, key):
     resource_db = ndb.Key(urlsafe=key).get()
     if not resource_db or (resource_db.user_key != auth.current_user_key()
                            and not auth.current_user_db().admin):
         helpers.make_not_found_exception('Resource %s not found' % key)
     delete_resource_key(resource_db.key)
     return helpers.make_response(resource_db, model.Resource.FIELDS)
示例#9
0
def welcome():
    user_db = auth.current_user_db()
    today = datetime.date.today()
    week_start = today - timedelta(days=today.weekday())
    week_end = week_start + timedelta(days=6)

    # list_keys = list_query.fetch(keys_only=True)  # maybe put a limit here.
    #
    # list_keys = random.sample(list_keys, 20)
    # issue_dbs = [list_key.get() for list_key in list_keys]
    user_issues = []
    if user_db is not None:
        if user_db.series_list:
            for serie in user_db.series_list:
                serie_6_issues = Issue.query(Issue.serie == serie).order(-Issue.date).fetch(limit=6)
                user_issues += serie_6_issues
            # if user_db.buy_list:
            #     current_week += Issue.query(Issue.key.IN(user_db.buy_list))
            #
            # next_weeks = Issue.query(
            #     ndb.AND(Issue.serie.IN(user_db.series_list),
            #             Issue.date > week_end
            #             )
            # ).order(Issue.date).fetch()
    # for issue in user_issues:
    #     print(issue.title.encode())
    return flask.render_template('welcome.html',
                                 html_class='welcome',
                                 user_db=user_db,
                                 user_issues=user_issues,
                                 )
示例#10
0
文件: views.py 项目: gmist/solostyle
def index():
    from main import FeedbackForm
    form = FeedbackForm()
    if form.validate_on_submit():
        feedback_email = model.Config.get_master_db().feedback_email
        try:
            if feedback_email:
                mail.send_mail(
                    sender=feedback_email,
                    to=feedback_email,
                    subject=u'[%s] - cообщение от %s' % (
                        model.Config.get_master_db().brand_name,
                        form.name.data,
                      ),
                    reply_to=form.email.data or feedback_email,
                    body=u'%s\n\n%s\n%s' % (form.feedback.data, form.email.data, form.contact.data)
                )
        except:
            pass
        flash(u'Спасибо за сообщение! Мы свяжемся с Вами в ближайшее время.', category='success')
        return redirect(url_for('contacts.index'))
    if not form.errors and auth.current_user_id() > 0:
        form.email.data = auth.current_user_db().email
    contacts = Contact.query(Contact.is_public == True).order(Contact.order_id)
    return render_template(
        'contacts/index.html',
        html_class='contacts_page',
        contacts=contacts,
        form=form
    )
示例#11
0
def user_forgot(token=None):
  if not config.CONFIG_DB.has_email_authentication:
    flask.abort(418)

  form = auth.form_with_recaptcha(UserForgotForm(obj=auth.current_user_db()))
  if form.validate_on_submit():
    cache.bump_auth_attempt()
    email = form.email.data
    user_dbs, cursors = util.get_dbs(
        model.User.query(), email=email, active=True, limit=2,
      )
    count = len(user_dbs)
    if count == 1:
      task.reset_password_notification(user_dbs[0])
      return flask.redirect(flask.url_for('welcome'))
    elif count == 0:
      form.email.errors.append('This email was not found')
    elif count == 2:
      task.email_conflict_notification(email)
      form.email.errors.append(
          '''We are sorry but it looks like there is a conflict with your
          account. Our support team is already informed and we will get back to
          you as soon as possible.'''
        )

  if form.errors:
    cache.bump_auth_attempt()

  return flask.render_template(
      'user/user_forgot.html',
      title=_('Forgot Password?'),
      html_class='user-forgot',
      form=form,
    )
示例#12
0
def profile_password():
  if not config.CONFIG_DB.has_email_authentication:
    flask.abort(418)
  user_db = auth.current_user_db()
  form = ProfilePasswordForm(obj=user_db)

  if form.validate_on_submit():
    errors = False
    old_password = form.old_password.data
    new_password = form.new_password.data
    if new_password or old_password:
      if user_db.password_hash:
        if util.password_hash(user_db, old_password) != user_db.password_hash:
          form.old_password.errors.append(_('Invalid current password'))
          errors = True
      if not errors and old_password and not new_password:
        form.new_password.errors.append(_('This field is required.'))
        errors = True

      if not (form.errors or errors):
        user_db.password_hash = util.password_hash(user_db, new_password)
        flask.flash(__('Your password has been changed.'), category='success')

    if not (form.errors or errors):
      user_db.put()
      return flask.redirect(flask.url_for('profile'))

  return flask.render_template(
      'profile/profile_password.html',
      title=user_db.name,
      html_class='profile-password',
      form=form,
      user_db=user_db,
    )
示例#13
0
def profile_update():
    user_db = auth.current_user_db()
    form = ProfileUpdateForm(obj=user_db)

    if form.validate_on_submit():
        email = form.email.data
        if email and not user_db.is_email_available(email, user_db.key):
            form.email.errors.append('This email is already taken.')

        if not form.errors:
            send_verification = not user_db.token or user_db.email != email
            form.populate_obj(user_db)
            if send_verification:
                user_db.verified = False
                task.verify_email_notification(user_db)
            user_db.put()
            return flask.redirect(flask.url_for('profile'))

    return flask.render_template(
        'profile/profile_update.html',
        title=user_db.name,
        html_class='profile-update',
        form=form,
        user_db=user_db,
    )
示例#14
0
def profile():
  form = ProfileUpdateForm()
  user_db = auth.current_user_db()
  if form.validate_on_submit():
    user_db.name = form.name.data.strip()
    user_db.email = form.email.data.strip().lower()
    user_db.locale = form.locale.data.strip()
    user_db.put()
    return flask.redirect(flask.url_for(
        'set_locale', locale=user_db.locale, next=flask.url_for('welcome')
      ))

  if not form.errors:
    form.name.data = user_db.name
    form.email.data = user_db.email or ''
    form.locale.data = user_db.locale or auth.get_locale()

  if flask.request.path.startswith('/_s/'):
    return util.jsonify_model_db(user_db)

  return flask.render_template(
      'profile.html',
      title=_('Profile'),
      html_class='profile',
      form=form,
      user_db=user_db,
    )
示例#15
0
def update_weekly():
    results = model.weekly.query(
        model.weekly.user_key == auth.current_user_key()).fetch(1)

    today = datetime.date(datetime.now())
    week_num = today.strftime("%U")
    year_num = today.strftime("%G")

    count = 0
    for result in results:
        count += 1

    if count < 1:
        user_db = auth.current_user_db()
        name = user_db.name
        weekly_db = model.weekly(user_key=auth.current_user_key(),
                                 player_name=name,
                                 week=week_num,
                                 year=year_num)
    else:
        weekly_db = result
        if (weekly_db.week != week_num) or (weekly_db.year != year_num):
            weekly_db.wins = 0
            weekly_db.week = week_num
            weekly_db.year = year_num

    weekly_db.wins += 1

    weekly_db.put()
    return "success"
示例#16
0
def update_weekly():	
	results = model.weekly.query(model.weekly.user_key == auth.current_user_key()).fetch(1)	
	
	today=datetime.date(datetime.now())
	week_num = today.strftime("%U")
	year_num = today.strftime("%G")
	
	count = 0
	for result in results:
		count += 1
		
	if count < 1:
		user_db = auth.current_user_db()
		name = user_db.name
		weekly_db = model.weekly(user_key=auth.current_user_key(), player_name=name, week=week_num, year=year_num)
	else:
		weekly_db = result;
		if (weekly_db.week != week_num) or (weekly_db.year != year_num):
			weekly_db.wins = 0
			weekly_db.week = week_num
			weekly_db.year = year_num
			   
	weekly_db.wins += 1
	
	weekly_db.put()
	return "success"
示例#17
0
def profile_update():
  user_db = auth.current_user_db()
  form = ProfileUpdateForm(obj=user_db)

  if form.validate_on_submit():
    email = form.email.data
    if email and not user_db.is_email_available(email, user_db.key):
      form.email.errors.append('This email is already taken.')

    if not form.errors:
      send_verification = not user_db.token or user_db.email != email
      form.populate_obj(user_db)
      if send_verification:
        user_db.verified = False
        task.verify_email_notification(user_db)
      user_db.put()
      return flask.redirect(flask.url_for('profile'))

  return flask.render_template(
      'profile/profile_update.html',
      title=user_db.name,
      html_class='profile-update',
      form=form,
      user_db=user_db,
    )
示例#18
0
def profile_password():
  if not config.CONFIG_DB.has_email_authentication:
    flask.abort(418)
  user_db = auth.current_user_db()
  form = ProfilePasswordForm(obj=user_db)

  if form.validate_on_submit():
    errors = False
    old_password = form.old_password.data
    new_password = form.new_password.data
    if new_password or old_password:
      if user_db.password_hash:
        if util.password_hash(user_db, old_password) != user_db.password_hash:
          form.old_password.errors.append('Invalid current password')
          errors = True
      if not errors and old_password and not new_password:
        form.new_password.errors.append('This field is required.')
        errors = True

      if not (form.errors or errors):
        user_db.password_hash = util.password_hash(user_db, new_password)
        flask.flash('Your password has been changed.', category='success')

    if not (form.errors or errors):
      user_db.put()
      return flask.redirect(flask.url_for('profile'))

  return flask.render_template(
      'profile/profile_password.html',
      title=user_db.name,
      html_class='profile-password',
      form=form,
      user_db=user_db,
    )
示例#19
0
def profile():
    user_db = auth.current_user_db()
    form = ProfileUpdateForm(obj=user_db)

    if form.validate_on_submit():
        form.populate_obj(user_db)
        user_db.put()
        return flask.redirect(
            flask.url_for('set_locale',
                          locale=user_db.locale,
                          next=flask.url_for('welcome')))

        return flask.redirect(flask.url_for('welcome'))

    if flask.request.path.startswith('/_s/'):
        return util.jsonify_model_db(user_db)

    return flask.render_template(
        'profile.html',
        title=_('Profile'),
        html_class='profile',
        form=form,
        user_db=user_db,
        has_json=True,
    )
示例#20
0
def lesson(lesson_id, section_id):
    user_db = auth.current_user_db()
    if user_db.progress < lesson_id:
        return redirect(url_for('lesson', lesson_id=user_db.progress, section_id=1))
    if lesson_id > 0 and not user_db.registered:
        flash(u'Please register with your email below to access additional Lessons.')
        return redirect(url_for('welcome'))
    if request.method == 'POST':
        if answers.check(request.form, lesson_id):
            user_db.progress = lesson_id + 1
            try:
                user_db.put()
                flash(u'Congratulations! Welcome to Lesson %s.' % user_db.progress, 'success')
                return redirect(url_for('lesson', lesson_id=user_db.progress, section_id=1))
            except:
                flash(u'Something went wrong.', 'info')
                return redirect(url_for('lesson', lesson_id=lesson_id,section_id=section_id))
    lesson_db = Lesson.query(Lesson.number == lesson_id).get()
    section_dbs = Section.query(Section.lesson == lesson_id).order(Section.number)
    piece_dbs = Piece.query(Piece.lesson == lesson_id, Piece.section == section_id).order(Piece.number)
    graph_string = 'graphs/graph_' + str(lesson_id) + '_' + str(section_id)
    return render_template(
        'lesson.html',
        html_class='lesson',
        lesson=lesson_db,
        sections=section_dbs,
        pieces=piece_dbs,
        graph=graph_string + '.html',
        graph_head=graph_string + '_head.html',
        lesson_id=lesson_id,
        section_id=section_id,
        progress=user_db.progress
    )
示例#21
0
def my_profile():
    user=auth.current_user_db()
    return flask.render_template(
        'g+_templates/profile.html',
        user_db=user,
        comment_counts=len(user.comments),
        followers_count=len(user.teams),
    )
示例#22
0
def inject_user():
    """Injects 'user' variable into jinja template, so it can be passed into angular. See base.html"""
    user = False
    if auth.is_logged_in():
        user = auth.current_user_db().to_dict(include=User.get_private_properties())
    return {
        'user': user
    }
示例#23
0
 def delete(self, reply_id):
     reply_repo = ReplyRepo(reply_id)
     reply = reply_repo.reply
     if reply is None:
         abort(404)
     reply_model = reply_repo.downvote(auth.current_user_db())
     response = marshal(reply_model, reply_field)
     return get_single_result_object(response)
示例#24
0
    def get(self, key, item_key):
        item_db = ndb.Key(urlsafe=item_key).get()
        if not item_db:
            return ApiException.error(404)

        if auth.current_user_db().id() != item_db.user_id:
            return ApiException.error(403)
        return item_db.to_dict(include=Hackathon.get_public_properties())
示例#25
0
def profile():
	user_db = auth.current_user_db()

	return base_auth_response(
			'profile/profile.html',
			title=user_db.name,
			html_class='profile-view',
	)
示例#26
0
def profile():
    user_db = auth.current_user_db()

    return flask.render_template(
        'profile/profile.html',
        title=user_db.name,
        html_class='profile-view',
        user_db=user_db,
    )
示例#27
0
def cart_page():
    user_db = auth.current_user_db()
    cart = []
    if user_db.cart:
        cart = Issue.query(Issue.key.IN(
            user_db.cart)).order(-Issue.date).fetch()
    else:
        flask.abort(404)
    return flask.render_template('cart_page.html', cart=cart, user_db=user_db)
示例#28
0
def profile():
  user_db = auth.current_user_db()

  return flask.render_template(
      'profile/profile.html',
      title=user_db.name,
      html_class='profile-view',
      user_db=user_db,
    )
示例#29
0
def quiz_creator(lesson_key):
  user_db = auth.current_user_db()

  return flask.render_template(
      'quiz/quiz_update.html',
      title="Quiz Creator",
      html_class='quiz-view',
      user_db=user_db,
    )
示例#30
0
    def post(self, key, item_type,
             item_key):  # updates an existing profile item
        user_id = g.model_db.id()
        profile = Profile.get_by('user_id', user_id)
        if auth.current_user_db().id(
        ) != user_id:  # check profile belongs to current_user
            return ApiException.error(108)

        return self.update_item(profile, item_type, item_key)
示例#31
0
 def delete(self,topic_id):
     topic_repo = TopicRepo(topic_id)
     topic = topic_repo.topic
     if topic is None:
         abort(404)
     topic_model = topic_repo.downvote(auth.current_user_db())
     response = marshal(topic_model, simple_topic_field)
     notification(response['team'].replace(" ",""), 'topic_downvote', topic=response)
     return get_single_result_object(response)
示例#32
0
def quiz_creator(lesson_key):
    user_db = auth.current_user_db()

    return flask.render_template(
        'quiz/quiz_update.html',
        title="Quiz Creator",
        html_class='quiz-view',
        user_db=user_db,
    )
示例#33
0
def welcome():
    if auth.is_logged_in():
        currency_dbs, currency_cursor = model.Currency.get_dbs(
            limit=-1, order='is_crypto,name')
        transaction_dbs, transaction_cursor = model.Transaction.get_dbs(
            user_key=auth.current_user_key(), order='-date', limit=-1)

        total_profit = 0
        total_net_worth = 0

        currency_codes = []
        for transaction_db in transaction_dbs:
            total_profit += transaction_db.profit_amount_user
            total_net_worth += transaction_db.net_worth_user
            currency_codes.append(transaction_db.acquired_currency_code)

        currency_codes = list(set(currency_codes))
        price_dbs = []
        user_currency_code = auth.current_user_db().currency_key.get(
        ).code if auth.current_user_db().currency_key else 'USD'
        for currency_code in currency_codes:
            if currency_code != user_currency_code:
                price_db = model.Price.get_by(
                    'code_unique',
                    ':'.join(tuple(sorted([currency_code,
                                           user_currency_code]))))
                if price_db:
                    price_dbs.append(price_db)

        return flask.render_template(
            'welcome.html',
            html_class='welcome',
            transaction_dbs=transaction_dbs,
            total_profit=total_profit,
            total_net_worth=total_net_worth,
            currency_dbs=currency_dbs,
            price_dbs=price_dbs,
            user_currency_code=user_currency_code,
            api_url=flask.url_for('api.transaction.list'),
        )
    return flask.render_template(
        'welcome.html',
        html_class='welcome',
    )
示例#34
0
文件: pay.py 项目: georgekis/salary
def pay_list():
  pay_dbs, pay_cursor = auth.current_user_db().get_pay_dbs()

  return flask.render_template(
      'pay/pay_list.html',
      html_class='pay-list',
      title='Pay List',
      pay_dbs=pay_dbs,
      next_url=util.generate_next_url(pay_cursor),
    )
示例#35
0
文件: views.py 项目: gmist/1businka2
def user_verify(token):
    user_db = auth.current_user_db()
    if user_db.token != token:
        flask.flash("That link is either invalid or expired.", category="danger")
        return flask.redirect(flask.url_for("profile"))
    user_db.verified = True
    user_db.token = util.uuid()
    user_db.put()
    flask.flash("Hooray! Your email is now verified.", category="success")
    return flask.redirect(flask.url_for("profile"))
示例#36
0
def user_verify(token):
  user_db = auth.current_user_db()
  if user_db.token != token:
    flask.flash(__('That link is either invalid or expired.'), category='danger')
    return flask.redirect(flask.url_for('profile'))
  user_db.verified = True
  user_db.token = util.uuid()
  user_db.put()
  flask.flash(__('Hooray! Your email is now verified.'), category='success')
  return flask.redirect(flask.url_for('profile'))
示例#37
0
def purchased_page():
    user_db = auth.current_user_db()
    purchased = []
    if user_db.purchased_list:
        purchased = Issue.query(Issue.key.IN(
            user_db.purchased_list)).order(-Issue.date).fetch()
    else:
        flask.abort(404)
    return flask.render_template('purchased_page.html',
                                 purchased=purchased,
                                 user_db=user_db)
示例#38
0
def resource_list():
  resource_dbs, resource_cursor = auth.current_user_db().get_resource_dbs()

  return flask.render_template(
    'resource/resource_list.html',
    html_class='resource-list',
    title='Resource List',
    resource_dbs=resource_dbs,
    next_url=util.generate_next_url(resource_cursor),
    api_url=flask.url_for('api.resource.list'),
  )
示例#39
0
def resource_list():
  resource_dbs, resource_cursor = auth.current_user_db().get_resource_dbs()

  return flask.render_template(
    'resource/resource_list.html',
    html_class='resource-list',
    title='Resource List',
    resource_dbs=resource_dbs,
    next_url=util.generate_next_url(resource_cursor),
    api_url=flask.url_for('api.resource.list'),
  )
示例#40
0
def purchased_list_del():
    title = request.form['issue_title']
    issue = Issue.query(Issue.title == title).get(keys_only=True)
    user_db = auth.current_user_db()
    if (issue is not None) & (issue in user_db.purchased_list):
        user_db.purchased_list.remove(issue)
        user_db.put()
        app.logger.debug("issue removed from purchased list: %s" % title)
    else:
        app.logger.error("issue %s not found" % title)
    return flask.redirect(flask.url_for('purchased_page'))
示例#41
0
    def put(self, key):
        user_id = g.model_db.id()
        profile = Profile.get_by('user_id', user_id)
        if auth.current_user_db().id() != user_id:  # logged in
            return ApiException.error(108)

        new_profile_data = _.pick(request.json,
                                  Profile.ALL_NON_STRUCTURED_PROPERTIES)
        profile.populate(**new_profile_data)
        profile.put()

        return profile.to_dict(include=profile.get_all_properties())
示例#42
0
    def post(self, key):
        user_id = g.model_db.id()
        if auth.current_user_db().id() != user_id: # not allowed to create registrations for other people
            return ApiException.error(403)

        item_db = Hackathon.get_or_create(g.model_db, 'spring_2016') # this is the name of the hackathon on feb 19, 2016
        update_properties = ['rsvp', 'resume', 'skills', 'maker', 'phone', 'shirt', 'gender', 'superpower']
        new_item_data = _.pick(request.json, update_properties)
        item_db.populate(**new_item_data)
        item_db.put()

        return item_db.to_dict(include=Hackathon.get_public_properties())
示例#43
0
def join_game(gameid, hostplayer):
    """Return a game page"""
    user_db = auth.current_user_db()
    name = user_db.name
    token = channel.create_channel(name + gameid)
    template_values = {
        "gameid": gameid,
        "token": channel.create_channel(name + gameid),
        "yourname": name,
        "hostplayer": hostplayer
    }
    return render_template("player.html", values=template_values)
示例#44
0
def join_game(gameid,hostplayer):
	"""Return a game page"""
	user_db = auth.current_user_db()
	name = user_db.name
	token = channel.create_channel(name + gameid) 
	template_values = {
						"gameid":gameid,
						"token": channel.create_channel(name + gameid),
						"yourname": name,
						"hostplayer":hostplayer
						}
	return render_template("player.html", values=template_values)
示例#45
0
def user_verify(token):
    user_db = auth.current_user_db()
    if user_db.token != token:
        flask.flash(u'Холбоос буруу эсвэл хугацаа нь дууссан байна.',
                    category='danger')
        return flask.redirect(flask.url_for('profile'))
    user_db.verified = True
    user_db.token = util.uuid()
    user_db.put()
    flask.flash(u'Баярлалаа! Таны цахим шуудан баталгаажлаа.',
                category='success')
    return flask.redirect(flask.url_for('profile'))
示例#46
0
def serie_page(title):
    user_db = auth.current_user_db()
    serie = []
    if title:
        serie = Issue.query(
            Issue.serie == ndb.Key(Serie, title)).order(-Issue.date).fetch()
    if not serie:
        abort(404)
    return flask.render_template('serie_page.html',
                                 title=title,
                                 serie=serie,
                                 user_db=user_db)
 def get_user():
     user = auth.current_user_db()
     #if user.google_display_name == '':
     #    flask.flash('User is not known yet')
     #    return flask.redirect(flask.url_for('signin_google_plus'))
     #current = int(time.time())
     #remaining = user.expires_at - current
     #print "remaining=%d" % (remaining)
     #if remaining <= 0:
     #    result = refresh(user)
     #    return result
     return user
示例#48
0
def show_detail(id):
    # remove the media from session and set a new one.
    # this is used for the back url
    session.pop('media', None)
    media = request.args.get('media')
    if media is None:
        media = 'tv'
    session['media'] = media

    form = NewComment(mediaType=media)
    shows = showFunctions.getDetails(id, media)
    #shows = getSingleShowInfo(id, media)
    back_url = request.args.get('back')
    showId = str(id)

    if (auth.current_user_id > 0):
        fav = showFunctions.isFavorited(id)

    #fake_data(showid)

    comments_db, comments_cursor = model.UserComments.get_dbs(showId=showId,
                                                              limit=10,
                                                              prev_cursor=True)

    if form.validate_on_submit():
        media = form.mediaType.data

        comment = model.UserComments(user_key=auth.current_user_key(),
                                     showId=showId,
                                     body=form.body.data,
                                     creator=auth.current_user_db().name)
        if comment.put():

            flask.flash("Comment Created", category='success')
            return flask.redirect(
                flask.url_for('show_detail',
                              id=id,
                              media=media,
                              order='-created'))

    return flask.render_template(
        'details.html',
        html_class='show_detail',
        shows=shows,
        back_url=back_url,
        fav=fav,
        media=media,
        form=form,
        comments_db=comments_db,
        next_url=util.generate_next_url(comments_cursor['next']),
        prev_url=util.generate_next_url(comments_cursor['prev']),
    )
示例#49
0
def feedback():
    if not config.CONFIG_DB.feedback_email:
        return flask.abort(418)

    form = FeedbackForm(obj=auth.current_user_db())
    if form.validate_on_submit():
        body = "%s\n\n%s" % (form.message.data, form.email.data)
        kwargs = {"reply_to": form.email.data} if form.email.data else {}
        task.send_mail_notification(form.subject.data, body, **kwargs)
        flask.flash("Thank you for your feedback!", category="success")
        return flask.redirect(flask.url_for("welcome"))

    return flask.render_template("feedback.html", title="Feedback", html_class="feedback", form=form)
示例#50
0
def profile():
  user_db = auth.current_user_db()

  if flask.request.path.startswith('/_s/'):
    return util.jsonify_model_db(user_db)

  return flask.render_template(
      'profile/profile.html',
      title=user_db.name,
      html_class='profile-view',
      user_db=user_db,
      has_json=True,
    )
示例#51
0
def profile():
    next_url = util.get_next_url()
    customer_fields_require = False
    user_db = current_user_db()
    form = ProfileUpdateForm(obj=user_db)
    if form.validate_on_submit():
        form.populate_obj(user_db)
        user_db.put()
        if not "customer_require" in flask.request.form:
            flask.flash(u"Профиль успешно обновлен")
            return flask.redirect(flask.url_for("pages.index"))
        else:
            if not form.email.data or not form.company.data:
                if not form.email.data:
                    form.email.errors.append(u"Это поле обязательно для заполнения")
                if not form.company.data:
                    form.company.errors.append(u"Это поле обязательно для заполнения")
                customer_fields_require = True
            else:
                msg = u"Профиль успешно обновлен, "
                request = PartnerRequest.query(PartnerRequest.customer == user_db.key)
                if request.count():
                    msg += u"Вы уже делали запрос на сотрудничество, запрос "
                    request = request.get()
                    if request.status == REQUEST_STATUS["now"]:
                        msg += u"еще не рассмотрен"
                    elif request.status == REQUEST_STATUS["accept"]:
                        msg += u"одобрен"
                    elif request.status == REQUEST_STATUS["admin"]:
                        msg += u"одобрен и Вам были даны права администратора"
                    else:
                        msg += u"отклонен"
                else:
                    msg += u"в ближайшее время с Вами свяжется наш менеджер"
                    request = PartnerRequest(customer=user_db.key)
                    request.put()
                flask.flash(msg)
                return flask.redirect(flask.url_for("pages.index"))

    if flask.request.path.startswith("/_json/"):
        return util.jsonify_model_db(user_db)

    return flask.render_template(
        "auth/profile.html",
        title="Profile",
        html_class="profile",
        form=form,
        user_db=user_db,
        customer_fields_require=customer_fields_require,
        next_url=next_url,
    )
示例#52
0
def profile():
  next_url = util.get_next_url()
  customer_fields_require = False
  user_db = current_user_db()
  form = ProfileUpdateForm(obj=user_db)
  if form.validate_on_submit():
    form.populate_obj(user_db)
    user_db.put()
    if not 'customer_require' in flask.request.form:
      flask.flash(u'Профиль успешно обновлен')
      return flask.redirect(flask.url_for('pages.index'))
    else:
      if not form.email.data or not form.company.data:
        if not form.email.data:
            form.email.errors.append(u'Это поле обязательно для заполнения')
        if not form.company.data:
            form.company.errors.append(u'Это поле обязательно для заполнения')
        customer_fields_require = True
      else:
        msg = u'Профиль успешно обновлен, '
        request = PartnerRequest.query(PartnerRequest.customer == user_db.key)
        if request.count():
            msg += u'Вы уже делали запрос на сотрудничество, запрос '
            request = request.get()
            if request.status == REQUEST_STATUS['now']:
                msg += u'еще не рассмотрен'
            elif request.status == REQUEST_STATUS['accept']:
                msg += u'одобрен'
            elif request.status == REQUEST_STATUS['admin']:
                msg += u'одобрен и Вам были даны права администратора'
            else:
                msg += u'отклонен'
        else:
            msg += u'в ближайшее время с Вами свяжется наш менеджер'
            request = PartnerRequest(customer = user_db.key)
            request.put()
        flask.flash(msg)
        return flask.redirect(flask.url_for('pages.index'))

  if flask.request.path.startswith('/_json/'):
    return util.jsonify_model_db(user_db)

  return flask.render_template(
      'auth/profile.html',
      title='Profile',
      html_class='profile',
      form=form,
      user_db=user_db,
      customer_fields_require = customer_fields_require,
      next_url = next_url
    )
示例#53
0
文件: views.py 项目: gmist/3dhero.ru
def index():
    master_db = Config.get_master_db()
    if master_db.recaptcha_public_key and master_db.recaptcha_private_key:
        if not flask.request.headers.getlist("X-Forwarded-For"):
            ip = flask.request.remote_addr
        else:
            ip = flask.request.headers.getlist("X-Forwarded-For")[0]
        form = FeedbackCaptchaForm(captcha={
            'ip_address': ip,
            'public_key': master_db.recaptcha_public_key,
            'private_key': master_db.recaptcha_private_key
        })
        use_captcha = True
    else:
        form = FeedbackForm()
        use_captcha = False
    if form.validate_on_submit():
        feedback = Feedback()
        form.populate_obj(feedback)
        feedback.put()
        feedback_email = master_db.feedback_email
        managers = Manager.query()
        if feedback_email and managers:
            subject = u'[%s] Сообщение - %s' % (
                master_db.brand_name,
                form.subject.data
            )
            body = u'%s\n\n%s' % (form.feedback.data, form.email.data)
            for manager in managers:
                if manager.email and manager.is_mailable:
                    emails = collect_emails(manager.email)
                    for email in emails:
                        mail.send_mail(
                            sender=master_db.feedback_email,
                            to=email,
                            subject=subject,
                            reply_to=form.email.data or master_db.feedback_email,
                            body=body
                        )
        flask.flash(u'Спасибо за Ваш отзыв!', category='success')
        return flask.redirect(flask.url_for('pages.index'))
    if not form.errors and current_user_id() > 0:
        form.email.data = current_user_db().email
    return flask.render_template(
        'feedback/index.html',
        title=u'Обратная связь',
        html_class='feedback',
        form=form,
        use_captcha=use_captcha
    )
示例#54
0
def propose_new_lesson_version(lesson_id):
  user_db = auth.current_user_db()
  lesson = model.Lesson.get_by_id(int(lesson_id))
  form = NewLessonForm(name = lesson.name, description = lesson.description,
   topics = ','.join([ key.urlsafe() for key in lesson.topics]), lesson_id = lesson_id,
   is_a = lesson.is_a)
  return flask.render_template(
      'lesson/lesson_update.html',
      title='Lesson Update Proposal',
      post_path=flask.url_for('api.lesson_version.new',lesson_key=lesson.key.urlsafe()),
      form=form,
      lesson_db=lesson,
      html_class='lesson-update-proposal',
    )
示例#55
0
def resource_list():
  resource_dbs, resource_cursor = auth.current_user_db().get_resource_dbs()

  if flask.request.path.startswith('/_s/'):
    return util.jsonify_model_dbs(resource_dbs, resource_cursor)

  return flask.render_template(
      'resource/resource_list.html',
      html_class='resource-list',
      title='Resource List',
      resource_dbs=resource_dbs,
      next_url=util.generate_next_url(resource_cursor),
      has_json=True,
    )