def send_mail(from_id, to_id, title, body): sender_info = user.get_user(from_id) receiver_info = user.get_user(to_id) if not sender_info[0]: return (False, _('INVALID_SENDER')) if not receiver_info[0]: return (False, _('INVALID_RECEIVER')) if title.strip() == '': return (False, _('EMPTY_TITLE')) if body.strip() == '': return (False, _('EMPTY_BODY')) t = db.transaction() try: db.insert('Mails', mSenderSerial = from_id, mReceiverSerial = to_id, mSenderId = sender_info[1].uId, mSenderNick = sender_info[1].uNick, mDatetime = web.SQLLiteral('NOW()'), mTitle = title, mContent = body) except: t.rollback() return (False, _('DATABASE_ERROR')) else: t.commit() return (True, _('SUCCESS'))
def team_accept_invite_request(): params = utils.flat_multi(request.form) _user = user.get_user().first() if not user.in_team(_user): raise WebException("You must be in a team!") _team = get_team(tid=_user.tid).first() tid = _team.tid if _user.uid != _team.owner: raise WebException("You must be the captain of your team to rescind invitations!") if _team.finalized: raise WebException("This team is finalized.") if len(_team.get_members()) >= utils.get_config("team_size"): raise WebException("Your team is full.") uid = params.get("uid") _user2 = user.get_user(uid=uid).first() if user.in_team(_user2): raise WebException("This user is already in a team!") invitation = TeamInvitations.query.filter_by(rtype=1, frid=_user2.uid, toid=tid).first() if invitation is None: raise WebException("Invitation doesn't exist.") with app.app_context(): _user2 = Users.query.filter_by(uid=_user2.uid).first() _user2.tid = tid db.session.delete(invitation) invitation2 = TeamInvitations.query.filter_by(rtype=0, frid=tid, toid=_user2.uid).first() if invitation2 is not None: db.session.delete(invitation2) db.session.commit() db.session.close() return { "success": 1, "message": "Success!" }
def modify_post(self, current_uid = -1): user_id = current_uid usr = user.get_user(user_id)[1] data = web.input(profile_image = {}) if data.newpass1 and not user.verify_password(user_id, data.oldpass): return util.render().error(error_message=_('INVALID_PASSWORD'), help_context='error') if data.newpass1 != data.newpass2: return util.render().error(error_message = _('PASSWORD_DO_NOT_MATCH'), help_context='error') if len(data.newpass1) > 0 and len(data.newpass1) < 6: return util.render().error(error_message = _('PASSWORD_TOO_SHORT'), help_context='error') if len(data.newpass1) == 0: password = data.oldpass else: password = data.newpass1 nick = data.nick email = data.email homepage = data.homepage sig = data.sig introduction = data.introduction language = data.language theme = data.theme user_info = user.get_user(user_id) change_lang = False if language != user_info[1].language: change_lang = True profile_image = data.profile_image.value delete_profile_image = data.has_key('delete_profile_image') ret = user.modify_user(user_id, locals()) if change_lang: web.ctx.session.lang = language raise web.seeother(util.link('/+u'))
def query_show(query_id): query = g.conn.session.query(Query).filter(Query.id == query_id).one() can_edit = get_user() is not None and get_user().id == query.user_id is_starred = False if get_user(): is_starred = g.conn.session.query(func.count(Star.id))\ .filter(Star.user_id == get_user().id)\ .filter(Star.query_id == query_id).scalar() == 1 jsvars = { 'query_id': query.id, 'can_edit': can_edit, 'is_starred': is_starred, 'published': query.published } if query.latest_rev and query.latest_rev.latest_run_id: jsvars['qrun_id'] = query.latest_rev.latest_run_id return render_template( "query/view.html", user=get_user(), query=query, jsvars=jsvars, latest_rev=query.latest_rev )
def team_invite(): params = utils.flat_multi(request.form) _user = user.get_user().first() _team = get_team(tid=_user.tid).first() if _user.uid != _team.owner: raise WebException("You must be the captain of your team to invite members!") if _team.finalized: raise WebException("This team is finalized.") new_member = params.get("new_member") if new_member is None: raise WebException("Please provide a username!") _user2 = user.get_user(username_lower=new_member.lower()).first() if _user2 is None: raise WebException("User doesn't exist!") if _user2.tid > 0: raise WebException("This user is already a part of a team!") if _team.get_pending_invitations(toid=_user2.uid) is not None: raise WebException("You've already invited this member!") req = TeamInvitations(0, _team.tid, _user2.uid) with app.app_context(): db.session.add(req) db.session.commit() db.session.close() return { "success": 1, "message": "Success!" }
def new_query(): if get_user() is None: return redirect("/login?next=/query/new") query = Query() query.user = get_user() g.conn.session.add(query) g.conn.session.commit() return redirect(url_for('query_show', query_id=query.id))
def modify_get(self, current_uid = -1): user_id = current_uid usr = user.get_user(user_id)[1] referer = util.link('/+u') return util.render().myinfo_edit(user = user.get_user(user_id)[1], user_id = user_id, title = _('Edit My Information'), board_desc = _('Edit My Information'), referer = web.ctx.env.get('HTTP_REFERER', referer), help_context = 'myinfo')
def star_query(): if get_user() is None: return "Unauthorized access", 403 query = g.conn.session.query(Query).get(request.form['query_id']) if query: star = Star() star.user = get_user() star.query = query g.conn.session.add(star) g.conn.session.commit() return "" else: return "Query not found", 404
def unstar_query(): if get_user() is None: return "Unauthorized access", 403 query = g.conn.session.query(Query).get(request.form['query_id']) if query: star = g.conn.session.query(Star)\ .filter(Star.query_id == request.form['query_id'])\ .filter(Star.user_id == get_user().id)\ .one() g.conn.session.delete(star) g.conn.session.commit() return "" else: return "Query not found", 404
def ideas(request): # Optional parameters: sort="user" | "rating" | "date" user = get_user(request) session = DBSession() project = request.context # Create list of ideas with User's rating added: if user: idea_query = session.query(Idea, AggregateRating, UserRating)\ .outerjoin(AggregateRating, (AggregateRating.idea_id==Idea.id))\ .outerjoin(UserRating, (Idea.id==UserRating.idea_id) & (UserRating.user_id==user.id))\ .join(User, (Idea.author_id==User.id))\ .filter(Idea.project_id == project.id) else: # Just fill third column with Nones. idea_query = session.query(Idea, AggregateRating, UserRating)\ .outerjoin(AggregateRating, (AggregateRating.idea_id==Idea.id))\ .outerjoin(UserRating, (UserRating.idea_id==0))\ .join(User, (Idea.author_id==User.id))\ .filter(Idea.project_id == project.id) sort = request.params.get('sort', 'rating') if sort == 'user': # Use Python to sort, so we sort Anonymous posts properly. pass elif sort == 'rating': # Use Python to sort, so we can use our total_rating algorithm.. pass elif sort == 'date': idea_query = idea_query.order_by(Idea.creation_time.desc()) # Most recent first else: logging.warn('Unrecognized sort: ' + str(sort)) idea_data = idea_query.all() # Do python sorting. if sort == 'user': idea_data.sort(key=lambda el:el[0].author.first_name + ' ' + el[0].author.last_name if not el[0].anonymous else 'Anonymous') elif sort == 'rating': if project.rating_type == 'like/love': idea_data.sort(key=lambda el: el[0].aggregate_rating.total_rating if el[0].aggregate_rating else 0, reverse=True) else: idea_data.sort(key=lambda el: el[0].aggregate_rating.average_stars if el[0].aggregate_rating else 0, reverse=True) # Turn it all into dicts for our templating engine. for i in range(len(idea_data)): idea, aggregate_rating, rating = idea_data[i] idea_data[i] = idea_dict(request, idea, rating, aggregate_rating, include_comments=True) # Idea.user_rating will be used to determine the initial state of the Like/Love/Stars return template_permissions(request, { 'project' : project, 'creator' : user_dict(request, project.creator), 'project_id' : project.id, 'idea_data': idea_data, 'user' : user_dict(request, user), 'ideas_count': len(idea_data), 'people_count': 1, 'sort' : sort })
def update_association(user_id, client_id, refresh_token_str): client = get_client(client_id) user = get_user(user_id) logging.warn('update_associations 1: ' + str(refresh_token_str)) refresh_token = get_token(client_id, client.secret, refresh_token_str) #always check to see if it is confidential or not. #it shouldn't be if it's using update_association, but you never know #and it's good to have a log message to possible alert the admin that #this is going on. if client.type.lower() != 'confidential': raise ConfidentailError('Client ' + client_id + \ ' is not a confidentail client') db = DB() try: key = 'client_association_' + str(user.id) if db.contains(key): association = db.get(key) if client.id in association.clients: logging.warn('update_associations 2: ' + str(association.clients[client.id])) old_refresh = get_token(client.id, client.secret, association.clients[client.id]) delete_token(old_refresh.access_token) delete_token(old_refresh.code) association.clients[client.id] = refresh_token.code logging.warn('update_associations 3: ' + str(refresh_token.code) + ', ' + str(association.clients[client.id])) db.update(key, association) db.commit() #except Exception, e: # logging.error('update_associations: ' + str(e)) # db.abort() finally: db.close() return False
def create(request): user = get_user(request) if 'project_key' in request.params: # User submitted a project. # TODO: Validation. try: new_project = request.context.newProject( title=request.params['project_title'], key=request.params['project_key'], description=request.params['project_description'], url_name=request.params['project_url'], creator_id=user.id) participation = Participation(user=user, project=new_project) session = DBSession() session.add(participation) session.flush() note.new_project(request, new_project, user) except IntegrityError: # url_name collision. raise HTTPBadRequest(explanation="Sorry! That URL has already been taken!") return HTTPFound(location=request.root.project_url(new_project)+'/invite') else: return {'user' : user_dict(request, user)}
def show_userpage(request): session = DBSession() other_user = request.context current_user = get_user(request) shared_projects = [] for project in current_user.projects: if project in other_user.projects: shared_projects += [project] project_data = [] for project in shared_projects: data = {} data['title'] = project.title # How many ideas and comments other_user has posted to this project. data['idea_count'] = project.ideas.filter(Idea.author==other_user).count() data['comment_count'] = project.comments.filter(Comment.author==other_user).count() data['url'] = request.root.project_url(project) project_data += [data] return { 'first_name' : other_user.first_name, 'last_name' : other_user.last_name, 'profile_picture' : other_user.profile_picture, 'user' : current_user, 'shared_project_count' : len(project_data), 'projects' : project_data }
def create_access_token_from_user_pass(client_id, client_secret, user_id, password, scope): client = None if client_id != None: client = get_client(client_id) else: # create a client object from username and password client = Client(user_id, user_id, password, None) # make client_secret equal the password # saving me from having to change anything below client_secret = password user = get_user(user_id) db = DB() try: if client != None and user != None and client.secret == client_secret and user.password == password: token = AccessToken(client.id, user.id, scope=scope) while db.contains(token.code): token = AccessToken(client.id, user.id, scope=scope) db.put(token.code, token) db.commit() return token.code except Exception, e: logging.error("".join(["create_access_token_from_user_pass: ", str(e)])) db.abort()
def api_run_query(): if get_user() is None: return "Authentication required", 401 text = request.form['text'] query = g.conn.session.query(Query).filter(Query.id == request.form['query_id']).one() if query.latest_rev and query.latest_rev.latest_run: result = worker.run_query.AsyncResult(query.latest_rev.latest_run.task_id) if not result.ready(): result.revoke(terminate=True) query.latest_rev.latest_run.status = QueryRun.STATUS_SUPERSEDED g.conn.session.add(query.latest_rev.latest_run) g.conn.session.commit() query_rev = QueryRevision(query_id=query.id, text=text) query.latest_rev = query_rev # XXX (phuedx, 2014/08/08): This deviates from the pre-existing # QueryRevision interface, but I'm not confident that SQLAlchemy would # invalidate a cached result for a relationship if a property changed. query_run = QueryRun() query_run.rev = query_rev query_run.status = QueryRun.STATUS_QUEUED g.conn.session.add(query_run) g.conn.session.add(query) g.conn.session.commit() query_rev.latest_run = query_run query_run.task_id = worker.run_query.delay(query_run.id).task_id g.conn.session.add(query_rev) g.conn.session.add(query_run) g.conn.session.commit() return json.dumps({ 'qrun_id': query_run.id })
def display_project_people(request): cur_user = get_user(request) session = DBSession() project = request.context participants = session.query(Participation, User).outerjoin(User).filter(Participation.project == project).all() people_data = [] email_data = [] for participant, user in participants: person_data = {} if user: person_data['first_name'] = user.first_name person_data['last_name'] = user.last_name person_data['profile_url'] = request.root.user_url(user) person_data['invite_accepted'] = participant.access_time is not None person_data['profile_picture'] = user.profile_picture people_data += [person_data] else: email_data += [participant.user_email] # Sort by first last name people_data.sort(key=lambda user: user['first_name'] + u' ' + user['last_name']) return template_permissions(request, { 'people' : people_data, 'invited_emails' : email_data, 'project_id' : project.id, 'project' : project, 'creator' : user_dict(request, project.creator), 'user' : user_dict(request, cur_user), 'ideas_count': project.ideas.count(), 'people_count': len(active_users(project)), })
def user_mgr(): if session.get("user") == "admin": users = user.get_user() # print users return render_template("/user_mgr.html", users=users) else: return redirect("/index")
def present_main(): # check for a cookie, if present, then extract value username = login_check() if (username == None): print "main: can't identify user...redirecting to signup" bottle.redirect("/login") connection = pymongo.Connection(connection_string, safe=True) me = user.get_user(connection, username) friends = me['friends'] friends_requests = me['friends_requests'] challenges_ids = me['challenges'] challenges = [] for challenge_id in challenges_ids: challenges.append(achievement.find_achievement_by_id(connection, challenge_id)) achievements_ids = me['achievements'] achievements = [] for achievement_id in achievements_ids: challenges.append(achievement.find_achievement_by_id(connection, achievement_id)) return bottle.template("main", {'username':username, 'friends':friends, 'friends_requests':friends_requests, 'challenges':challenges, 'achievements':achievements, })
def team_accept_invite(): params = utils.flat_multi(request.form) _user = user.get_user().first() if user.in_team(_user): raise WebException("You're already in a team!") tid = params.get("tid") _team = get_team(tid=tid).first() if _team is None: raise WebException("Team not found.") if len(_team.get_members()) >= utils.get_config("team_size"): raise WebException("This team is full.") invitation = TeamInvitations.query.filter_by(rtype=0, frid=tid, toid=_user.uid).first() if invitation is None: raise WebException("Invitation doesn't exist.") with app.app_context(): _user = Users.query.filter_by(uid=_user.uid).first() _user.tid = tid db.session.delete(invitation) invitation2 = TeamInvitations.query.filter_by(rtype=1, frid=_user.uid, toid=tid).first() if invitation2 is not None: db.session.delete(invitation2) db.session.add(Activity(_user.uid, 6, _team.tid, -1)) db.session.commit() db.session.close() return { "success": 1, "message": "Success!" }
def create_implicit_grant_access_token(uid, client_id, redirect_uri, scope=None): user = get_user(uid) client = get_client(client_id) db = DB() try: # the only authentication here is to check the # redirect_uri is the same as the one stored # for the registered client if client.redirect_uri == redirect_uri: token = AccessToken(client.id, user.id, scope=scope) while db.contains(token.code): token = AccessToken(client.id, user.id, scope=scope) db.put(token.code, token) db.commit() return token.code else: logging.warn( "".join([str(client_id), " uri of ", str(client.redirect_uri), " does not match ", str(redirect_uri)]) ) except Exception, e: logging.error("".join(["create_implicit_grant_access_token: ", str(e)])) db.abort()
def project(request): user = get_user(request) session = DBSession() project = request.context updates = session.query(ProjectUpdate)\ .filter(ProjectUpdate.project_id==project.id)\ .filter(ProjectUpdate.when >= utcnow() - timedelta(days=10))\ .order_by(ProjectUpdate.when.desc()).limit(10).all() # Update user access time: if user: part = session.query(Participation).filter(Participation.user_email==user.email).filter(Participation.project_id==project.id).first() if not part or not part.access_time: note.new_participant(request, request.context, user) part.access_time = utcnow() session.flush() return template_permissions(request, { 'project_id' : project.id, 'project' : project, 'creator' : user_dict(request, project.creator), 'updates' : updates, 'ideas': project.ideas.all(), 'user' : user_dict(request, user), 'can_update' : user == project.creator, 'ideas_count': project.ideas.count(), 'people_count': 1 })
def get_user(self, nick): """Returns a user object for the specified nick. @returns user.User() """ return user.get_user(nick)
def render(): try: if web.config.theme == 'default': return config.render[user.get_user(web.ctx.session.uid)[1].theme] else: return config.render[web.config.theme] except: return config.render[web.config.theme]
def activity_user(): params = utils.flat_multi(request.args) if "user" not in params: raise WebException("Please specify a user.") _user = get_user(username_lower=params.get("user").lower()).first() if _user is None: raise WebException("User not found.") return _user.get_activity()
def leave_get(self, current_uid = -1): user_id = current_uid usr = user.get_user(user_id)[1] default_referer = posixpath.join('/', '+u') return util.render().leave(board_desc = _('Leave NOAH'), title=_('Leave NOAH'), referer = web.ctx.env.get('HTTP_REFERER', default_referer),)
def GET(self, username, current_uid = -1): user_id = user._get_uid_from_username(username) if user_id < 0: raise web.notfound(util.render().error(error_message = _('NO_SUCH_USER'), help_context='error')) return util.render().myinfo(user = user.get_user(user_id)[1], user_id = user_id, title = _('User Information'), board_desc = _('User Information'), help_context='myinfo')
def GET(self, current_uid = -1): user_id = web.ctx.session.uid f = [{'type':'rss', 'path':'/+u/+favorite_rss', 'name':u'즐겨찾기 피드 (RSS)'}, {'type':'atom', 'path':'/+u/+favorite_atom', 'name':u'즐겨찾기 피드 (Atom)'},] return util.render().myinfo(user = user.get_user(user_id)[1], user_id = user_id, title = _('My Information'), board_desc = _('My Information'), feeds = f, help_context='myinfo')
def fork_query(id): if get_user() is None: return redirect("/login?next=fork/{id}".format(id=id)) query = Query() query.user = get_user() parent_query = g.conn.session.query(Query).filter(Query.id == id).one() query.title = parent_query.title query.parent_id = parent_query.id query.description = parent_query.description g.conn.session.add(query) g.conn.session.commit() query_rev = QueryRevision(query_id=query.id, text=parent_query.latest_rev.text) query.latest_rev = query_rev g.conn.session.add(query) g.conn.session.add(query_rev) g.conn.session.commit() return redirect(url_for('query_show', query_id=query.id))
def process_cookie(cookie): # See if they are logged in. If so display their name current_user = None if cookie is not None: login_id = cookies.get_id(cookie) if login_id == "admin": current_user = special_admin elif login_id is not None: current_user = user.get_user(login_id) return current_user
def session_set(self, username): u = user.get_user(user._get_uid_from_username(username)) if u[0]: web.ctx.session.uid = u[1].uSerial web.ctx.session.username = u[1].uId web.ctx.session.usernick = u[1].uNick web.ctx.session.lang = u[1].language return u[1] else: return None
def create_story(username, title, content): uid = user.get_user(username=username)[0] db = sqlite3.connect(DATABASE) c = db.cursor() query = "INSERT INTO stories VALUES (NULL, ?)" c.execute(query, (title,)) # Fetch primary key of newly inserted row storyid = c.lastrowid now = int(datetime.datetime.now().strftime("%s")) query = "INSERT INTO updates VALUES (NULL, ?, ?, ?, ?)" c.execute(query, (storyid, uid, now, content,)) db.commit() db.close()
def useredit_index(): params = request.args if request.method == 'GET' else request.form username = params.get('username', '') if username: user_info = user.get_user(username) if user_info: username = user_info.get('username') password = user_info.get('password') age = user_info.get('age') return render_template('useredit.html', username=username, password=password, age=age) else: return render_template('useredit.html', useredit_info='username error') else: return render_template('useredit.html')
def login(): if request.method == "POST": # User has submitted a request to login required_keys = ["username", "pass"] if not validate_form(request.form, required_keys): return render_template("login.html", message="Malformed request.", category="danger") username = request.form["username"] password = hashlib.sha1(request.form["pass"]).hexdigest() result = user.get_user(username=username) if result: if result[2] == password: session["username"] = username return redirect(url_for("index")) return render_template("login.html", message="Invalid password", category="danger") return render_template("login.html", message="Username does not exist...", add_mess="Register a new account?", category="danger") return render_template("login.html")
def update_story(username, story_id, content): uid = user.get_user(username=username)[0] db = sqlite3.connect(DATABASE) c = db.cursor() for story in user.get_stories(uid): if story_id in story: return False, "You already contributed to this story." query = "INSERT INTO updates VALUES (NULL, ?, ?, ?, ?)" now = int(datetime.datetime.now().strftime("%s")) c.execute(query, (story_id, uid, now, content,)) db.commit() db.close() return True, "Story updated."
def editprofile(): if "username" not in session: return redirect(url_for("login")) if request.method == "POST": # User has submitted a request to edit their profile username = session["username"] required_keys = ["name", "aboutme"] if not validate_form(request.form, required_keys): return render_template("editprofile.html", message="Malformed request.", category="danger") user.update_profile(username, request.form['name'], request.form['aboutme']) return redirect(url_for('profile')) uid = user.get_user(username=session["username"])[0] info = user.get_info(uid) return render_template("editprofile.html", info=info)
def modify_user(): username = request.args.get('username', '') _user = user.get_user(username) _error = '' _username = '' _password = '' _age = '' if _user is None: _error = '用户信息不存在' else: _username = _user.get('username') _password = _user.get('password') _age = _user.get('age') return render_template('user_modify.html', error=_error, username=_username, password=_password, age=_age)
def login_page(): form = LoginForm() if form.validate_on_submit(): username = form.data["username"] user = get_user(username) if user is not None: password = form.data["password"] if hasher.verify(password, user.password): login_user(user) flash("Login Succesfull :)") next_page = request.args.get("next", url_for("home_page")) return redirect(next_page) flash("Invalid credentials.") x = datetime.now() date = x.strftime("%x") day_name = x.strftime("%A") time = x.strftime("%X") return render_template("login.html", form=form, date = date, day_name = day_name, time = time)
def query_runs_all(): queries = g.conn.session.query(Query)\ .join(Query.latest_rev).join(QueryRevision.latest_run) queries_filter = 'all' if request.args.get('published') == 'true': queries = queries.filter(Query.published) queries_filter = 'published' limit = int( request.args.get('limit', app.config.get('QUERY_RESULTS_PER_PAGE', 50))) queries, prev_link, next_link = QueriesRangeBasedPagination( queries, request.args.get('from'), limit, request.path, request.referrer, dict(request.args)).paginate() return render_template("query/list.html", user=get_user(), queries=queries, prev_link=prev_link, next_link=next_link, queries_filter=queries_filter)
def register(): if request.method == "POST": # User has submitted a request to register an account required_keys = ["username", "pass", "passconfirm", "bday"] if not validate_form(request.form, required_keys): return render_template("register.html", message="Malformed request.", category="danger") username = request.form["username"] password = request.form["pass"] password_confirm = request.form["passconfirm"] bday = request.form["bday"] if not username.isalnum(): return render_template("register.html", message="Usernames must contain only alphanumeric characters.", category="danger") if password != password_confirm: return render_template("register.html", message="Passwords do not match.", category="danger") if len(password) < 6: return render_template("register.html", message="Password must be at least 6 characters in length.", category="danger") if password == password.lower(): return render_template("register.html", message="Password must contain at least one capitalized letter.", category="danger") now = datetime.datetime.now() try: # dob should be in the format "yyyy-mm-dd" dob = map(int, bday.split("-")) assert len(dob) == 3 dob = datetime.datetime(dob[0], dob[1], dob[2]) except: return render_template("register.html", message="Invalid birthday.", category="danger") if int((now - dob).days / 365.25) < 13: return render_template("register.html", message="Users must be 13 years or older to register for an account.", category="danger") if user.get_user(username=username): return render_template("register.html", message="Username is already in use.", category="danger") user.add_user(username, password, bday) return render_template("register.html", message="Account created!", category="success") return render_template("register.html")
async def embed_single_pull(ctx): u = user.get_user(ctx.author.id) if u.primogems < 160: await error.embed_not_enough_primo(ctx) return if u.five_pity >= 89: (p, t), five, four = pull(False, True, u) elif u.four_pity >= 9: (p, t), five, four = pull(True, False, u) else: (p, t), five, four = pull(False, False, u) text = "" if five: color = discord.Color.gold() text = prefix.fiveStarPrefix + p.name u.five_pity = 0 u.four_pity = 0 elif four: color = discord.Color.purple() text = prefix.fourStarPrefix + p.name u.five_pity += 1 u.four_pity = 0 else: color = discord.Color.blue() text = prefix.threeStarPrefix + p.name u.five_pity += 1 u.four_pity += 1 if t == "c": file = discord.File(p.URL_portrait, f"{p.URL_name}-portrait.png") embed = discord.Embed(title=text, color=color) embed.set_image(url=f"attachment://{p.URL_name}-portrait.png") else: file = discord.File(p.URL_icon, f"{p.URL_name}-icon.png") embed = discord.Embed(title=text, color=color) embed.set_image(url=f"attachment://{p.URL_name}-icon.png") u.primogems -= 160 u.update_equiped_weapons() await commission.check_wish_complete(ctx, u, 1) database_mongo.save_user(u) asyncio.get_event_loop().create_task(display_pull(ctx, embed, file, p.rarity, True))
def register_page(): form = RegistrationForm() if form.validate_on_submit(): password = form.password.data hashed_pw = bcrypt.generate_password_hash(password).decode('utf-8') username = form.username.data email = form.email.data temp = get_user(username) db = current_app.config["db"] email_check = db.is_email_taken(email) if temp is not None or email_check is not None: return ("Please check your username and password!") else: phone = "" #phone is initially empty profile_pic = "default.jpg" user = User(username,hashed_pw,email,phone,profile_pic) #user = User(username,password,email,phone,profile_pic) db.add_user(user) return redirect(url_for('login_page')) return render_template('register.html', form=form)
def login_page(): s_id = None if request.method == "GET": values = {"email": "", "password": ""} return render_template("login.html", values=values) else: email = request.form["email"] password = request.form["password"] user = get_user(email) if user is not None: if hasher.verify(password, user.password): login_user(user) return redirect(url_for("home_page")) else: flash("Incorrect password") else: flash("Incorrect email.") values = {"email": "", "password": ""} return render_template("login.html", values=values)
def create_webpage_lookup(user_id, webpage, lookup_id, filename, keywords, datetime, articles): # get a user object or create one check_user = user.get_user(user_id) if not check_user: check_user = user.create_user(user_id) # create a webpage object webpage_id = web_page.put(webpage, filename) webpage_lookup = { "user": check_user, "webpage": webpage_id, "keywords": keywords, "datetime": datetime, "lookup_id": lookup_id, "articles": articles } return db.webpage_lookup.insert_one(webpage_lookup)
def login_page(): form = LoginForm() if form.validate_on_submit(): username = form.username.data temp = get_user(username) if temp is not None: #realpassword = temp.password user = User(username, temp.password,temp.email,temp.phone,temp.profile_pic) password = form.password.data if bcrypt.check_password_hash(temp.password,password): login_user(user) #flash("You have logged in.") next_page = request.args.get("next", url_for("home_page")) return redirect(next_page) else: return ("Wrong Password") else: return ("User can not be found") return render_template("login.html", form=form)
def login(self): # Get inputs from entry boxes username = self.username_box.text() password = self.password_box.text() # Clear any existing errors self.error_label.clear() if username_available(username): self.error_label.setText("No account with that username") return else: user = get_user(username) if user.password == password: self.parent.sign_in(user) else: self.error_label.setText("Incorrect password") return self.reset() self.parent.stack.setCurrentIndex(0)
def login_page(): print("login page") form = forms.LoginForm() if form.validate_on_submit(): username = request.form["username"] user = usr.get_user(username) if user is not None: password = request.form["password"] if hasher.verify(password, user.password): login_user(user) today = datetime.today() db = current_app.config["db"] count = db.get_meal_count(today.date()) scrape = False if ((today.hour > 14) and (count < 2)): scrape = True if ((today.hour >= 0) and (count < 1)): scrape = True if scrape: current_m = current_meal.Current_Meal() current_m.Itu_meal() current_app.config["current_m"] = current_m else: current_m = current_meal.Current_Meal() current_m.id = db.find_meal_with_date(today.date()) current_m.meal(current_m.id) current_m.get_food_calories() current_app.config["current_m"] = current_m current_m = current_app.config["current_m"] comments, chief_comments = usr.get_comments(current_m.id) next_page = request.args.get( "next", url_for("home_page", current_m=current_m, comments=comments, is_chief=current_user.is_admin, chief_comments=chief_comments)) return redirect(next_page) flash("Wrong username or password") return render_template("login2.html", form=form)
def login(): """ login page and login post function """ if current_user.is_anonymous: pass else: if current_user.is_admin: return redirect(url_for("admin_page")) form = LoginForm() if form.validate_on_submit(): student_id = form.data["username"] user = get_user(user_id=student_id) if user is not None: password = form.data["password"] if hasher.verify(password, user.password): login_user(user) flash("You have logged in.") next_page = request.args.get("next", url_for("home_page")) return redirect(next_page) flash("Invalid credentials.") return render_template("login.html", form=form)
def register(): form = RegisterForm() if form.validate_on_submit(): user = get_user(form.username.data) if user is None: if current_app.config['db'].get_user_by_email(form.email.data): form.email.errors.append("This email is already registered.") else: user = User( None, form.username.data, form.email.data, sha256(form.password.data.encode('utf-8')).hexdigest(), form.public.data, _datetime.date.today()) current_app.logger.debug(user.register_date) user = current_app.config['db'].register_user(user) login_user(user) next_page = request.args.get("next", url_for("index")) return redirect(next_page) else: form.username.errors.append("This nickname is already registered.") return render_template('register.html', form=form) form.public.data = True return render_template('register.html', form=form)
def team_create(): params = utils.flat_multi(request.form) _user = user.get_user().first() if (_user.tid is not None and _user.tid >= 0) or get_team( owner=_user.uid).first() is not None: raise WebException("You're already in a team!") verify_to_schema(TeamSchema, params) teamname = params.get("teamname") school = params.get("school") team = Teams(teamname, school, _user.uid, _user.utype != 1) with app.app_context(): db.session.add(team) db.session.commit() Users.query.filter_by(uid=_user.uid).update({"tid": team.tid}) team_activity = UserActivity(_user.uid, 1, tid=team.tid) db.session.add(team_activity) db.session.commit() session["tid"] = team.tid return {"success": 1, "message": "Success!"}
def change_password(): if not current_user.is_authenticated: return redirect("/") new1 = request.form['new1'] new2 = request.form['new2'] if new1 != new2: message = "New passwords don't match. Try again." return render_template("password.html", message=message) old = request.form['old'] user = get_user(current_user.username) if pbkdf2_sha256.verify(old, user.password): new = pbkdf2_sha256.hash(new1) query = """UPDATE Users SET password = '******' WHERE username = '******'""" % ( new, current_user.username) with psycopg2.connect(url) as connection: with connection.cursor() as cursor: cursor.execute(query) connection.commit() logout_user() return redirect("/signin") else: message = "The old password you entered is incorrect. Try again." return render_template("password.html", message=message)
def team_invite_request(): params = utils.flat_multi(request.form) _user = user.get_user().first() if user.in_team(_user): raise WebException("You're already in a team!") tid = params.get("tid") _team = get_team(tid=tid).first() if _team is None: raise WebException("Team not found.") if _team.finalized: raise WebException("This team is finalized.") if _team.get_invitation_requests(frid=_user.uid) is not None: raise WebException("You've already requested to join this team!") req = TeamInvitations(1, _user.uid, _team.tid) with app.app_context(): db.session.add(req) db.session.commit() db.session.close() return {"success": 1, "message": "Success!"}
def filter_stories(stories): """ Convert a list of stories to more usable format. Assumes all columns are present, and in order """ filtered = [] for story in stories: story_id = story[0] title = story[1] updates = [] for update in get_updates(story_id): author = user.get_user(id=update[2])[1] updates.append({ "author": author, "timestamp": datetime.datetime.fromtimestamp(update[3]).strftime("%B %d, %Y %I:%M %p"), "content": update[4] }) filtered.append({ "story_id": story_id, "title": title, "updates": updates }) return filtered
def login(): if request.method == 'GET': return render_template('login.html', target = '/login', way = '登陆') if request.method == 'POST': user_name = request.form.get('username') password = request.form.get('password') user_info = get_user(user_name) emsg = None if user_info is None: emsg = '该用户名不存在' else: user = User(user_info) if user.verify_password(password): # 校验密码 login_user(user) # 创建用户 Session else: emsg = "密码有误" if emsg is None: return redirect(request.args.get('next') or '/yukiyu/main') else: flash(emsg) return redirect('/login')
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] error = None user = get_user(username) if user is not None: user_password = user[1] if not check_password_hash(user_password, password): error = 'Incorrect password, please try again.' else: error = 'User not found' if error is None: session.clear() session['authenticated'] = 'true' session['user_id'] = token_urlsafe() return redirect(url_for('ansible')) flash(error) return render_template('login.html')
def user_update(): # 获取用户更新信息,username作为唯一标识符,且不能更新 username = request.args.get('username', '') age = request.form.get('age', '') job = request.form.get('job', '') password = request.form.get('password', '') # 更新操作代码块 if request.method == 'GET': # 用户信息回显 user_dict = user.get_user(username) return render_template('user_upd.html', username=username, user_dict=user_dict) else: if not username or not password: return render_template('user_upd.html', error=u'(密码)不能为空,请重新输入') elif user.update_users(username=username, age=age, password=password, job=job): return redirect('/user/list/') else: return "用户更新失败!"
def team_edit(): params = utils.flat_multi(request.form) _user = user.get_user().first() _team = get_team(tid=_user.tid).first() if _user.uid != _team.owner: raise WebException( "You must be the captain of your team to edit information!") if _team.finalized: raise WebException("This team is finalized.") with app.app_context(): update = {} if params.get("new_teamname") is not None: if get_team(teamname_lower=params["new_teamname"].lower()).first( ) is not None: raise WebException("This team name is taken!") update["teamname"] = params["new_teamname"] update["teamname_lower"] = params["new_teamname"].lower() if params.get("new_school") is not None: update["school"] = params["new_school"] _team.update_info(update) return {"success": 1}
def new_password_page(): db = current_app.config["db"] error = None if request.method == "GET": values = {"old_password": "", "s_question": "", "new_password": ""} return render_template("new_password.html", values=values) else: old_password = request.form["old_password"] s_question = request.form["s_question"] new_password = request.form["new_password"] user = get_user(current_user.email) if hasher.verify(old_password, user.password): if current_user.is_student: if s_question == db.get_student(current_user.email)[-1]: db.change_password(current_user.email, hasher.hash(new_password), current_user.is_student) else: error = "Security question's answer is incorrect" else: if s_question == db.get_authorized(current_user.email)[-1]: db.change_password(current_user.email, hasher.hash(new_password), current_user.is_student) else: error = "Security question's answer is incorrect" else: error = "Old password is incorrect" if error is not None: flash(error) values = {"old_password": "", "s_question": "", "new_password": ""} return render_template("new_password.html", values=values) flash("Your password is changed") return redirect(url_for("profile_page"))
def profile_modify(): profile = user.get_user(session['id']) return render_template('profile_modify.html', profile=profile)
def load_user(user_id): return get_user(user_id)
def user(userID): userData = get_user(userID, domain=request.args.get('domain')) return render_template('json_viewer.html', data=userData)