def favourites(): the_songs = Favourites.query.filter( Favourites.user_id == current_user.get_id()).all() if request.method == 'POST': if request.form['action'] == 'Add': if not request.form['name_song'] or len( request.form['name_song']) > 255: flash( 'Please add author and name of song between 0 and 255 characters. ', 'error') else: song = Favourites(request.form['name_song'], None, current_user.get_id()) db.session.add(song) db.session.commit() flash('Record was successfully added') return redirect(url_for('index')) if request.form['action'] == 'Del': if request.form['id_song'] and request.form['id_song'].isdigit: song_id = request.form['id_song'] res = Favourites.query.filter_by(id=song_id).delete( synchronize_session='fetch') if res == 0: flash('No such song.') else: flash('Record was deleted. ') db.session.commit() return redirect(url_for('index')) return render_template('favourites.html', songs=the_songs, title='Favourites')
def sell_coin(): try: # 挂售只针对NFT资产,别的资产不会被挂售,每次挂售数量都是单位1 data = request_data_to_dict() coin_id = int(data.get("coin_id")) coin_name = data.get('coin_name') pay_pwd = data.get('pay_pwd') page = data.get('page') price = abs( Decimal(data.get('sell_price')).quantize(Decimal("0.00000000"))) except Exception as e: abort(400) else: asset = Assets.get_or_none(Assets.id == coin_id) if asset.lock: flash('资产锁定不可挂售', 'take-error') return redirect(url_for('my_home', page=page)) query = Commodity.select().where( Commodity.asset == coin_id).count() # 被摆上过货架 print(query) # 验证密码 if len(pay_pwd) == 6 and verify_password(pay_pwd, current_user.pay_password): if query: with db.database.atomic(): # 如果有了挂售的定价标准,还得更新本次挂售的价格及价格单位 Commodity.update(price=price, status=1, created_at=datetime.now(), platform=2, seller=current_user.get_id()).where( Commodity.asset == coin_id).execute() Assets.update( lock=True, visible=0).where(Assets.id == coin_id).execute() else: with db.database.atomic(): c = Commodity.create( name=coin_name.strip(), status=1, platform=2, commodity_type=1, price=price, price_unit='WBT', # 暂定 asset=coin_id, desc=asset.desc, seller=current_user.get_id()) c.save() Assets.update( lock=True, visible=0).where(Assets.id == coin_id).execute() messages = mi['sell-success'] if session.get( 'lang', 'en') == 'en' else mi['sell-success-zh'] flash(messages, 'order-success') return redirect(url_for('user_sales')) messages = mi['pay-pwd-err'] if session.get( 'lang', 'en') == 'en' else mi['pay-pwd-err-zh'] flash(messages, 'order-error') return redirect(url_for('my_home', page=page))
def _get_current_userprofile(): if current_user.is_anonymous: return AnonymousUserProfile() profile = g.get("userprofile", UserProfile.get_by_userid(current_user.get_id())) if profile is None: profile = UserProfile(user_id=int(current_user.get_id())) g.userprofile = profile return profile
def user_recharge(): if request.method == "GET": query = Coin.select().dicts() coin = [q for q in query] pairs = ExchangePair.select() args = request.args page = int(args.get('page', '1')) if (args.get('page', '1')).isdigit() else 1 query_recharge = Recharge.select().where( Recharge.user == current_user.get_id()).order_by( Recharge.created_at.desc()) total_count = query_recharge.count() pagination = Pagination(page, PER_PAGE, total_count) query_recharge = query_recharge.paginate(page=page, paginate_by=PER_PAGE) return render_template(wrap_template_name("user/home.html"), records=query_recharge, infos=coin, pairs=pairs, pagination=pagination) elif request.method == "POST": try: data = request_data_to_dict() coin_type_id = int(data.get("type")[0]) except Exception: abort(400) else: cate = Coin.get_or_none(Coin.id == coin_type_id) if not cate: abort(400) exist_recharge = Recharge.get_or_none( Recharge.user == current_user.get_id(), # Recharge.cate == coin_type_id, Recharge.status == types.recharge_status["pending"]) if exist_recharge: messages = mi['recharge-err'] if session.get( 'lang', 'en') == 'en' else mi['recharge-err-zh'] flash(messages, 'recharge-error') # Recharge.update(value=amount).where(Recharge.id == rid).execute() return redirect( url_for('recharge_detail', rid=exist_recharge.id)) else: recharge = Recharge.create( value=0, receiver=current_user.eth_address.lower(), user=current_user.get_id(), cate=coin_type_id) recharge_created.send("app", addr=recharge.user.eth_address) return redirect(url_for("recharge_detail", rid=recharge.id))
def set_session_info(app, response, **extra): """Add X-Session-ID and X-User-ID to http response.""" session_id = getattr(session, 'sid_s', None) if session_id: response.headers['X-Session-ID'] = session_id if current_user.is_authenticated: response.headers['X-User-ID'] = current_user.get_id()
def edit(): form = EditForm() form.email.data = current_user.email form.first_name.data = current_user.first_name form.last_name.data = current_user.last_name form.share_favourites.data = current_user.share_favourites if request.method == 'POST': if len(request.form['first_name']) < 255 and len( request.form['last_name']) < 255: usr = User.query.filter_by(id=current_user.get_id()).first() usr.first_name = request.form['first_name'] usr.last_name = request.form['last_name'] if 'share_favourites' in request.form: usr.share_favourites = 1 else: usr.share_favourites = 0 db.session.add(usr) db.session.commit() flash('Your changes have been saved.') # return redirect(url_for('users')) else: flash( 'Please, fill the form correctly: up to 255 characters for each field.' ) return render_template('edit.html', form=form)
def index(): """List linked accounts.""" oauth = current_app.extensions['oauthlib.client'] services = [] service_map = {} i = 0 for appid, conf in six.iteritems( current_app.config['OAUTHCLIENT_REMOTE_APPS']): if not conf.get('hide', False): services.append( dict(appid=appid, title=conf['title'], icon=conf.get('icon', None), description=conf.get('description', None), account=None)) service_map[oauth.remote_apps[appid].consumer_key] = i i += 1 # Fetch already linked accounts accounts = RemoteAccount.query.filter_by( user_id=current_user.get_id()).all() for a in accounts: if a.client_id in service_map: services[service_map[a.client_id]]['account'] = a # Sort according to title services.sort(key=itemgetter('title')) return render_template("invenio_oauthclient/settings/index.html", services=services)
def support(): """Render contact form.""" uap = user_agent_information() form = contact_form_factory() if form.validate_on_submit(): attachments = request.files.getlist("attachments") if attachments and not check_attachment_size(attachments): form.attachments.errors.append('File size exceeded. ' 'Please add URLs to the files ' 'or make a smaller selection.') else: context = { 'user_id': current_user.get_id(), 'info': form.data, 'uap': uap } send_support_email(context) send_confirmation_email(context) flash(_( 'Request sent successfully, ' 'You should receive a confirmation email within several ' 'minutes - if this does not happen you should retry or send ' 'us an email directly to [email protected].'), category='success') return redirect(url_for('zenodo_frontpage.index')) return render_template('zenodo_support/contact_form.html', uap=uap, form=form, categories=current_support_categories)
def create_push_subscription(): json_data = request.get_json() subscription = PushSubscription.update_or_create( user_id=current_user.get_id(), subscription_json=json_data['subscription_json'], keys=["subscription_json"]) return jsonify({"status": "success", "result": subscription.todict()})
def application_comment_action(application_id, comment_id, action): form_comment = HrApplicationCommentForm() if current_user.has_role("recruiter") or current_user.has_role("admin"): if HrApplication.query.filter_by(id=int(application_id)).first(): if HrApplicationComment.query.filter_by(id=comment_id).first(): comment = HrApplicationComment.query.filter_by(id=comment_id).first() if comment.user_id == current_user.get_id() or current_user.has_role("admin"): if request.method == 'POST': if action == "edit": if form_comment.validate_on_submit(): flash("comment valid", category="message") HrManager.edit_comment(comment, form_comment.comment.data) elif action == "delete": print "wat" comment.delete() elif action == "delete": print "wat" comment.delete() return redirect(url_for('recruit.application_view', application_id=application_id)) return redirect(url_for('recruit.applications'))
def application_view(application_id): comments = [] characters = [] form_app = HrApplicationForm() form_comment = HrApplicationCommentForm() application = HrApplication.query.filter_by(id=application_id).first() if application: if current_user.has_role("recruiter") or current_user.has_role("admin"): characters = EveCharacter.query.filter_by(user_id=application.user_id).all() comments = HrApplicationComment.query.filter_by(application_id=application_id).all() return render_template('recruit/application.html', application=application, characters=characters, comments=comments, form_comment=form_comment, form_app=form_app) elif int(application.user_id) == int(current_user.get_id()): return render_template('recruit/application.html', application=application, characters=characters, comments=comments, form_comment=form_comment, form_app=form_app) return redirect(url_for('recruit.applications'))
def api_add(): form = UpdateKeyForm() if form.validate_on_submit(): characters = EveApiManager.get_characters_from_api(form.data['api_id'], form.data['api_key']) if EveManager.create_api_keypair(form.data['api_id'], form.data['api_key'], current_user.get_id()): EveManager.create_alliances_from_list(characters) EveManager.create_corporations_from_character_list(characters) character_creation = EveManager.create_characters_from_list(characters, current_user, form.data['api_id']) if character_creation: flash(character_creation, category="message") # else: # flash("Character error, RIP. (contact IT)", category="message") else: flash("API Key already in use", category='message') return render_template("users/api_add.html", form=form) return redirect(url_for('user.api_manage')) else: return render_template("users/api_add.html", form=form)
def application_create(): auth_info = AuthInfoManager.get_or_create(current_user) form = HrApplicationForm() characters = EveCharacter.query.filter_by( user_id=current_user.get_id()).all() character_choices = [] for character in characters: character_choices = character_choices + [ (character.character_id, character.character_name) ] form.characters.choices = character_choices if request.method == 'POST': if form.validate_on_submit(): application = HrManager.create_application( form, main_character_name=current_user.auth_info[0].main_character. character_name, user=current_user) flash("Application Created, apply in game with \"" + url_for('recruit.application_view', _external=True, application_id=application.id) + "\" in the body", category='message') return redirect( url_for('recruit.application_view', application_id=application.id)) return render_template('recruit/application_create.html', form=form)
def get_list(self, page, sort_column, sort_desc, search, filters, execute=True, page_size=None): count, query = super(GroupBasedView, self).get_list(page, sort_column, sort_desc, search, filters, execute=False, page_size=None) user_record = User.query.get(current_user.get_id()).infos group_records = [] res = [] # 当前model 过滤条件为用户info for info in user_record: group_records += WechatGroup.query.filter_by( wechat_info_id=info.id).all() for group in group_records: res += query.from_self().filter_by(wechat_group_id=group.id).all() query = res return count, query
def get_permission(record, fjson): """Get download file permission. @param record: @param fjson: @return: """ user_id = current_user.get_id() record_id = record.get('recid') file_name = fjson.get('filename') current_time = dt.now() duration = current_time - \ timedelta(days=current_app.config['WEKO_RECORDS_UI_DOWNLOAD_DAYS']) list_permission = FilePermission.find_list_permission_by_date( user_id, record_id, file_name, duration) if list_permission: permission = list_permission[0] if permission.status == 1: return permission else: activity_id = permission.usage_application_activity_id activity = WorkActivity() steps = activity.get_activity_steps(activity_id) if steps: for step in steps: if step and step['Status'] == 'action_canceled': return None return permission else: return None
def get_list(self, page, sort_column, sort_desc, search, filters, execute=True, page_size=None): # print(filters) # print('this is filter') # # for i in current_user.infos: # filters.append((5, 'Wechat User Id', str(i.id))) # print(filter) count, query = super(BaseUserView, self).get_list(page, sort_column, sort_desc, search, filters, execute=False, page_size=None) # 当前用户的infos user_record = User.query.get(current_user.get_id()).infos res = [] # 当前model 过滤条件为用户info for info in user_record: res += query.from_self().filter_by(wechat_info_id=info.id).all() query = res return count, query
def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :param provider_id: The provider ID the connection shoudl be made to """ cv.setdefault('user_id', current_user.get_id()) connection = _datastore.find_connection( provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id']) if connection is None: after_this_request(_commit) connection = _datastore.create_connection(**cv) msg = ('Connection established to %s' % provider.name, 'success') connection_created.send(current_app._get_current_object(), user=current_user._get_current_object(), connection=connection) else: msg = ('A connection is already established with %s ' 'to your account' % provider.name, 'notice') connection_failed.send(current_app._get_current_object(), user=current_user._get_current_object()) redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'), get_url(config_value('CONNECT_ALLOW_VIEW'))) do_flash(*msg) return redirect(redirect_url)
def connect_handler(cv, provider): """Shared method to handle the connection process :param connection_values: A dictionary containing the connection values :param provider_id: The provider ID the connection shoudl be made to """ cv.setdefault('user_id', current_user.get_id()) connection = _datastore.find_connection( provider_id=cv['provider_id'], provider_user_id=cv['provider_user_id']) if connection is None: after_this_request(_commit) connection = _datastore.create_connection(**cv) msg = ('Connection established to %s' % provider.name, 'success') connection_created.send(current_app._get_current_object(), user=current_user._get_current_object(), connection=connection) else: msg = ('A connection is already established with %s ' 'to your account' % provider.name, 'notice') connection_failed.send(current_app._get_current_object(), user=current_user._get_current_object()) next_url = request.form.get('next', get_post_login_redirect()) redirect_url = (next_url or session.pop( config_value('POST_OAUTH_CONNECT_SESSION_KEY'), get_url(config_value('CONNECT_ALLOW_VIEW')))) do_flash(*msg) return redirect(redirect_url)
def my_home(): curr_login_user = current_user.get_id() coin = Coin.select() game = GameType.select() pairs = ExchangePair.select() args = request.args page = int(args.get('page', '1')) if (args.get('page', '1')).isdigit() else 1 query_coin = ShopCoin.select().where( ShopCoin.owner == curr_login_user).order_by(ShopCoin.created_at.desc()) query_assets = Assets.select().where( Assets.owner == curr_login_user).order_by(Assets.id.desc()) query_coin_count = query_coin.count() query_assets_count = query_assets.count() total_count = query_coin_count + query_assets_count pagination = Pagination(page, PER_PAGE, total_count) # print(dir(query_coin)) # query_coin = query_coin.paginate(page=page,paginate_by=PER_PAGE) # query_assets = query_assets.paginate(page=page,paginate_by=PER_PAGE) data = [q for q in query_coin] + [q for q in query_assets] data = data[(page - 1) * PER_PAGE:page * PER_PAGE] return render_template(wrap_template_name("user/home.html"), items=data, infos=coin, pairs=pairs, pagination=pagination, page=page, game=game)
def remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user, provider_user_id=provider_user_id) deleted = _datastore.delete_connection(user_id=current_user.get_id(), provider_id=provider_id, provider_user_id=provider_user_id) if deleted: after_this_request(_commit) msg = ('Connection to %(provider)s removed' % ctx, 'info') connection_removed.send(current_app._get_current_object(), user=current_user._get_current_object(), provider_id=provider_id) else: msg = ('Unabled to remove connection to %(provider)s' % ctx, 'error') do_flash(*msg) return redirect(request.referrer or get_post_login_redirect())
def application_interact(application_id, action): application_status = None if current_user.main_character_id == None: return redirect(url_for('user.eve_characters')) application = HrApplication.query.filter_by(id=application_id).first() if application: if current_user.has_role('admin') or current_user.has_role('recruiter') or current_user.has_role('reviewer'): if current_user.has_role("admin") or (action not in ['delete', 'hide', 'unhide']): if current_user.has_role('recruiter') or current_user.has_role('admin') or (action not in ['approve', 'reject', 'close', 'training']): application_status = RecruitManager.alter_application(application, action, current_user) flash("%s's application %s" % (application.main_character_name, application_status), category='message') elif application.user_id == current_user.get_id(): if action == "delete" and application.approve_deny == "New": application_status = RecruitManager.alter_application(application, action, current_user) flash("%s's application %s" % (application.main_character, application_status), category='message') if action == 'training' or action == 'hide': return redirect(request.referrer) elif application_status and application_status != "deleted": return redirect(url_for('recruit.application_view', application_id=application.id)) return redirect(url_for('recruit.applications'))
def token_getter(remote, token=''): """Retrieve OAuth access token. Used by flask-oauthlib to get the access token when making requests. :param token: Type of token to get. Data passed from ``oauth.request()`` to identify which token to retrieve. """ session_key = token_session_key(remote.name) if session_key not in session and current_user.is_authenticated: # Fetch key from token store if user is authenticated, and the key # isn't already cached in the session. remote_token = RemoteToken.get( current_user.get_id(), remote.consumer_key, token_type=token, ) if remote_token is None: return None # Store token and secret in session session[session_key] = remote_token.token() return session.get(session_key, None)
def application_comment_action(application_id, comment_id, action): form_comment = HrApplicationCommentForm() if current_user.has_role("recruiter") or current_user.has_role("admin"): if HrApplication.query.filter_by(id=int(application_id)).first(): if HrApplicationComment.query.filter_by(id=comment_id).first(): comment = HrApplicationComment.query.filter_by( id=comment_id).first() if comment.user_id == current_user.get_id( ) or current_user.has_role("admin"): if request.method == 'POST': if action == "edit": if form_comment.validate_on_submit(): flash("comment valid", category="message") HrManager.edit_comment( comment, form_comment.comment.data) elif action == "delete": print "wat" comment.delete() elif action == "delete": print "wat" comment.delete() return redirect( url_for('recruit.application_view', application_id=application_id)) return redirect(url_for('recruit.applications'))
def index(): """List linked accounts.""" oauth = current_app.extensions["oauthlib.client"] services = [] service_map = {} i = 0 for appid, conf in six.iteritems(current_app.config["OAUTHCLIENT_REMOTE_APPS"]): if not conf.get("hide", False): services.append( dict( appid=appid, title=conf["title"], icon=conf.get("icon", None), description=conf.get("description", None), account=None, ) ) service_map[oauth.remote_apps[appid].consumer_key] = i i += 1 # Fetch already linked accounts accounts = RemoteAccount.query.filter_by(user_id=current_user.get_id()).all() for a in accounts: if a.client_id in service_map: services[service_map[a.client_id]]["account"] = a # Sort according to title services.sort(key=itemgetter("title")) return render_template("invenio_oauthclient/settings/index.html", services=services)
def is_same_user(user_id): """ Checks if provided authorization is for same User as user_id. This is not a decorator as we sometimes need to use it in the view. :param user_id: Id of the user the url belongs to :type user_id: int """ if current_user.has_role("admin"): return True elif current_user.is_authenticated: return int(current_user.get_id()) == user_id elif request.authorization: if _check_http_auth(): return int(current_user.get_id()) == user_id return False
def application_interact(application_id, action): application_status = None auth_info = AuthInfoManager.get_or_create(current_user) if auth_info.main_character_id == None: return redirect(url_for('user.eve_characters')) application = HrApplication.query.filter_by(id=application_id).first() if application: # alter_application takes one of 4 actions if current_user.has_role("admin") or current_user.has_role( "recruiter"): if current_user.has_role("admin") or action != "delete": application_status = HrManager.alter_application( application, action, current_user) flash("%s's application %s" % (application.main_character_name, application_status), category='message') elif application.user_id == current_user.get_id(): if action == "delete" and application.approve_deny == "Pending": application_status = HrManager.alter_application( application, action, current_user) flash("%s's application %s" % (application.main_character, application_status), category='message') if application_status and application_status != "deleted": return redirect( url_for('recruit.application_view', application_id=application.id)) return redirect(url_for('recruit.applications'))
def jwt_create_token(user_id=None, additional_data=None): """Encode the JWT token. :param int user_id: Addition of user_id. :param dict additional_data: Additional information for the token. :returns: The encoded token. :rtype: str .. note:: Definition of the JWT claims: * exp: ((Expiration Time) expiration time of the JWT. * sub: (subject) the principal that is the subject of the JWT. * jti: (JWT ID) UID for the JWT. """ # Create an ID uid = str(uuid.uuid4()) # The time in UTC now now = datetime.utcnow() # Build the token data token_data = { 'exp': now + current_app.config['ACCOUNTS_JWT_EXPIRATION_DELTA'], 'sub': user_id or current_user.get_id(), 'jti': uid, } # Add any additional data to the token if additional_data is not None: token_data.update(additional_data) # Encode the token and send it back encoded_token = encode( token_data, current_app.config['ACCOUNTS_JWT_SECRET_KEY'], current_app.config['ACCOUNTS_JWT_ALOGORITHM']).decode('utf-8') return encoded_token
def application_interact(application_id, action): application_status = None auth_info = AuthInfoManager.get_or_create(current_user) if auth_info.main_character_id == None: return redirect(url_for('user.eve_characters')) application = HrApplication.query.filter_by(id=application_id).first() if application: # alter_application takes one of 4 actions if current_user.has_role("admin") or current_user.has_role("recruiter"): if current_user.has_role("admin") or action != "delete": application_status = HrManager.alter_application(application, action, current_user) flash("%s's application %s" % (application.main_character_name, application_status), category='message') elif application.user_id == current_user.get_id(): if action == "delete" and application.approve_deny == "Pending": application_status = HrManager.alter_application(application, action, current_user) flash("%s's application %s" % (application.main_character, application_status), category='message') if application_status and application_status != "deleted": return redirect(url_for('recruit.application_view', application_id=application.id)) return redirect(url_for('recruit.applications'))
def api_add(): form = UpdateKeyForm() if form.validate_on_submit(): characters = EveApiManager.get_characters_from_api( form.data['api_id'], form.data['api_key']) if EveManager.create_api_keypair(form.data['api_id'], form.data['api_key'], current_user.get_id()): EveManager.create_alliances_from_list(characters) EveManager.create_corporations_from_character_list(characters) character_creation = EveManager.create_characters_from_list( characters, current_user, form.data['api_id']) if character_creation: flash(character_creation, category="message") # else: # flash("Character error, RIP. (contact IT)", category="message") else: flash("API Key already in use", category='message') return render_template("users/api_add.html", form=form) return redirect(url_for('user.api_manage')) else: return render_template("users/api_add.html", form=form)
def application_view(application_id): comments = [] characters = [] form_app = HrApplicationForm() form_comment = HrApplicationCommentForm() application = HrApplication.query.filter_by(id=application_id).first() if application: if current_user.has_role("recruiter") or current_user.has_role( "admin"): characters = EveCharacter.query.filter_by( user_id=application.user_id).all() comments = HrApplicationComment.query.filter_by( application_id=application_id).all() return render_template('recruit/application.html', application=application, characters=characters, comments=comments, form_comment=form_comment, form_app=form_app) elif int(application.user_id) == int(current_user.get_id()): return render_template('recruit/application.html', application=application, characters=characters, comments=comments, form_comment=form_comment, form_app=form_app) return redirect(url_for('recruit.applications'))
def mentee(): """ serves a page with tasks by the mentee and a form to add new tasks additionally a button to logout. Admin gets a button to access admin panel. KISS. """ current_user_id = current_user.get_id() user_obj = get_mentee_data(current_user_id) return render_template('mentee.html', user=user_obj)
def eve_main_character_change(character_id): if EveManager.check_if_character_owned_by_user(character_id, current_user.get_id()): AuthInfoManager.update_main_character_id(character_id, current_user) return redirect(url_for('user.eve_characters')) return redirect(url_for('user.eve_characters'))
def delete_user(user_id): user = RolesUsers.query.filter_by(user_id=user_id).first() if user.role_id == 1: # role_id = 1 => Role Admin id = current_user.get_id() if int(id) == int(user_id): User.query.filter_by(id=user_id).delete() RolesUsers.query.filter_by(user_id=user_id).delete() try: db.session.commit() except OperationalError: admin.logger.error( "Operational Error permission access database") flask_login.logout_user() return redirect(url_for('security.login')) else: # role_id != 1 => Role User User.query.filter_by(id=user_id).delete() RolesUsers.query.filter_by(user_id=user_id).delete() try: db.session.commit() except OperationalError: admin.logger.error( "Operational Error permission access database") return redirect(url_for('admin.index')) else: id = current_user.get_id() if int(id) == int(user_id): User.query.filter_by(id=user_id).delete() RolesUsers.query.filter_by(user_id=user_id).delete() try: db.session.commit() except OperationalError: admin.logger.error( "Operational Error permission access database") flask_login.logout_user() return redirect(url_for('security.login')) else: User.query.filter_by(id=user_id).delete() RolesUsers.query.filter_by(user_id=user_id).delete() try: db.session.commit() except OperationalError: admin.logger.error( "Operational Error permission access database") flash("Utilisateur supprimé", "success") return redirect(url_for('admin.index'))
def applications(page=1): auth_info = AuthInfoManager.get_or_create(current_user) query = HrApplication.query.filter(HrApplication.hidden == False, HrApplication.user_id == current_user.get_id()) personal_applications = query.paginate(page, current_app.config['MAX_NUMBER_PER_PAGE'], False) return render_template('recruit/applications.html', personal_applications=personal_applications)
def encrypt_resource(string): user_id = current_user.get_id() key = user_id or current_app.config['RESOURCE_KEY'] access = 'user' if user_id else 'public' return url_for("download_resource", encrypted=itsdangerous.URLSafeSerializer( key, salt=access).dumps(string), access=access)
def ils_jwt_create_token(): """JWT creation factory.""" user_id = current_user.get_id() additional_data = {"locationPid": "1"} if user_id: roles = [role.name for role in current_user.roles] username = current_userprofile.username or current_user.email additional_data.update({"roles": roles, "username": username}) return jwt_create_token(user_id=user_id, additional_data=additional_data)
def _get_current_userprofile(): """Get current user profile. .. note:: If the user is anonymous, then a :class:`invenio_userprofiles.models.AnonymousUserProfile` instance is returned. :returns: The :class:`invenio_userprofiles.models.UserProfile` instance. """ if current_user.is_anonymous: return AnonymousUserProfile() profile = g.get('userprofile', UserProfile.get_by_userid(current_user.get_id())) if profile is None: profile = UserProfile(user_id=int(current_user.get_id())) g.userprofile = profile return profile
def load_user_collections(app, user): """Load user restricted collections upon login. Receiver for flask_login.user_logged_in """ user_collections = set( [a.argument for a in ActionUsers.query.filter_by( action='view-restricted-collection', user_id=current_user.get_id()).all()] ) session['restricted_collections'] = user_collections
def new_task(): """ An api to add a new task. API needs authentication, and the task will be added to the authenticated user's tasks. @:param task: text of the task to be added in post request body """ task = request.form.get('task') current_user_id = current_user.get_id() add_task(current_user_id, task) return redirect(url_for('mentee'))
def applications(page=1): auth_info = AuthInfoManager.get_or_create(current_user) query = HrApplication.query.filter( HrApplication.hidden == False, HrApplication.user_id == current_user.get_id()) personal_applications = query.paginate( page, current_app.config['MAX_NUMBER_PER_PAGE'], False) return render_template('recruit/applications.html', personal_applications=personal_applications)
def load_user_collections(app, user): """Load user restricted collections upon login. Receiver for flask_login.user_logged_in """ user_collections = set([ a.argument for a in ActionUsers.query.filter_by(action='view-restricted-collection', user_id=current_user.get_id()).all() ]) session['restricted_collections'] = user_collections
def _get_current_userprofile(): """Get current user profile. .. note:: If the user is anonymous, then a :class:`invenio_userprofiles.models.AnonymousUserProfile` instance is returned. :returns: The :class:`invenio_userprofiles.models.UserProfile` instance. """ if current_user.is_anonymous: return AnonymousUserProfile() profile = g.get( 'userprofile', UserProfile.get_by_userid(current_user.get_id())) if profile is None: profile = UserProfile(user_id=int(current_user.get_id())) g.userprofile = profile return profile
def create_job(): form = JobForm() if form.validate_on_submit(): user = None if current_user.get_id() is not None: user = current_user job = api_job.create(user=user, **form.data) return redirect(url_for('.detail_job', job_id=job.id)) return render_template('job/create.html', form=form)
def apply_joinclass(class_id): """申请加入""" #如果没有填写班级的个人信息。则先提示要填写。不然不能加入。 if current_user.profile is None: flash(u'你还没有填写班级个人信息,补充后才能申请加入班级') #form = MemberInfoForm() #return render_template('profile_class_memberinfo.html', form=form) return redirect(url_for('security-frontend.create_profile')) #action =1 表示加入 apply = api_apply.create(action=1, class_id=class_id, user_id=current_user.get_id()) return redirect(url_for('.list_myclass'))
def _app_on_identity_loaded(sender, identity): """Define dxc needed flask_pricipal identity loaded handler. :param sender: Signle sender. "param identity: Identity. """ # identity.provides.add(ItemNeed('delete', 13, 'blog')) if current_user.get_id() is not None: for right in current_user.rights: identity.provides.add(RightNeed(right.action, right.app, right.entity)) for role in current_user.roles: for r in role.rights: identity.provides.add(RightNeed(r.action, r.app, r.entity))
def support(): """Render contact form.""" uap = user_agent_information() form = contact_form_factory() if form.validate_on_submit(): attachments = request.files.getlist("attachments") if attachments and not check_attachment_size(attachments): form.attachments.errors.append('File size exceeded. ' 'Please add URLs to the files ' 'or make a smaller selection.') else: context = { 'user_id': current_user.get_id(), 'info': form.data, 'uap': uap } try: send_support_email(context) send_confirmation_email(context) except smtplib.SMTPSenderRefused: flash( _('There was an issue sending an email to the provided ' 'address, please make sure it is correct. ' 'If this issue persists you can send ' 'us an email directly to [email protected].'), category='danger' ) except Exception: flash( _("There was an issue sending the support request." 'If this issue persists send ' 'us an email directly to [email protected].'), category='danger' ) raise else: flash( _('Request sent successfully. ' 'You should receive a confirmation email within several ' 'minutes - if this does not happen you should retry or ' 'send us an email directly to [email protected].'), category='success' ) return redirect(url_for('zenodo_frontpage.index')) return render_template( 'zenodo_support/contact_form.html', uap=uap, form=form, categories=current_support_categories )
def delete(user_id): """Delete spam.""" # Only admin can access this view if not Permission(ActionNeed('admin-access')).can(): abort(403) user = User.query.get(user_id) deleteform = DeleteSpamForm() communities = Community.query.filter_by(id_user=user.id) rs = RecordsSearch(index='records').query( Q('query_string', query="owners: {0}".format(user.id))) rec_count = rs.count() ctx = { 'user': user, 'form': deleteform, 'is_new': False, 'communities': communities, 'rec_count': rec_count, } if deleteform.validate_on_submit(): if deleteform.remove_all_communities.data: for c in communities: if not c.deleted_at: if not c.description.startswith('--SPAM--'): c.description = '--SPAM--' + c.description if c.oaiset: db.session.delete(c.oaiset) c.delete() db.session.commit() if deleteform.deactivate_user.data: _datastore.deactivate_user(user) db.session.commit() # delete_record function commits the session internally # for each deleted record if deleteform.remove_all_records.data: for r in rs.scan(): delete_record(r.meta.id, 'spam', int(current_user.get_id())) flash("Spam removed", category='success') return redirect(url_for('.delete', user_id=user.id)) else: records = islice(rs.scan(), 10) ctx.update(records=records) return render_template('zenodo_spam/delete.html', **ctx)
def security(): """View for security page.""" sessions = SessionActivity.query_by_user( user_id=current_user.get_id() ).all() master_session = None for index, session in enumerate(sessions): if SessionActivity.is_current(session.sid_s): master_session = session del sessions[index] return render_template( current_app.config['ACCOUNTS_SETTINGS_SECURITY_TEMPLATE'], formclass=RevokeForm, sessions=[master_session] + sessions, is_current=SessionActivity.is_current )
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account.""" if not current_user.is_authenticated: return current_app.login_manager.unauthorized() account = RemoteAccount.get(user_id=current_user.get_id(), client_id=remote.consumer_key) orcid = account.extra_data.get('orcid') if orcid: oauth_unlink_external_id(dict(id=orcid, method='orcid')) if account: with db.session.begin_nested(): account.delete() return redirect(url_for('invenio_oauthclient_settings.index'))
def delete(pid=None, record=None, depid=None, deposit=None): """Delete a record.""" # View disabled until properly implemented and tested. try: doi = PersistentIdentifier.get('doi', record['doi']) except PIDDoesNotExistError: doi = None owners = User.query.filter(User.id.in_(record.get('owners', []))).all() pids = [pid, depid, doi] if 'conceptdoi' in record: conceptdoi = PersistentIdentifier.get('doi', record['conceptdoi']) pids.append(conceptdoi) else: conceptdoi = None if 'conceptrecid' in record: conceptrecid = PersistentIdentifier.get('recid', record['conceptrecid']) pids.append(conceptrecid) else: conceptrecid = None form = RecordDeleteForm() form.standard_reason.choices = current_app.config['ZENODO_REMOVAL_REASONS'] if form.validate_on_submit(): reason = form.reason.data or dict( current_app.config['ZENODO_REMOVAL_REASONS'] )[form.standard_reason.data] delete_record(record.id, reason, int(current_user.get_id())) flash( _('Record %(recid)s and associated objects successfully deleted.', recid=pid.pid_value), category='success' ) return redirect(url_for('zenodo_frontpage.index')) return render_template( 'zenodo_deposit/delete.html', form=form, owners=owners, pid=pid, pids=pids, record=record, deposit=deposit, )
def revoke_session(): """Revoke a session.""" form = RevokeForm(request.form) if not form.validate_on_submit(): abort(403) sid_s = form.data['sid_s'] if SessionActivity.query.filter_by( user_id=current_user.get_id(), sid_s=sid_s).count() == 1: delete_session(sid_s=sid_s) db.session.commit() if not SessionActivity.is_current(sid_s=sid_s): # if it's the same session doesn't show the message, otherwise # the session will be still open without the database record flash('Session {0} successfully removed.'.format(sid_s), 'success') else: flash('Unable to remove the session {0}.'.format(sid_s), 'error') return redirect(url_for('invenio_accounts.security'))
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account.""" if not current_user.is_authenticated: return current_app.login_manager.unauthorized() remote_account = RemoteAccount.get(user_id=current_user.get_id(), client_id=remote.consumer_key) external_method = 'github' external_ids = [i.id for i in current_user.external_identifiers if i.method == external_method] if external_ids: oauth_unlink_external_id(dict(id=external_ids[0], method=external_method)) if remote_account: with db.session.begin_nested(): remote_account.delete() return redirect(url_for('invenio_oauthclient_settings.index'))
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account. This default handler will just delete the remote account link. You may wish to extend this module to perform clean-up in the remote service before removing the link (e.g. removing install webhooks). """ if not current_user.is_authenticated: return current_app.login_manager.unauthorized() with db.session.begin_nested(): account = RemoteAccount.get( user_id=current_user.get_id(), client_id=remote.consumer_key ) if account: account.delete() return redirect(url_for('invenio_oauthclient_settings.index'))
def remove_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """ provider = get_provider_or_404(provider_id) ctx = dict(provider=provider.name, user=current_user) deleted = _datastore.delete_connections(user_id=current_user.get_id(), provider_id=provider_id) if deleted: after_this_request(_commit) msg = ('All connections to %s removed' % provider.name, 'info') connection_removed.send(current_app._get_current_object(), user=current_user._get_current_object(), provider_id=provider_id) else: msg = ('Unable to remove connection to %(provider)s' % ctx, 'error') do_flash(*msg) return redirect(request.referrer)
def application_create(): auth_info = AuthInfoManager.get_or_create(current_user) form = HrApplicationForm() characters = EveCharacter.query.filter_by(user_id=current_user.get_id()).all() character_choices = [] for character in characters: character_choices = character_choices + [(character.character_id, character.character_name)] form.characters.choices = character_choices if request.method == 'POST': if form.validate_on_submit(): application = HrManager.create_application(form, main_character_name=current_user.auth_info[0].main_character.character_name, user=current_user) flash("Application Created, apply in game with \"" + url_for('recruit.application_view', _external=True, application_id=application.id) + "\" in the body", category='message') return redirect(url_for('recruit.application_view', application_id=application.id)) return render_template('recruit/application_create.html', form=form)
def jwt_create_token(user_id=None, additional_data=None): """Encode the JWT token. :param int user_id: Addition of user_id. :param dict additional_data: Additional information for the token. :returns: The encoded token. :rtype: str .. note:: Definition of the JWT claims: * exp: ((Expiration Time) expiration time of the JWT. * sub: (subject) the principal that is the subject of the JWT. * jti: (JWT ID) UID for the JWT. """ # Create an ID uid = str(uuid.uuid4()) # The time in UTC now now = datetime.utcnow() # Build the token data token_data = { 'exp': now + current_app.config['ACCOUNTS_JWT_EXPIRATION_DELTA'], 'sub': user_id or current_user.get_id(), 'jti': uid, } # Add any additional data to the token if additional_data is not None: token_data.update(additional_data) # Encode the token and send it back encoded_token = encode( token_data, current_app.config['ACCOUNTS_JWT_SECRET_KEY'], current_app.config['ACCOUNTS_JWT_ALOGORITHM'] ).decode('utf-8') return encoded_token
def get_current_user_first_name(): cur_id = current_user.get_id() cur_user = db.session.query(User).filter(User.id == cur_id).first() if cur_user is not None: return cur_user.first_name return "User"
def eve_characters(): characters = EveCharacter.query.filter_by(user_id=current_user.get_id()).all() return render_template('users/eve_characters.html', characters=characters)