예제 #1
0
def github_link_account_behavior():
    url = github_apis.auth_user()
    auth = OAuth2(client_id=client_id, token=session['oauth_user_token'])
    res = requests.get(url, auth=auth)
    if res.status_code != 200:
        msg = 'GitHub authorization failed'
        flash(msg, 'danger')
        return redirect(url_for('main.index'))

    github_user = res.json()
    username = github_user.get('login')
    email = github_user.get('email')
    github_url = github_user.get('html_url')
    github_avatar_url = github_user.get('avatar_url')

    if not current_user.avatar_url:
        avatar_name = 'github_avatar_{0}.jpeg'.format(username)
        avatar_url = qiniu_fetch_img(github_avatar_url, avatar_name)
        current_user.avatar_url = avatar_url

    current_user.github_username = username
    current_user.github = github_url
    
    current_user.save()

    return redirect(url_for('main.index'))
def delete_quote(id):
    note = Note.objects(id=id).first()

    deleteNote = deleteQuoteForm(request.form)
    if request.method == 'POST':
        deleteNote = deleteQuoteForm(request.form)

        if deleteNote.validate == False:
            flash('Faliure', 'danger')
            return redirect(url_for('profile') + ('/' + current_user.slug))

        if deleteNote.validate_on_submit():
            note = Note.objects(id=id).first()

            current_user.notes.remove(note)
            current_user.save()

            note.delete()

            flash('Successfully deleted', 'warning')

    return render_template("delete.html",
                           title="delete",
                           delete_note=deleteNote,
                           note=note)
예제 #3
0
파일: mini.py 프로젝트: endsh/chiki
    def jscode(self):
        ct = request.headers.get('Content-Type', '')
        form = request.json if 'json' in ct else request.form
        code = form.get('code')
        if code:
            url = self.get_jscode_url(code)
            res = requests.get(url).json()
            if 'openid' in res:
                return self.success(res)

            current_app.logger.error('jscode: ' + json.dumps(res))
            return json_error(msg='获取session_key失败')
        elif current_user.is_authenticated():
            um.funcs.on_wechat_login('mini', '')
            try:
                if Item.bool('allow_invite', False, name='允许渠道'):
                    um.funcs.on_wechat_login('mini', '')
                current_user.wechat_user.update_info(
                    form.get('userInfo'), action='mini')
                current_user.wechat_user.save()
                current_user.wechat_user.sync(current_user)
                current_user.save()
            except:
                current_app.logger.error(traceback.format_exc())
            return json_success(data=um.funcs.userinfo(current_user))
        return json_error(key='LOGIN_REQIURED')
예제 #4
0
def authorize_facebook():
    import urllib.parse
    import urllib.request
    redirect_uri = app.config.get('SITE_URL') + '/admin/authorize_facebook'
    params = {'client_id': app.config.get('FACEBOOK_APP_ID'),
              'redirect_uri': redirect_uri,
              'scope': 'publish_stream'}

    code = request.args.get('code')
    if code:
        params['code'] = code
        params['client_secret'] = app.config.get('FACEBOOK_APP_SECRET')

        r = urllib.request.urlopen(
            'https://graph.facebook.com/oauth/access_token?'
            + urllib.parse.urlencode(params))
        payload = urllib.parse.parse_qs(r.read())

        access_token = payload[b'access_token'][0].decode('ascii')
        current_user.facebook_access_token = access_token
        current_user.save()
        return redirect(url_for('settings'))
    else:
        return redirect('https://graph.facebook.com/oauth/authorize?'
                        + urllib.parse.urlencode(params))
예제 #5
0
def remove_from_pull_list():
    """
    AJAX method

    Remove a favorite title from your pull list
    """
    try:
        # Get the index of the book to delete
        title = Title.query.get(long(request.form['id']))
        # Delete comic at desired index
        current_user.pull_list.remove(title)
        # Save updated user
        current_user.save()
        Bundle.refresh_user_bundle(current_user, current_wednesday())
        Bundle.refresh_user_bundle(current_user, next_wednesday())
        Bundle.refresh_user_bundle(current_user, two_wednesdays())
        response = {
            'status': 'success',
            'message': title.name+' removed from your pull list'
        }
    except:
        print "Unexpected error:", sys.exc_info()[1]
        response = {
            'status': 'error',
            'message': 'Something went wrong...'
        }
    return jsonify(response)
예제 #6
0
    def bind(self, args):
        if current_user.is_user():
            if current_user.email:
                abort(BINDED)

            current_user.email = args['email']
            if um.config.required_bind_password:
                current_user.password = args['password']
            current_user.save()
            return current_user

        user = um.models.User.objects(email=args['email']).first()
        if not user:
            user = um.models.User(
                email=args['email'],
                password=args['password']
                if um.config.required_bind_password else '',
                channel=get_channel(),
                spm=get_spm(),
                ip=get_ip(),
            )
            user.create()
        elif um.config.required_bind_password and user.password != args[
                'password']:
            abort(PASSWORD_ERROR)
        return user
예제 #7
0
def tos(json):
    if json.get('accept', False):
        current_user.tos = True
        current_user.save()
        return current_user.tos
    else:
        return {'error': 'tos acceptation error'}
예제 #8
0
파일: venmo_auth.py 프로젝트: mhz5/relay
 def get(self):
     """
     You can use request.args to get URL arguments from a url. Another name for URL arguments
     is a query string.
     What is a URL argument? It"s some data that is appended to the end of a url after a "?"
     that can give extra context or information.
   
     """
     AUTHORIZATION_CODE = request.args.get("code")
     data = {
         "client_id": CLIENT_ID,
         "client_secret": CLIENT_SECRET,
         "code" : AUTHORIZATION_CODE
         }
     url = "https://api.venmo.com/v1/oauth/access_token"
     response = requests.post(url, data)
     response_dict = response.json()
     access_token = response_dict.get("access_token")
     user = response_dict.get("user")
     print(user["id"])
     user_account = UserAccount(user=user["id"], access_token=access_token, api="venmo")
     user_account.save()
     for current_user_account in current_user.user_accounts:
         if current_user_account.api == "venmo":
             return redirect("/apps")
     current_user.user_accounts.append(user_account)
     current_user.save()
     session["venmo_token"] = access_token
     return redirect("/apps")
예제 #9
0
def change_email(token):
    if current_user.is_social():
        return redirect(url_for('index'))
    if current_user.verify_change_email_token(token):
        current_user.save()
        flash(_cfg('flash.change_email_success', 'Your email address has been updated.'), 'success')
    return redirect(url_for('index'))
예제 #10
0
def finalize():
    """
    3. step
    Finalize app install
    """
    param_dict = dict(request.args.items())
    api_key = current_app.config['SHOPIFY_API_KEY']
    secret = current_app.config['SHOPIFY_API_SECRET']
    shop_url = request.args['shop']

    # user should be authenticated
    if not current_user.is_authenticated:
        return redirect(url_for('main.signup', next=url_for('shopify.finalize', **param_dict)))

    shopify_api.Session.setup(api_key=api_key, secret=secret)
    shopify_api_session = shopify_api.Session(shop_url)

    try:
        shopify_api_session.request_token(param_dict)
    except HTTPError:
        # application is already installed in given shop from another account
        return redirect(
            url_for('dashboard.drip',
                    error='Application is already installed in given shop from another account')
        )

    # check if shopify integration is already registered for given user
    current_user.shopify_integration = ShopifyIntegration()
    current_user.shopify_integration.token = shopify_api_session.token
    current_user.shopify_integration.shop_url = shop_url
    current_user.shopify_integration.installed = True
    current_user.save()

    return redirect(url_for('main.index'))
예제 #11
0
def add_to_pull_list():
    form = AddToPullList()
    response = {'status': 'fail', 'message': 'Title not being tracked by Longboxed'}
    title_id = request.form.get('id', False) # Support both adding methods
    if form.validate_on_submit() or title_id:

        if title_id:
            title = Title.query.get_or_404(title_id)
        else:
            title = Title.query.filter_by(name=request.form['title']).first_or_404()

        if title and title not in current_user.pull_list:
            current_user.pull_list.append(title)
            current_user.save()
            Bundle.refresh_user_bundle(current_user, current_wednesday())
            Bundle.refresh_user_bundle(current_user, next_wednesday())
            Bundle.refresh_user_bundle(current_user, two_wednesdays())
            response = {
                'status': 'success',
                'message': '<strong>'+title.name+'</strong> has been added to your pull list!',
                'data': {
                    'title': title.name,
                    'title_id': title.id
                }
            }
        else:
            response = {
                'status': 'fail',
                'message': '<strong>'+title.name+'</strong> is already on your pull list!',
                'data': {
                    'title': title.name,
                    'title_id': title.id
                }
            }
    return jsonify(response)
예제 #12
0
def follow():
    id = request.form.get('pinner')
    user = User.objects.get(id=id)
    current_user.follower_array.append(user)
    current_user.save()
    flash("Following " + user.uname)
    return redirect("/viewprofile/" + current_user.uname + "/following")
예제 #13
0
def sports():

    sport = request.form['name'].lower()
    # You get this before the state changes, so its the opposite
    checked = True if request.form['checked'] == 'false' else False

    if current_user.is_anonymous:
        if not 'sports' in session:
            session['sports'] = []
        if checked:
            if not sport in session['sports']:
                session['sports'].append(sport)
        else:
            if sport in session['sports']:
                session['sports'].remove(sport)

    else:
        if checked:
            if not sport in current_user.sports:
                current_user.sports.append(sport)
        else:
            if sport in current_user.sports:
                current_user.sports.remove(sport)

        current_user.save()
    return redirect('/')
예제 #14
0
def before_request():
    """
    Before each resource request, update user's last_activity attribute.
    """
    if current_user.is_authenticated:
        current_user.last_active = datetime.utcnow()
        current_user.save()
예제 #15
0
def tos(json):
    if json.get('accept', False):
        current_user.tos = True
        current_user.save()
        return current_user.tos
    else:
        return {'error': 'tos acceptation error'}
예제 #16
0
    def bind(self, args):
        if current_user.is_user():
            if current_user.phone:
                abort(BINDED)

            current_user.phone = args['phone']
            if um.config.required_bind_password:
                current_user.password = args['password']
            current_user.save()
            return current_user

        user = um.models.User.objects(phone=args['phone']).first()
        if not user:
            user = um.models.User(
                phone=args['phone'],
                password=args['password'] if um.config.required_bind_password else '',
                channel=get_channel(),
                spm=get_spm(),
                ip=get_ip(),
            )
            user.create()
        elif um.config.required_bind_password:
            user.password = args['password']
            user.save()
        return user
예제 #17
0
파일: view.py 프로젝트: vpersie9/blog
def confirm_email(token):
    if current_user.confirm_change(token):
        current_user.email=current_user.confirm_change(token)
        current_user.avatar_hash=hashlib.md5(current_user.email.encode('utf-8')).hexdigest()
        current_user.save()
        return redirect(url_for('index.show'))
    flash(u'注册邮箱修改失败 请重新修改')
    return redirect(url_for('auth.change_email'))
예제 #18
0
파일: views.py 프로젝트: xuemy/flaskbb
def change_email():
    form = ChangeEmailForm(current_user)
    if form.validate_on_submit():
        current_user.email = form.new_email.data
        current_user.save()

        flash("Your email have been updated!", "success")
    return render_template("user/change_email.html", form=form)
예제 #19
0
def change_email():
    form = ChangeEmailForm(current_user)
    if form.validate_on_submit():
        current_user.email = form.new_email.data
        current_user.save()

        flash("Your email have been updated!", "success")
    return render_template("user/change_email.html", form=form)
예제 #20
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.password = form.new_password.data
        current_user.save()

        flash("Your password have been updated!", "success")
    return render_template("user/change_password.html", form=form)
예제 #21
0
 def settings(self):
     form = RegistrationForm(obj=current_user)
     form.accept_tos.validators = []
     form.password.validators = []
     if form.validate_on_submit():
         form.populate_obj(current_user)
         current_user.save()
     return _render_template('user/settings.html',form=form)
예제 #22
0
def updateBatch():
    if current_user.get_current_anno()[0] == 'new':
        return 'OK',200
    annoDic = current_user.load()
    newBatch = json.loads(request.form.get('batch'))
    annoDic[current_user.get_current_anno()[0]][current_user.get_current_anno()[1]] = newBatch
    current_user.save(annoDic)
    return 'OK',200
예제 #23
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        flash('Your password has been changed.', 'success')
        return redirect(url_for('users.settings'))
    return settings(passwordForm=form)
예제 #24
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        flash('Your password has been changed.', 'success')
        return redirect(url_for('users.settings'))
    return settings(passwordForm=form)
예제 #25
0
파일: views.py 프로젝트: xuemy/flaskbb
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        current_user.password = form.new_password.data
        current_user.save()

        flash("Your password have been updated!", "success")
    return render_template("user/change_password.html", form=form)
예제 #26
0
def register():
    """Registration Page"""
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(form.email.data, form.password.data)
        user.save()
        flash('Thanks for registering')
        return redirect('/')
    return render_template('user/register.html', form=form)
예제 #27
0
파일: account.py 프로젝트: isuker/snippets
def unfollow(user_id):
    user = User.query.get_or_404(user_id)
    current_user.unfollow(user)
    current_user.save()
    user.save()

    save_action('"' + current_user.username + '"' + u"关注 了 "+ '"' + user.username + '"')
    return jsonify(success=True,
                   reload=True)
예제 #28
0
def change_email():
    form = ChangeEmailForm()
    if form.validate_on_submit():
        new_email = form.email.data
        current_user.email = new_email
        current_user.save()
        flash('Your email address has been changed to {0}'.format(new_email), 'success')
        return redirect(url_for('users.settings'))
    return settings(emailForm=form)
예제 #29
0
def setPassword():
    form = PasswordForm(request.form)
    if request.method == "POST" and form.validate():
        hashedpwd = hashpw(form.pwd.data, gensalt(log_rounds=13))
        current_user.update(set__pwd=hashedpwd)
        current_user.save()
        flash("Password was changed successfully")
        return redirect('/settings')
    return render_template("newpassword.html", form=form, upform=UploadForm())
예제 #30
0
파일: apis.py 프로젝트: dodoru/chiki
    def post(self):
        if not current_user.is_user():
            abort(NEED_BIND)

        args = get_args()
        self.handle(args)
        current_user.save()

        return success(**userinfo(current_user))
예제 #31
0
 def post(self):
     logging.info(request.form)
     current_user.social.facebook(
         data={
             "app_id": request.form.get("app_id"),
             "secret": request.form.get("secret"),
         })
     current_user.save()
     return redirect(url_for('.index'))
예제 #32
0
def register():
    """Registration Page"""
    form = RegistrationForm(request.form)
    if request.method == "POST" and form.validate():
        user = User(form.email.data, form.password.data)
        user.save()
        flash("Thanks for registering")
        return redirect("/")
    return render_template("user/register.html", form=form)
예제 #33
0
파일: views.py 프로젝트: gasxia/WordRem
def complete():
    try:
        for word in current_user.curwords:
            current_user.remainwords.remove(word)
            current_user.hiswords.append(HisWords(word=word, date=date.today()))
        current_user.curwords = []
        current_user.save()
    except Exception as e:
        return jsonify(status="fail", error=e.message)
    return jsonify(status="success")
예제 #34
0
파일: view.py 프로젝트: love3forever/newgit
def email_reset_request():
    form = ResetEmailForm()
    if form.validate_on_submit():
        if form.oldemil.data == current_user.email:
            current_user.email = form.newemail.data
            current_user.save()
            flash('Email changed!')
            return redirect(url_for('main.main_index'))
        flash('Invalid email')
    return render_template('settings/resetemil.html', form=form)
예제 #35
0
파일: views.py 프로젝트: braceio/data
def unlink_gspread(key):
    user = _user_for_key(key)
    if not user:
        abort(404)
    sheetobj = next(i for i in user['spreadsheets'] if i['key'] == key)
    sheets = current_user.get('spreadsheets') or []
    sheets.remove(sheetobj)
    current_user['spreadsheets'] = sheets
    current_user.save()
    return jsonify({'count': len(sheets)})
예제 #36
0
파일: views.py 프로젝트: Atober/spellworks
 def _confirm_account():
     if current_user.confirmed:
         flash(u"你已经验证过邮箱了。")
     else:
         current_user.confirmed = True
         try:
             current_user.save()
         except BaseException, e:
             raise e
         flash(u"邮箱已经验证成功,欢迎。")
예제 #37
0
파일: auth.py 프로젝트: ogurtsov/funicular
def profile():
    form = ProfileForm()
    if request.method == 'POST':
        form = ProfileForm(request.form)
        if form.validate():
            current_user.set_password(form.new_password.data)
            current_user.save()
            flash({'type':'success', 'text':'Password updated'})
            return redirect('/')
    return render_template("/auth/profile.html", **locals())
예제 #38
0
def unlink_gspread(key):
    user = _user_for_key(key)
    if not user:
        abort(404)
    sheetobj = next(i for i in user['spreadsheets'] if i['key'] == key)
    sheets = current_user.get('spreadsheets') or []
    sheets.remove(sheetobj)
    current_user['spreadsheets'] = sheets
    current_user.save()
    return jsonify({'count': len(sheets)})
예제 #39
0
def change_user_details():
    form = ChangeUserDetailsForm(obj=current_user)

    if form.validate_on_submit():
        form.populate_obj(current_user)
        current_user.save()

        flash("Your details have been updated!", "success")

    return render_template("user/change_user_details.html", form=form)
예제 #40
0
def change_email():
    form = ChangeEmailForm()
    if form.validate_on_submit():
        new_email = form.email.data
        current_user.email = new_email
        current_user.save()
        flash('Your email address has been changed to {0}'.format(new_email),
              'success')
        return redirect(url_for('users.settings'))
    return settings(emailForm=form)
예제 #41
0
파일: views.py 프로젝트: Atober/spellworks
 def _confirm_account():
     if current_user.confirmed:
         flash(u"你已经验证过邮箱了。")
     else:
         current_user.confirmed = True
         try:
             current_user.save()
         except BaseException, e:
             raise e
         flash(u"邮箱已经验证成功,欢迎。")
예제 #42
0
파일: views.py 프로젝트: r2dev/NewID
def twitter_oauthorized():
    resp = twitter.authorized_response()
    if resp is None:
        flash('You denied the request to sign in')
    else:
        session['twitter_oauth'] = resp
        current_user.twitter = session['twitter_oauth'].get('screen_name')
        current_user.save()

    return redirect(url_for('main.index'))
예제 #43
0
    def post(self):
        args = self.get_args()
        self.validate(args)
        user = self.bind(args)
        if not current_user.is_user() and not current_user.user:
            current_user.user = user.id
            current_user.sync(user)
            current_user.save()

        um.models.UserLog.bind(user.id, args['device'], key=self.key)
        return self.success(user, args)
예제 #44
0
파일: view.py 프로젝트: love3forever/newgit
def password_reset_request():
    form = ResetPasswordForm()
    if form.validate_on_submit():
        if form.oldpsw.data == current_user.password:
            current_user.password = form.newpsw.data
            current_user.save()
            logout_user()
            flash('Password changed! Please Login in')
            return render_template('index.html')
        flash('Invalid password.')
    return render_template('settings/resetpsw.html', form=form)
예제 #45
0
파일: views.py 프로젝트: gasxia/WordRem
def setting():
    try:
        form = request.form
        current_user.wordtag = form.get('wordtag')
        current_user.daycount = form.get('daycount')
        current_user.hiswords = []
        current_user.remainwords = Word.objects(tags=current_user.wordtag)
        current_user.save()
    except Exception as e:
        return jsonify(status="fail", error=e.message)
    return jsonify(status="success")
예제 #46
0
파일: views.py 프로젝트: gasxia/WordRem
def complete():
    try:
        for word in current_user.curwords:
            current_user.remainwords.remove(word)
            current_user.hiswords.append(HisWords(word=word,
                                                  date=date.today()))
        current_user.curwords = []
        current_user.save()
    except Exception as e:
        return jsonify(status="fail", error=e.message)
    return jsonify(status="success")
예제 #47
0
def change_password():
    form = ChangePasswordForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.old_password.data):
            current_user.password = form.password.data
            current_user.save()
            flash('Your password has been updated.', 'success')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid password.')
    return render_template('auth/change-password.html', form=form)
예제 #48
0
파일: views.py 프로젝트: gasxia/WordRem
def setting():
    try:
        form = request.form
        current_user.wordtag = form.get('wordtag')
        current_user.daycount = form.get('daycount')
        current_user.hiswords = []
        current_user.remainwords = Word.objects(tags=current_user.wordtag)
        current_user.save()
    except Exception as e:
        return jsonify(status="fail", error=e.message)
    return jsonify(status="success")
예제 #49
0
def change_password():
    """
    Change logged in user's password.
    """
    form = ChangePasswordForm(request.json_multidict)
    if not form.validate_on_submit():
        return api_error(form.errors)
    if not current_user.check_password(form.current.data):
        return api_error(dict(form=['Current password is incorrect.']))
    current_user.set_password(form.new_password.data)
    current_user.save()
    return '', 200
예제 #50
0
def profile():
    form = ChangePass()
    if form.validate_on_submit():
        current_user.set_password(form.new_password.data)
        current_user.save()
        return redirect(url_for(resolve_confirm_status(current_user)))
    return set_template('panelbuilder.html',
                        form,
                        '.profile',
                        panel_args=dict(
                            patex=current_app.config['PAHDS']['profile'],
                            tadata=current_app.config['TADATA']['profile']))
예제 #51
0
def enable_tfa_via_app():
    opts = {'user': current_user}
    if request.method == 'GET':
        return render_template('enable_tfa_via_app.html', opts=opts)
    token = request.form['token']
    if token and current_user.totp.valid(token):
        current_user.account['totp_enabled_via_app'] = True
        current_user.save()
        return render_template('enable_tfa_via_app.html', opts=opts)
    else:
        opts['token_error'] = True
        return render_template('enable_tfa_via_app.html', opts=opts)
예제 #52
0
def toggle_compiler_state():
    if current_user.compiler_state == 'off':
        if current_user.droplet_id is None:
            droplet_id = create_compiler(current_user.username)
            current_user.droplet_id = droplet_id
        else:
            start_compiler(current_user.droplet_id)
        current_user.compiler_state = 'on'
    else:
        stop_compiler(current_user.droplet_id)
        current_user.compiler_state = 'off'
    current_user.save()
    return redirect(url_for('account'))
예제 #53
0
def authorized(resp):
    if resp is None:
        flash("You denied the request", "danger")
        return redirect(url_for(".index"))

    try:
        sa = current_user.social.facebook
        sa.token = resp.get('access_token')
        current_user.save()
    except Exception as e:
        logging.exception(e)

    return redirect(url_for(".verify"))
예제 #54
0
def save_timezone():
    if current_user and current_user.is_active():
        timezone = unicode(request.form.get("timezone")).strip()
        if timezone in pytz.country_timezones("US"):
            current_user.timezone = timezone
            current_user.save()
            return jsonify({'message': 'Timezone updated.'})
        else:
            return jsonify(
                {'message': 'Unrecognized timezone, please try again.'})
    else:
        return jsonify(
            {'message': 'Error updating timezone, please try again.'})
예제 #55
0
파일: views.py 프로젝트: Aaron1992/shiguang
def change_password():
    form = ChangePasswordForm()
    errors = None
    if form.validate_on_submit():
        current_user.password = form.new_password.data
        current_user.save()
        flash("Password updataed.", "success")
        return "passwordchanged"
    errors = form.old_password.errors
    return render_template("change-password.html",
                           user=current_user,
                           errors=errors,
                           form=form)