Ejemplo n.º 1
0
def signup_post():
    form = SignupForm(request.forms)
    if form.validate():
        user = User()
        form.populate_obj(user)
        user.save()
        login.login_user(user.id)
        send_confirm_email(app.config, user.email)
        return redirect('/active_email')
    return {'form': form, 'token': request.csrf_token}
Ejemplo n.º 2
0
def signup_post():
    form = SignupForm(request.forms)
    if form.validate():
        user = User()
        form.populate_obj(user)
        user.save()
        login.login_user(user.id)
        send_confirm_email(app.config, user.email)
        return redirect('/active_email')
    return {'form': form, 'token': request.csrf_token}
Ejemplo n.º 3
0
def oauth_callback(provider):
    current_app.logger.info("Oauth callback for %s" % provider)
    redirect_uri = current_app.config['OAUTH'][provider]['callback_url']
    oauth_service = get_oauth_services()[provider]

    data = dict(code=request.args.get('code'),
                grant_type='authorization_code',
                redirect_uri=redirect_uri)

    if provider == 'google':
        oauth_session = oauth_service.get_auth_session(data=data,
                                                       decoder=json.loads)
        user_info = oauth_session.get('userinfo').json()
        email = session['email'] = user_info['email']
        username = user_info['given_name']
    elif provider == 'github':
        oauth_session = oauth_service.get_auth_session(data=data)
        user_info = oauth_session.get('user').json()
        email = session['email'] = user_info['email']
        username = user_info['login']

    access_token = oauth_session.access_token
    user_info['id'] = str(user_info['id'])

    current_app.logger.info("%s oauth access token is: %s" %
                            (provider, access_token))
    current_app.logger.info("%s oauth user info is %s" % (provider, user_info))

    user = User.find_by_oauth(provider, user_info['id'])
    if user:
        # TODO: 直接登录时更新 token.
        user_mixin = LoginManagerUser(user)
        login_user(user_mixin)
        flash(u"登录成功", category='info')
        return redirect('/')
    else:
        user = User.objects(email=email).first()
        if user:
            user_oauth = UserOauth(provider=provider,
                                   openid=user_info['id'],
                                   token=access_token)
            user_oauth.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            flash(u"登录成功", category='info')
            return redirect('/')
        else:
            return render_template('users/finish_signup.html',
                                   form=UserInfoForm(email=email,
                                                     username=username))
Ejemplo n.º 4
0
 def validate_email(self, field):
     if session['email']:
         if session['email'] != field.data:
             raise ValidationError(u'不能修改第三方登录的email地址')
     user = User.objects(email=field.data).first()
     if user:
         raise ValidationError(u'Email地址已被使用')
Ejemplo n.º 5
0
def create_paste():
    if request.method == 'GET':
        # missing csrf
        form = PasteForm(data={'codes': [{'title': '', 'content': ''}]})
        return render_template('pastes/create.html', form=form)
    else:
        form = PasteForm(request.form)
        if form.validate():
            user = current_user.user
            paste = save_paste_and_codes(form)
            if not paste.is_private:
                followers = User.objects(followings=user)
                content = NEW_PASTE.format(user_username=user.username,
                                           user_url=url_for('user_app.view', username=user.username),
                                           paste_title=paste.title,
                                           paste_url=url_for('paste_app.view_paste', hash_id=paste.hash_id))
                for follower in followers:
                    message = Message(user=follower,
                                      who=user,
                                      content=content)
                    message.save()
            return jsonify(success=True, hash_id=paste.hash_id)
        else:
            errors = form.errors
            errors['codes'] = [code.errors for code in form.codes]
            logger.info('Failed saving paste for reason: %s', errors)
            return jsonify(success=False, errors=errors)
Ejemplo n.º 6
0
def reset_password_get(token):
    email = validate_token(app.config, token)
    if email:
        user = User.objects(email=email).first()
        if user:
            return {'form': PasswordForm(), 'token': token}
    abort(404)
Ejemplo n.º 7
0
def send_mail_post():
    form = EmailForm(request.forms)
    if form.validate():
        user = User.objects(email=form.email.data).first()
        send_confirm_email(app.config, user.email)
        return redirect('/success_sendmail')
    return {'form': form}
Ejemplo n.º 8
0
def lost_password_post():
    form = EmailForm(request.forms)
    if form.validate():
        user = User.objects(email=form.email.data).first()
        send_reset_password_email(app.config, user.email)
        return redirect('/reset_password_email_sent')
    return {'form': form}
Ejemplo n.º 9
0
def send_confirm_email(config, user_email):
    token = generate_confirmation_token(config, user_email)
    user = User.objects(email=user_email).first()
    content = CONFIRMATION_CONTENT % (user.username, config['DOMAIN'], token,
                                      config['DOMAIN'], token)
    send_email.delay(get_email_config(config), user_email,
                     CONFIRMATION_SUBJECT, content)
Ejemplo n.º 10
0
    def validate_username(self, field):
        if current_user.is_authenticated and current_user.user.username == field.data:
            return True

        user = User.objects(username=field.data).first()
        if user:
            raise ValidationError(u'用户名已被使用')
Ejemplo n.º 11
0
def create_paste():
    if request.method == 'GET':
        # missing csrf
        form = PasteForm(
            data={'codes': [{
                'title': '',
                'content': '',
                'syntax': 'text'
            }]})
        return render_template('pastes/create.html', form=form)
    else:
        form = PasteForm.from_json(data=request.json)
        if form.validate():
            user = current_user.user
            paste = save_paste_and_codes(form)
            if not paste.is_private:
                followers = User.objects(followings=user)
                content = NEW_PASTE.format(
                    user_username=user.username,
                    user_url=url_for('user_app.view', username=user.username),
                    paste_title=paste.title,
                    paste_url=url_for('paste_app.view_paste',
                                      hash_id=paste.hash_id))
                for follower in followers:
                    message = Message(user=follower, who=user, content=content)
                    message.save()
            return jsonify(success=True, hash_id=paste.hash_id)
        else:
            errors = form.errors
            errors['codes'] = [code.errors for code in form.codes]
            logger.info('Failed saving paste for reason: %s', errors)
            return jsonify(success=False, errors=errors)
Ejemplo n.º 12
0
def send_reset_password_email(config, user_email):
    token = generate_confirmation_token(config, user_email)
    user = User.objects(email=user_email).first()
    content = RESET_PASSWORD_CONTENT % (user.username, config['DOMAIN'], token,
                                        config['DOMAIN'], token)
    send_email.delay(get_email_config(config), user_email,
                     RESET_PASSWORD_SUBJECT, content)
Ejemplo n.º 13
0
def send_mail_post():
    form = EmailForm(request.forms)
    if form.validate():
        user = User.objects(email=form.email.data).first()
        send_confirm_email(app.config, user.email)
        return redirect('/success_sendmail')
    return {'form': form}
Ejemplo n.º 14
0
def reset_password_get(token):
    email = validate_token(app.config, token)
    if email:
        user = User.objects(email=email).first()
        if user:
            return {'form': PasswordForm(), 'token': token}
    abort(404)
Ejemplo n.º 15
0
def lost_password_post():
    form = EmailForm(request.forms)
    if form.validate():
        user = User.objects(email=form.email.data).first()
        send_reset_password_email(app.config, user.email)
        return redirect('/reset_password_email_sent')
    return {'form': form}
Ejemplo n.º 16
0
def send_email():
    form = EmailForm()
    if form.validate_on_submit():
        user = User.objects(email=form.email.data).first()
        send_confirm_email(current_app.config, user.email)
        return redirect('/success_sendmail')
    return render_template('sendmail.html', form=form)
Ejemplo n.º 17
0
def get_pastes_from_search(p=1):
    query_string = request.query.q

    def get_string_by_keyword(keyword, query_string):
        string = ''
        result = re.search('\s*%s:([a-zA-Z+-_#]+)\s*' % keyword, query_string)
        if result:
            if len(result.groups()) == 1:
                string = result.groups()[0]
        query_string = query_string.replace('%s:%s' % (keyword, string), '')
        return string, query_string

    tag, query_string = get_string_by_keyword('tag', query_string)
    user, query_string = get_string_by_keyword('user', query_string)
    keyword = query_string.strip()

    criteria = {'title__contains': keyword, 'is_private': False}
    if tag:
        criteria['tags'] = tag
    if user:
        user_object = User.objects(username=user).first()
        criteria['user'] = user_object

    return keyword, Paste.objects(
        **criteria).order_by('-updated_at')[(p - 1) * ITEMS_PER_PAGE:p *
                                            ITEMS_PER_PAGE]
Ejemplo n.º 18
0
def manage():
    form = UserInfoForm(request.forms)
    if form.validate():
        if request.user:
            request.user.username = form.username.data
            return redirect('/')
        else:
            user = User(email=form.email.data, username=form.username.data,
                        is_email_confirmed=True)
            user.save()
            login.login_user(str(user.id))
            session = get_session(request)
            if 'email' in session:
                del(session['email'])
            return redirect('/')
    return {'form': form, 'token': request.csrf_token}
Ejemplo n.º 19
0
def oauth_callback(provider):
    logger.info("Oauth callback for %s" % provider)
    redirect_uri = app.config['oauth.%s.callback_url' % provider]
    oauth_service = oauth_services[provider]
    session = get_session(request)

    data = dict(code=request.params.get('code'),
                grant_type='authorization_code',
                redirect_uri=redirect_uri)

    if provider == 'google':
        oauth_session = oauth_service.get_auth_session(data=data,
                                                       decoder=json.loads)
        user_info = oauth_session.get('userinfo').json()
        email = session['email'] = user_info['email']
        username = user_info['given_name']
    elif provider == 'github':
        oauth_session = oauth_service.get_auth_session(data=data)
        user_info = oauth_session.get('user').json()
        email = session['email'] = user_info['email']
        username = user_info['login']

    access_token = oauth_session.access_token
    user_info['id'] = str(user_info['id'])

    logger.info("%s oauth access token is: %s" % (provider, access_token))
    logger.info("%s oauth user info is %s" % (provider, user_info))

    user = User.find_by_oauth(provider, user_info['id'])
    if user:
        # TODO: 直接登录时更新 token.
        login.login_user(str(user.id))
        return redirect('/')
    else:
        user = User.objects(email=email).first()
        if user:
            user_oauth = UserOauth(provider=provider,
                                   openid=user_info['id'],
                                   token=access_token)
            user_oauth.save()
            login.login_user(str(user.id))
            return redirect('/')
        else:
            return {
                'form': UserInfoForm(email=email, username=username),
                'token': request.csrf_token
            }
Ejemplo n.º 20
0
def unwatch_user(username):
    following_user = User.objects(username=username).first_or_404()

    if current_user.user.is_following(following_user):
        current_user.user.followings.remove(following_user)
        current_user.user.save()

    return jsonify(watchedStatus=current_user.user.is_following(following_user))
Ejemplo n.º 21
0
def unwatch_user(username):
    be_followed_user = User.objects(username=username).first_or_404()

    if be_followed_user.is_followed_by(current_user.user):
        be_followed_user.followers.remove(current_user.user)
        be_followed_user.save()

    return jsonify(watchedStatus=be_followed_user.is_followed_by(current_user.user))
Ejemplo n.º 22
0
def unwatch_user(username):
    following_user = User.objects(username=username).first_or_404()

    if current_user.user.is_following(following_user):
        current_user.user.followings.remove(following_user)
        current_user.user.save()

    return jsonify(watchedStatus=current_user.user.is_following(following_user))
Ejemplo n.º 23
0
def manage():
    form = UserInfoForm(request.form)
    if form.validate():
        if current_user.is_authenticated:
            current_user.user.username = form.username.data
            return redirect('/')
        else:
            user = User(email=form.email.data, username=form.username.data,
                        is_email_confirmed=True)
            user.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            if 'email' in session:
                del(session['email'])
            return redirect('/')
    return render_template('users/manage.html',
                           form=form)
Ejemplo n.º 24
0
def send_email():
    form = EmailForm()
    if form.validate_on_submit():
        user = User.objects(email=form.email.data).first()
        send_confirm_email(current_app.config, user.email)
        return redirect('/success_sendmail')
    return render_template('sendmail.html',
                           form=form)
Ejemplo n.º 25
0
def manage():
    form = UserInfoForm(request.forms)
    if form.validate():
        if request.user:
            request.user.username = form.username.data
            return redirect('/')
        else:
            user = User(email=form.email.data,
                        username=form.username.data,
                        is_email_confirmed=True)
            user.save()
            login.login_user(str(user.id))
            session = get_session(request)
            if 'email' in session:
                del (session['email'])
            return redirect('/')
    return {'form': form, 'token': request.csrf_token}
Ejemplo n.º 26
0
def oauth_callback(provider):
    current_app.logger.info("Oauth callback for %s" % provider)
    redirect_uri = current_app.config['OAUTH'][provider]['callback_url']
    oauth_service = get_oauth_services()[provider]

    data = dict(code=request.args.get('code'),
                grant_type='authorization_code',
                redirect_uri=redirect_uri)

    if provider == 'google':
        oauth_session = oauth_service.get_auth_session(data=data, decoder=json.loads)
        user_info = oauth_session.get('userinfo').json()
        email = session['email'] = user_info['email']
        username = user_info['given_name']
    elif provider == 'github':
        oauth_session = oauth_service.get_auth_session(data=data)
        user_info = oauth_session.get('user').json()
        email = session['email'] = user_info['email']
        username = user_info['login']

    access_token = oauth_session.access_token
    user_info['id'] = str(user_info['id'])

    current_app.logger.info("%s oauth access token is: %s" % (provider, access_token))
    current_app.logger.info("%s oauth user info is %s" % (provider, user_info))

    user = User.find_by_oauth(provider, user_info['id'])
    if user:
        # TODO: 直接登录时更新 token.
        user_mixin = LoginManagerUser(user)
        login_user(user_mixin)
        flash(u"登录成功", category='info')
        return redirect('/')
    else:
        user = User.objects(email=email).first()
        if user:
            user_oauth = UserOauth(provider=provider, openid=user_info['id'], token=access_token)
            user_oauth.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            flash(u"登录成功", category='info')
            return redirect('/')
        else:
            return render_template('users/finish_signup.html',
                                   form=UserInfoForm(email=email, username=username))
Ejemplo n.º 27
0
def signup():
    form = SignupForm()
    if request.method == 'GET':
        return render_template('users/signup.html', form=form)
    else:
        if form.validate_on_submit():
            user = User()
            form.populate_obj(user)
            user.save()
            bookmark = Bookmark(user=user,
                                title=u"%s 的收藏夹" % user.username,
                                is_default=True)
            bookmark.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            send_confirm_email(current_app.config, user.email)
            return redirect(url_for('site_app.index'))
        return render_template('users/signup.html', form=form)
Ejemplo n.º 28
0
def view_followers(username):
    page = get_page()
    user = User.objects.get_or_404(username=username)

    pagination = User.objects(followings=user).paginate(page, per_page=20)

    return render_template('users/followers.html',
                           user=user,
                           pagination=pagination)
Ejemplo n.º 29
0
def view_bookmarks(username):
    page = get_page()

    user = User.objects(username=username).get_or_404()

    pagination = Bookmark.objects(user=user).order_by('-updated_at').paginate(page, per_page=20)

    return render_template('bookmarks/index.html',
                           pagination=pagination)
Ejemplo n.º 30
0
def view_bookmarks(username):
    page = get_page()

    user = User.objects(username=username).get_or_404()

    pagination = Bookmark.objects(user=user).order_by('-updated_at').paginate(
        page, per_page=20)

    return render_template('bookmarks/index.html', pagination=pagination)
Ejemplo n.º 31
0
def index():
    page = get_page()
    pagination = Paste.objects(is_private=False).order_by('-updated_at').paginate(page=page, per_page=20)

    print datetime.today()

    return render_template('index.html',
                           pagination=pagination,
                           hot_pastes=Paste.objects(is_private=False).order_by('-views')[:10],
                           pastes_count=Paste.objects().count(),
                           comments_count=Comment.objects().count(),
                           users_count=User.objects().count(),
                           syntax_count=Syntax.objects().count(),
                           bookmarks_count=Bookmark.objects().count(),
                           users_increased=User.objects(created_at__gt=date.today()).count(),
                           pastes_increased=Paste.objects(created_at__gt=date.today()).count(),
                           comments_increased=Comment.objects(created_at__gt=date.today()).count(),
                           bookmarks_increased=Bookmark.objects(created_at__gt=date.today()).count(),
                           tags=Tag.objects().order_by('-popularity')[:10])
Ejemplo n.º 32
0
def lost_password_get():
    if request.method == 'GET':
        return render_template('users/lost_password.html', form=EmailForm())
    else:
        form = EmailForm(request.form)
        if form.validate():
            user = User.objects(email=form.email.data).first()
            send_reset_password_email(current_app.config, user.email)
            return redirect('/reset_password_email_sent')
        return render_template('users/lost_password.html', form=form)
Ejemplo n.º 33
0
    def validate(self):
        if not Form.validate(self):
            return False

        user = User.objects(email=self.email.data).first()

        if not user:
            self.email.errors.append(u'用户不存在')
            return False

        return True
Ejemplo n.º 34
0
    def validate(self):
        if not Form.validate(self):
            return False

        user = User.objects(email=self.email.data).first()

        if not user:
            self.email.errors.append(u'用户不存在')
            return False

        return True
Ejemplo n.º 35
0
def signup():
    form = SignupForm()
    if request.method == 'GET':
        return render_template('users/signup.html',
                               form=form)
    else:
        if form.validate_on_submit():
            user = User()
            form.populate_obj(user)
            user.save()
            bookmark = Bookmark(user=user,
                                title=u"%s 的收藏夹" % user.username,
                                is_default=True)
            bookmark.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            send_confirm_email(current_app.config, user.email)
            return redirect(url_for('site_app.index'))
        return render_template('users/signup.html',
                               form=form)
Ejemplo n.º 36
0
    def validate_email(self, field):
        if current_user.is_authenticated:
            field.data = current_user.user.email
            return True

        if session['email']:
            if session['email'] != field.data:
                raise ValidationError(u'不能修改第三方登录的email地址')
        user = User.objects(email=field.data).first()
        if user:
            raise ValidationError(u'Email地址已被使用')
Ejemplo n.º 37
0
def oauth_callback(provider):
    logger.info("Oauth callback for %s" % provider)
    redirect_uri = app.config['oauth.%s.callback_url' % provider]
    oauth_service = oauth_services[provider]
    session = get_session(request)

    data = dict(code=request.params.get('code'),
                grant_type='authorization_code',
                redirect_uri=redirect_uri)

    if provider == 'google':
        oauth_session = oauth_service.get_auth_session(data=data, decoder=json.loads)
        user_info = oauth_session.get('userinfo').json()
        email = session['email'] = user_info['email']
        username = user_info['given_name']
    elif provider == 'github':
        oauth_session = oauth_service.get_auth_session(data=data)
        user_info = oauth_session.get('user').json()
        email = session['email'] = user_info['email']
        username = user_info['login']

    access_token = oauth_session.access_token
    user_info['id'] = str(user_info['id'])

    logger.info("%s oauth access token is: %s" % (provider, access_token))
    logger.info("%s oauth user info is %s" % (provider, user_info))

    user = User.find_by_oauth(provider, user_info['id'])
    if user:
        # TODO: 直接登录时更新 token.
        login.login_user(str(user.id))
        return redirect('/')
    else:
        user = User.objects(email=email).first()
        if user:
            user_oauth = UserOauth(provider=provider, openid=user_info['id'], token=access_token)
            user_oauth.save()
            login.login_user(str(user.id))
            return redirect('/')
        else:
            return {'form': UserInfoForm(email=email, username=username), 'token': request.csrf_token}
Ejemplo n.º 38
0
def reset_password_post(token):
    email = validate_token(app.config, token)
    if email:
        user = User.objects(email=email).first()
        if user:
            form = PasswordForm(request.forms)
            if form.validate():
                user.password = user.generate_password(form.password.data)
                user.save()
                redirect('/reset_password_success')
            return {'form': PasswordForm(), 'token': token}
    abort(404)
Ejemplo n.º 39
0
def reset_password_post(token):
    email = validate_token(app.config, token)
    if email:
        user = User.objects(email=email).first()
        if user:
            form = PasswordForm(request.forms)
            if form.validate():
                user.password = user.generate_password(form.password.data)
                user.save()
                redirect('/reset_password_success')
            return {'form': PasswordForm(), 'token': token}
    abort(404)
Ejemplo n.º 40
0
def lost_password_get():
    if request.method == 'GET':
        return render_template('user/lost_password.html',
                               form=EmailForm())
    else:
        form = EmailForm(request.forms)
        if form.validate():
            user = User.objects(email=form.email.data).first()
            send_reset_password_email(current_app.config, user.email)
            return redirect('/reset_password_email_sent')
        return render_template('user/lost_password.html',
                               form=form)
Ejemplo n.º 41
0
def finish_signup():
    form = UserInfoForm(request.form)
    if form.validate():
        if current_user.is_authenticated:
            current_user.user.username = form.username.data
            return redirect('/')
        else:
            user = User(email=form.email.data,
                        username=form.username.data,
                        is_email_confirmed=True)
            user.save()
            bookmark = Bookmark(user=user,
                                title=u"%s 的收藏夹" % user.username,
                                is_default=True)
            bookmark.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            flash(u"登录成功", category='info')
            if 'email' in session:
                del (session['email'])
            return redirect('/')
    return render_template('users/finish_signup.html', form=form)
Ejemplo n.º 42
0
    def validate(self):
        if not Form.validate(self):
            return False

        user = User.objects(email=self.email.data).first()

        if user:
            if user.check_login(self.password.data):
                self.user = user
                return True

        self.password.errors.append(u'登录邮箱或者密码不正确')
        return False
Ejemplo n.º 43
0
def finish_signup():
    form = UserInfoForm(request.form)
    if form.validate():
        if current_user.is_authenticated:
            current_user.user.username = form.username.data
            return redirect('/')
        else:
            user = User(email=form.email.data, username=form.username.data,
                        is_email_confirmed=True)
            user.save()
            bookmark = Bookmark(user=user,
                                title=u"%s 的收藏夹" % user.username,
                                is_default=True)
            bookmark.save()
            user_mixin = LoginManagerUser(user)
            login_user(user_mixin)
            flash(u"登录成功", category='info')
            if 'email' in session:
                del (session['email'])
            return redirect('/')
    return render_template('users/finish_signup.html',
                           form=form)
Ejemplo n.º 44
0
def confirm_email(token):
    email = validate_token(app.config, token)
    if email:
        user = User.objects(email=email).first()
        if user:
            if (request.user is not None and user == request.user) or request.user is None:
                if user.is_email_confirmed:
                    return {'title': u"Email已经激活过了", 'message': u"对不起,您的email已经激活过了。"}
                else:
                    user.is_email_confirmed = True
                    user.email_confirmed_on = datetime.datetime.now()
                    user.save()
                    return {'title': u'Email已经激活', 'message': u'您的email已经激活,请点击登录查看最新代码段。'}
    return {'title': u'Email验证链接错误', 'message': u'对不起,您的验证链接无效或者已经过期。'}
Ejemplo n.º 45
0
def reset_password(token):
    if request.method == 'GET':
        email = validate_token(current_app.config, token)
        if email:
            user = User.objects(email=email).first()
            if user:
                return render_template('user/reset_password.html',
                                       form=PasswordForm(),
                                       token=token)
        abort(404)
    else:
        email = validate_token(current_app.config, token)
        if email:
            user = User.objects(email=email).first()
            if user:
                form = PasswordForm()
                if form.validate_on_submit():
                    user.password = user.generate_password(form.password.data)
                    user.save()
                    return redirect('/reset_password_success')
                return render_template('user/reset_password.html',
                                       form=PasswordForm(),
                                       token=token)
        abort(404)
Ejemplo n.º 46
0
def confirm_email(token):
    email = validate_token(current_app.config, token)
    if email:
        user = User.objects(email=email).first_or_404()
        if (current_user.is_authenticated and user == current_user.user) or not current_user.is_authenticated:
            if user.is_email_confirmed:
                return render_template('email/confirm.html', title=u"Email已经激活过了", message=u"对不起,您的email已经激活过了。")
            else:
                user.is_email_confirmed = True
                user.email_confirmed_on = datetime.datetime.now()
                user.save()
                return render_template('email/confirm.html', title=u'Email已经激活', message=u'您的email已经激活,请点击登录查看最新代码段。')
    return render_template('email/confirm.html',
                           title=u'Email验证链接错误',
                           message=u'对不起,您的验证链接无效或者已经过期。')
Ejemplo n.º 47
0
def watch_user(username):
    following_user = User.objects(username=username).first_or_404()

    if not current_user.user.is_following(following_user):
        current_user.user.followings.append(following_user)
        current_user.user.save()

        content = WATCH.format(user_username=current_user.user.username,
                               user_url=url_for('user_app.view', username=current_user.user.username))
        message = Message(user=following_user,
                          who=current_user.user,
                          content=content)
        message.save()

    return jsonify(watchedStatus=current_user.user.is_following(following_user))
Ejemplo n.º 48
0
def confirm_email(token):
    email = validate_token(current_app.config, token)
    if email:
        user = User.objects(email=email).first_or_404()
        if (current_user.is_authenticated and user == current_user.user) or not current_user.is_authenticated:
            if user.is_email_confirmed:
                return render_template('email/confirm.html', title=u"Email已经激活过了", message=u"对不起,您的email已经激活过了。")
            else:
                user.is_email_confirmed = True
                user.email_confirmed_on = datetime.datetime.now()
                user.save()
                return render_template('email/confirm.html', title=u'Email已经激活', message=u'您的email已经激活,请点击登录查看最新代码段。')
    return render_template('email/confirm.html',
                           title=u'Email验证链接错误',
                           message=u'对不起,您的验证链接无效或者已经过期。')
Ejemplo n.º 49
0
def reset_password(token):
    if request.method == 'GET':
        email = validate_token(current_app.config, token)
        if email:
            user = User.objects(email=email).first()
            if user:
                return render_template('users/reset_password.html',
                                       form=PasswordForm(),
                                       token=token)
        abort(404)
    else:
        email = validate_token(current_app.config, token)
        if email:
            user = User.objects(email=email).first()
            if user:
                form = PasswordForm(request.form)
                if form.validate_on_submit():
                    user.password = user.generate_password(form.password.data)
                    user.save()
                    return redirect('/reset_password_success')
                return render_template('users/reset_password.html',
                                       form=PasswordForm(),
                                       token=token)
        abort(404)
Ejemplo n.º 50
0
def index():
    page = get_page()
    pagination = Paste.objects(
        is_private=False).order_by('-updated_at').paginate(page=page,
                                                           per_page=20)

    print datetime.today()

    return render_template(
        'index.html',
        pagination=pagination,
        hot_pastes=Paste.objects(is_private=False).order_by('-views')[:10],
        pastes_count=Paste.objects().count(),
        comments_count=Comment.objects().count(),
        users_count=User.objects().count(),
        syntax_count=Syntax.objects().count(),
        bookmarks_count=Bookmark.objects().count(),
        users_increased=User.objects(created_at__gt=date.today()).count(),
        pastes_increased=Paste.objects(created_at__gt=date.today()).count(),
        comments_increased=Comment.objects(
            created_at__gt=date.today()).count(),
        bookmarks_increased=Bookmark.objects(
            created_at__gt=date.today()).count(),
        tags=Tag.objects().order_by('-popularity')[:10])
Ejemplo n.º 51
0
def watch_user(username):
    following_user = User.objects(username=username).first_or_404()

    if not current_user.user.is_following(following_user):
        current_user.user.followings.append(following_user)
        current_user.user.save()

        content = WATCH.format(user_username=current_user.user.username,
                               user_url=url_for('user_app.view', username=current_user.user.username))
        message = Message(user=following_user,
                          who=current_user.user,
                          content=content)
        message.save()

    return jsonify(watchedStatus=current_user.user.is_following(following_user))
Ejemplo n.º 52
0
def create_paste():
    if request.method == 'GET':
        # missing csrf
        form = PasteForm(data={'codes': [{'title': '', 'content': ''}]})
        return render_template('pastes/create.html', form=form)
    else:
        form = PasteForm(request.form)
        if form.validate():
            user = current_user.user
            paste = save_paste_and_codes(form)
            followers = User.objects(followers=user)
            for follower in followers:
                create_message(follower, paste)
            return jsonify(success=True, hash_id=paste.hash_id)
        else:
            errors = form.errors
            errors['codes'] = [code.errors for code in form.codes]
            logger.info('Failed saving paste for reason: %s', errors)
            return jsonify(success=False, errors=errors)
Ejemplo n.º 53
0
def get_pastes_from_search(query_string, p=1):
    def get_string_by_keyword(keyword, query_string):
        string = ''
        result = re.search('\s*%s:([a-zA-Z+-_#]+)\s*' % keyword, query_string)
        if result:
            if len(result.groups()) == 1:
                string = result.groups()[0]
        return string, query_string.replace('%s:%s' % (keyword, string), '')

    tag, query_string = get_string_by_keyword('tag', query_string)
    user, query_string = get_string_by_keyword('user', query_string)
    keyword = query_string.strip()

    criteria = {'title__contains': keyword, 'is_private': False}
    if tag:
        criteria['tags'] = tag
    if user:
        user_object = User.objects(username=user).first()
        if user_object:
            criteria['user'] = user_object

    return keyword, Paste.objects(**criteria).order_by('-updated_at').paginate(p, per_page=2)