Esempio n. 1
0
def user_reset(token=None):
  user_db = model.User.get_by('token', token)
  if not user_db:
    flask.flash(__('That link is either invalid or expired.'), category='danger')
    return flask.redirect(flask.url_for('welcome'))

  if auth.is_logged_in():
    login.logout_user()
    return flask.redirect(flask.request.path)

  form = UserResetForm()
  if form.validate_on_submit():
    user_db.password_hash = util.password_hash(user_db, form.new_password.data)
    user_db.token = util.uuid()
    user_db.verified = True
    user_db.put()
    flask.flash(__('Your password was changed succesfully.'), category='success')
    return auth.signin_user_db(user_db)

  return flask.render_template(
      'user/user_reset.html',
      title='Reset Password',
      html_class='user-reset',
      form=form,
      user_db=user_db,
    )
Esempio n. 2
0
def duration_choices():
    choices = [
        ("4", "4 %s" % __("Hours")),
        ("8", "8 %s" % __("Hours")),
        ("16", "16 %s" % __("Hours")),
        ("24", "24 %s" % __("Hours")),
    ]
    return choices
Esempio n. 3
0
class LoginForm(Form):
    """ Login page view model """
    username = TextField(__('Username'),
        [validators.Length(min=4,
                           max=25,
                           message=__('Username should contain between 4 and 20 characters'))])
    password = PasswordField(__('Password'),
        [validators.Required(message=__('Password is required'))])
Esempio n. 4
0
def duration_choices():
    choices = [
        ('4', '4 %s' % __('Hours')),
        ('8', '8 %s' % __('Hours')),
        ('16', '16 %s' % __('Hours')),
        ('24', '24 %s' % __('Hours'))
    ]
    return choices
Esempio n. 5
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'))
Esempio n. 6
0
def signin():
  next_url = util.get_next_url()
  form = None
  if config.CONFIG_DB.has_email_authentication:
    form = form_with_recaptcha(SignInForm())
    save_request_params()
    if form.validate_on_submit():
      result = get_user_db_from_email(form.email.data, form.password.data)
      if result:
        cache.reset_auth_attempt()
        return signin_user_db(result)
      if result is None:
        form.email.errors.append(__('Email or Password do not match'))
      if result is False:
        return flask.redirect(flask.url_for('welcome'))
    if not form.errors:
      form.next_url.data = next_url

  if form and form.errors:
    cache.bump_auth_attempt()

  return flask.render_template(
    'auth/auth.html',
    title=_('Sign in'),
    html_class='auth',
    next_url=next_url,
    form=form,
    form_type='signin' if config.CONFIG_DB.has_email_authentication else '',
    **urls_for_oauth(next_url)
  )
Esempio n. 7
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 not user_db.password_hash:
    del form.old_password

  if form.validate_on_submit():
    errors = False
    old_password = form.old_password.data if form.old_password else None
    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 (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,
  )
Esempio n. 8
0
def signup():
  next_url = util.get_next_url()
  form = None
  if config.CONFIG_DB.has_email_authentication:
    form = form_with_recaptcha(SignUpForm())
    save_request_params()
    if form.validate_on_submit():
      user_db = model.User.get_by('email', form.email.data)
      if user_db:
        form.email.errors.append(__('This email is already taken.'))

      if not form.errors:
        user_db = create_user_db(
            None,
            util.create_name_from_email(form.email.data),
            form.email.data,
            form.email.data,
          )
        user_db.put()
        task.activate_user_notification(user_db)
        cache.bump_auth_attempt()
        return flask.redirect(flask.url_for('welcome'))

  if form and form.errors:
    cache.bump_auth_attempt()

  title = _('Sign up') if config.CONFIG_DB.has_email_authentication else _('Sign in')
  return flask.render_template(
      'auth/auth.html',
      title=title,
      html_class='auth',
      next_url=next_url,
      form=form,
      **urls_for_oauth(next_url)
    )
Esempio n. 9
0
def profile(username):
    user = User.query.filter_by(username=username).first_or_404()
    if user.role.name == 'client':
        return render_template('user/client_profile.html', user=user)
    elif user.role.name == 'escort':
        tags = user.escort_profile.service_tags.all()
        cover = EscortPhoto.query.filter_by(
            profile_id=user.escort_profile_id,
            is_cover=True
            ).first()
        if not cover:
            flash(_('Choose a photo for your profile, <a href="%(url)s" class="alert-link">Click here</a>.', url=url_for('user.edit_photos')), 'alert-info')
            cover = 'choose/cb8c260efa71923e651caf7ffc47e653.jpg'
        else:
            cover = cover.key
        classified_tags = {}
        if len(tags) != 0:
            for tag in tags:
                classified_tags.setdefault(tag.category, [])
                classified_tags[tag.category].append(__(tag.tag_en))
        return render_template(
            'user/escort_profile.html',
            user=user,
            profile=user.escort_profile,
            tags=classified_tags,
            domain=current_app.config['QN_DOMAIN'],
            cover=cover
            )
Esempio n. 10
0
def user_activate(token):
  if auth.is_logged_in():
    login.logout_user()
    return flask.redirect(flask.request.path)

  user_db = model.User.get_by('token', token)
  if not user_db:
    flask.flash(__('That link is either invalid or expired.'), category='danger')
    return flask.redirect(flask.url_for('welcome'))

  form = UserActivateForm(obj=user_db)
  if form.validate_on_submit():
    form.populate_obj(user_db)
    user_db.password_hash = util.password_hash(user_db, form.password.data)
    user_db.token = util.uuid()
    user_db.verified = True
    user_db.put()
    return auth.signin_user_db(user_db)

  return flask.render_template(
      'user/user_activate.html',
      title='Activate Account',
      html_class='user-activate',
      user_db=user_db,
      form=form,
    )
Esempio n. 11
0
def signup():
  next_url = util.get_next_url()
  form = None
  if config.CONFIG_DB.has_email_authentication:
    form = form_with_recaptcha(SignUpForm())
    save_request_params()
    if form.validate_on_submit():
      user_db = model.User.get_by('email', form.email.data)
      if user_db:
        form.email.errors.append(__('This email is already taken.'))

      if not form.errors:
        user_db = create_user_db(
          None,
          util.create_name_from_email(form.email.data),
          form.email.data,
          form.email.data,
        )
        user_db.put()
        task.activate_user_notification(user_db)
        cache.bump_auth_attempt()
        return flask.redirect(flask.url_for('welcome'))

  if form and form.errors:
    cache.bump_auth_attempt()

  title = _('Sign up') if config.CONFIG_DB.has_email_authentication else _('Sign in')
  return flask.render_template(
    'auth/auth.html',
    title=title,
    html_class='auth',
    next_url=next_url,
    form=form,
    **urls_for_oauth(next_url)
  )
Esempio n. 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,
    )
Esempio n. 13
0
def signin():
  next_url = util.get_next_url()
  form = None
  if config.CONFIG_DB.has_email_authentication:
    form = form_with_recaptcha(SignInForm())
    save_request_params()
    if form.validate_on_submit():
      result = get_user_db_from_email(form.email.data, form.password.data)
      if result:
        cache.reset_auth_attempt()
        return signin_user_db(result)
      if result is None:
        form.email.errors.append(__('Email or Password do not match'))
      if result is False:
        return flask.redirect(flask.url_for('welcome'))
    if not form.errors:
      form.next_url.data = next_url

  if form and form.errors:
    cache.bump_auth_attempt()

  return flask.render_template(
      'auth/auth.html',
      title=_('Sign in'),
      html_class='auth',
      next_url=next_url,
      form=form,
      form_type='signin' if config.CONFIG_DB.has_email_authentication else '',
      **urls_for_oauth(next_url)
    )
Esempio n. 14
0
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  if login.login_user(flask_user_db):
    user_db.put_async()
    response = flask.redirect(util.get_next_url())
    util.set_locale(user_db.locale, response)
    flask.flash(__(
        'Hello %(name)s, welcome to %(brand)s.',
        name=user_db.name, brand=config.CONFIG_DB.brand_name,
      ), category='success')
    return response
  else:
    flask.flash(__('Sorry, but you could not sign in.'), category='danger')
    return flask.redirect(flask.url_for('signin'))
Esempio n. 15
0
def google_authorized():
  google_user = users.get_current_user()
  if google_user is None:
    flask.flash(__('You denied the request to sign in.'))
    return flask.redirect(util.get_next_url())

  user_db = retrieve_user_from_google(google_user)
  return signin_user_db(user_db)
Esempio n. 16
0
def facebook_authorized(resp):
  if resp is None:
    flask.flash(__('You denied the request to sign in.'))
    return flask.redirect(util.get_next_url())

  flask.session['oauth_token'] = (resp['access_token'], '')
  me = facebook.get('/me')
  user_db = retrieve_user_from_facebook(me.data)
  return signin_user_db(user_db)
Esempio n. 17
0
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
      'next': flask.url_for('welcome'),
      'remember': False,
    })
  if login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    response = flask.redirect(auth_params['next'])
    util.set_locale(user_db.locale, response)
    flask.flash(__(
        'Hello %(name)s, welcome to %(brand)s.',
        name=user_db.name, brand=config.CONFIG_DB.brand_name,
      ), category='success')
    return response
  flask.flash(__('Sorry, but you could not sign in.'), category='danger')
  return flask.redirect(flask.url_for('signin'))
Esempio n. 18
0
def facebook_authorized():
  response = facebook.authorized_response()
  if response is None:
    flask.flash(__('You denied the request to sign in.'))
    return flask.redirect(util.get_next_url())

  flask.session['oauth_token'] = (response['access_token'], '')
  me = facebook.get('/me?fields=name,email')
  user_db = retrieve_user_from_facebook(me.data)
  return auth.signin_user_db(user_db)
Esempio n. 19
0
def google_authorized():
  response = google.authorized_response()
  if response is None:
    flask.flash(__('You denied the request to sign in.'))
    return flask.redirect(util.get_next_url())

  flask.session['oauth_token'] = (response['access_token'], '')
  me = google.get('me', data={'access_token': response['access_token']})
  user_db = retrieve_user_from_google(me.data)
  return auth.signin_user_db(user_db)
Esempio n. 20
0
    def __call__(self, form, field):
        if form.xiamitype.data is False and form.banyungongtype.data is False \
                and form.zimuzutype.data is False and form.packtype.data is False:
            if self.message is None:
                message = __(u'Plz select at least one type')
            else:
                message = self.message

            field.errors[:] = []
            raise StopValidation(message)
Esempio n. 21
0
def account_check():
    form = LoginForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            account = form.account.data
            password = form.password.data
            remember = form.remember.data

            work = {
                (XiamiLogin, XiamiUser): form.xiamitype.data,
                (BanyungongLogin, BanyungongUser): form.banyungongtype.data,
                (ZimuzuLogin, ZimuzuUser): form.zimuzutype.data,
                (PacktLogin, PacktUser): form.packtype.data,
            }

            for (job_klass, model_klass), jobstatus in work.items():
                if jobstatus is True:
                    login_request = job_klass(app.logger)
                    user_klass = model_klass

                    result = login_request.login(account, password)
                    cookie = login_request.dump_cookie()

                    if result is None:  # Successful
                        user = user_klass.query.filter_by(
                            account=account).first()
                        if user is None:
                            user = user_klass()
                            user.account = account
                            user.cookie = cookie

                            if remember:
                                user.passwd = password

                            db.session.add(user)
                        else:
                            user.cookie = cookie

                            if remember:
                                user.passwd = password

                        db.session.commit()
                        msg = '%s %s added for daily checkin' % (
                            login_request.tag, account)
                        flash(msg)
                        app.logger.info(msg)
                    else:
                        msg = __("Error: %(originator)s: %(result)s",
                                 originator=login_request.tag,
                                 result=result)
                        flash(msg)
                        app.logger.info(msg)

    return render('secret/login.html', form=form)
Esempio n. 22
0
def twitter_authorized(resp):
  if resp is None:
    flask.flash(__('You denied the request to sign in.'))
    return flask.redirect(util.get_next_url())

  flask.session['oauth_token'] = (
      resp['oauth_token'],
      resp['oauth_token_secret'],
    )
  user_db = retrieve_user_from_twitter(resp)
  return signin_user_db(user_db)
Esempio n. 23
0
def signin_twitter():
  flask.session.pop('oauth_token', None)
  save_request_params()
  try:
    return twitter.authorize(callback=flask.url_for('twitter_authorized'))
  except:
    flask.flash(
        __('Something went wrong with Twitter sign in. Please try again.'),
        category='danger',
      )
    return flask.redirect(flask.url_for('signin', next=util.get_next_url()))
Esempio n. 24
0
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
      'next': flask.url_for('welcome'),
      'remember': False,
    })
  flask.session.pop('auth-params', None)
  if login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash(__('Sorry, but you could not sign in.'), category='danger')
  return flask.redirect(flask.url_for('signin'))
Esempio n. 25
0
def signin_user_db(user_db):
  if not user_db:
    return flask.redirect(flask.url_for('signin'))
  flask_user_db = FlaskUser(user_db)
  auth_params = flask.session.get('auth-params', {
    'next': flask.url_for('welcome'),
    'remember': False,
  })
  flask.session.pop('auth-params', None)
  if login.login_user(flask_user_db, remember=auth_params['remember']):
    user_db.put_async()
    return flask.redirect(util.get_next_url(auth_params['next']))
  flask.flash(__('Sorry, but you could not sign in.'), category='danger')
  return flask.redirect(flask.url_for('signin'))
Esempio n. 26
0
class LoginForm(Form):
    account = StringField(__(u'Account'), validators=[DataRequired(__(u'This field is required'))])
    password = PasswordField(__(u'Password'), validators=[DataRequired(__(u'This field is required'))])
    remember = BooleanField(__(u'I can save password in DB'))
    xiamitype = BooleanField(u'Xiami')
    banyungongtype = BooleanField(u'Banyungong')
    packtype = BooleanField(u'PacktPub')
    zimuzutype = BooleanField(u'Zimuzu', validators=[AccountTypeRequired()])
    submit = SubmitField(__(u'Add My Account'))
Esempio n. 27
0
def get_user_db_from_email(email, password):
  user_dbs, cursors = model.User.get_dbs(email=email, active=True, limit=2)
  if not user_dbs:
    return None
  if len(user_dbs) > 1:
    flask.flash(__('''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.'''), category='danger')
    task.email_conflict_notification(email)
    return False

  user_db = user_dbs[0]
  if user_db.password_hash == util.password_hash(user_db, password):
    return user_db
  return None
Esempio n. 28
0
def get_user_db_from_email(email, password):
  user_dbs, cursors = model.User.get_dbs(email=email, active=True, limit=2)
  if not user_dbs:
    return None
  if len(user_dbs) > 1:
    flask.flash(__('''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.'''), category='danger')
    task.email_conflict_notification(email)
    return False

  user_db = user_dbs[0]
  if user_db.password_hash == util.password_hash(user_db, password):
    return user_db
  return None
Esempio n. 29
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,
    )
Esempio n. 30
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,
    )
Esempio n. 31
0
class EditUserForm(Form):
    """ User modification page view model """
    username = TextField(__('Username'),
        [validators.Length(min=4,
                           max=25,
                           message=__('Username should contain between 4 and 20 characters'))])
    password = PasswordField(__('Password'))
    confirm_password = PasswordField(__('Confirm password'),
        [validators.EqualTo('password', message=__('Passwords must match'))])
    is_super_admin = BooleanField(__('Super Administrator'))
    is_disabled = BooleanField(__('Disabled'))
    shinken_contact = SelectField(__('Shinken contact'))

    def __init__(self, formvalues):
        super(EditUserForm, self).__init__(formvalues)

    #   Contacts drop down list
        clist = [(c, c) for c in livestatus.contacts]
        clist.insert(0, ('None', 'None'))
        self.shinken_contact.choices = clist
class CreateTaskForm(Form):
    tpl = SelectField(u'Templates')
    submit = SubmitField(__(u'Submit'))
def custom_form_factory(form, field_types=[], field_slugs=[],
                        excluded_field_types=[],
                        registration_fields=False):
    fields = (CustomField.query.filter_by(meeting_id=g.meeting.id)
              .order_by(CustomField.sort))
    form_attrs = {
        '_custom_fields': OrderedMultiDict({c.slug: c for c in fields}),
    }

    if field_types:
        fields = fields.filter(CustomField.field_type.in_(field_types))

    if field_slugs:
        fields = fields.filter(CustomField.slug.in_(field_slugs))

    if excluded_field_types:
        fields = fields.filter(
            ~CustomField.field_type.in_(excluded_field_types))

    if registration_fields:
        fields = fields.for_registration()

    if getattr(form, 'CUSTOM_FIELDS_TYPE', None):
        fields = fields.filter_by(custom_field_type=form.CUSTOM_FIELDS_TYPE)

    for f in fields:
        attrs = {'label': unicode(CustomFieldLabel(f.label)),
                 'validators': [],
                 'description': f.hint}

        data = _CUSTOM_FIELDS_MAP[f.field_type.code]

        # overwrite data if _CUSTOM_FIELDS_MAP attribute is present on form
        form_fields_map = getattr(form, '_CUSTOM_FIELDS_MAP', None)
        if form_fields_map:
            try:
                data = form_fields_map[f.field_type.code]
            except KeyError:
                pass

        if f.required:
            attrs['validators'].append(DataRequired())
        attrs['validators'].extend(data.get('validators', []))

        if f.max_length:
            attrs['validators'].append(Length(max=f.max_length))

        if f.field_type.code == CustomField.SELECT:
            query = CustomFieldChoice.query.filter_by(custom_field=f)
            attrs['choices'] = [(unicode(c.value), __(c.value.english))
                                for c in query]
            if not f.required:
                attrs['choices'] = [('', '---')] + attrs['choices']
            attrs['coerce'] = unicode

        if f.field_type.code == CustomField.LANGUAGE:
            attrs['choices'] = [i for i in Participant.LANGUAGE_CHOICES
                                if i[0].lower() in app.config['TRANSLATIONS']]
            if not f.required:
                attrs['choices'] = [('', '---')] + attrs['choices']

            attrs['coerce'] = unicode

        if f.field_type.code == CustomField.CATEGORY:
            query = Category.get_categories_for_meeting(
                form.CUSTOM_FIELDS_TYPE)
            if registration_fields:
                query = query.filter_by(visible_on_registration_form=True)
            attrs['choices'] = [(c.id, c) for c in query]
            attrs['coerce'] = int

        if f.field_type.code in (CustomField.MULTI_CHECKBOX,CustomField.RADIO):
            query = CustomFieldChoice.query.filter_by(custom_field=f)
            attrs['choices'] = [(unicode(c.value), c.value) for c in query]
            attrs['coerce'] = unicode

        # set field to form
        # _set_rules_for_custom_fields(f, attrs)
        field = data['field'](**attrs)
        setattr(field, 'field_type', f.field_type.code)
        form_attrs[f.slug] = field

    form_attrs['rules'] = Rule.get_rules_for_fields(fields)
    return type(form)(form.__name__, (form,), form_attrs)
class HarForm(Form):
    har_file = FileField(__(u'Upload'))
    submit = SubmitField(__(u'Submit'))
# -*- coding: utf-8 -*-

from flask.ext.babel import lazy_gettext as __

from flask_wtf import Form
from wtforms import SelectField, SubmitField

# Some fields need to know
name = __(u'username')


class CreateTaskForm(Form):
    tpl = SelectField(u'Templates')
    submit = SubmitField(__(u'Submit'))
Esempio n. 36
0
def signout():
  login.logout_user()
  flask.flash(__('You have been signed out.'), category='success')
  return flask.redirect(flask.url_for('welcome'))