def index(response): form_id = response.get_field('form_id', 'front') if form_id == 'front': response.write(LOGIN_HTML) elif form_id == 'login': user = response.get_field('user') try: user = User.get(user=user) set_user(response, user) response.redirect('/profile') except DoesNotExistError: response.redirect('/') elif form_id == 'signup': user = response.get_field('user') passwd1 = response.get_field('passwd1') #passwd2 = response.get_field('passwd2') first = response.get_field('first') last = response.get_field('last') dob = response.get_field('dob') logger.info('adding user {} ({} {}) with passwd {}'.format(user, first, last, passwd1)) if user and first and last and passwd1: try: user = User.add(user=user, passwd=passwd1, first=first, last=last, dob=dob) set_user(response, user) response.redirect('/profile') except IntegrityError: response.write(LOGIN_HTML) else: response.write(LOGIN_HTML)
def join(): if request.method == 'GET': return render_template('join.html') username = request.form.get('username') password = request.form.get('password') email = request.form.get('email') if not username: flash('Please input username') return redirect(url_for('join')) elif not password: flash('Please input password') return redirect(url_for('join')) elif not email: flash('Please input email') return redirect(url_for('join')) try: # use the .get() method to quickly see if a user with that name exists user = User.get(username=username) flash('That username is already taken') except User.DoesNotExist: # if not, create the user and store the form data on the new model user = User.create(username=username, password=md5(password).hexdigest(), email=email,join_date=datetime.datetime.now()) # mark the user as being 'authenticated' by setting the session vars auth_user(user) return redirect(url_for('homepage'))
def add_user(self, user: User): if user.hash is None: raise ValueError("User doesn't have a hash.") if user.hash == owner_hash: for perm in all_perms.keys(): user.add_permission(perm) self.session.add(user)
def r_success(): nickname = request.form["nickname"] email = request.form["email"] passwd = request.form["passwd"] repasswd = request.form["repasswd"] if passwd != repasswd: return "비밀번호가 다릅니다." if len(passwd) < 8: return """ <script> alert("비밀번호를 8자리 이상 적어주세요."); history.back(); </script> """ if not len(email) or not len(nickname): return """ <script> alert("모두 채워 주세요."); history.back(); </script> """ if is_already_registered(email, nickname) == 2: return "메일" if is_already_registered(email, nickname) == 3: return "별명" new = User() new.nickname = nickname new.email = email new.pw = passwd db.session.add(new) db.session.commit() return render_template("index.html")
def get(self, node): page = self.get_argument("page", 1) share_res = Share.find({'sharetype': node}).sort( '_id', DESCENDING).limit(10).skip((int(page) - 1) * 10) pagesum = (share_res.count() + 9) / 10 shares = [] for share in share_res: user = User.by_sid(share.user_id) share.name = user.user_name share.published = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(share.published)) share.domain = user.user_domain share.markdown = filter_tags( markdown2.markdown(share.markdown))[:100] share.gravatar = get_avatar(user.user_email, 16) shares.append(share) members = User.find().sort('_id', DESCENDING).limit(20) members_dict = [] for member in members: member.gravatar = get_avatar(member.user_email, 25) members_dict.append(member) node_about = options.node_about[node] self.render( "node.html", shares=shares, members=members_dict, pagesum=pagesum, page=page, node=node, node_about=node_about)
def create_user(self, name, team): newbie = User(name=name, team=team, loyalists=100, leader=True) self.sess.add(newbie) cap = Region.capital_for(team, self.sess) newbie.region = cap self.sess.commit() return newbie
def get(self, name): user = User.find_one({"user_domain": name}) user.user_say = markdown2.markdown(user.user_say) user.user_jointime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.user_jointime)) likenum = User.find({"user_id": user._id}).count() user.gravatar = get_avatar(user.user_email, 100) self.render("userhome.html", user=user, likenum=likenum)
def recruit_from_comment(self, comment): session = self.session if not comment.author: # Deleted comments don't have an author return name = comment.author.name.lower() if name == self.config.username.lower(): return # Is this author already one of us? found = session.query(User).filter_by( name=name).first() if not found: # Getting the author ID triggers a lookup on the userpage. In the # case of banned users, this will 404. @failable would normally # catch that just fine, but I want to check it here so that in the # future, I can do things like e.g. add to an 'ignored' list and # save myself the lookup try: author_id = comment.author.id except NotFound: logging.warn("Ignored banned user %s" % name) return team = 0 assignment = self.config['game']['assignment'] if assignment == 'uid': base10_id = base36decode(author_id) team = base10_id % 2 elif assignment == "random": team = random.randint(0, 1) is_leader = name in self.config["game"]["leaders"] newbie = User(name=name, team=team, loyalists=100, leader=is_leader) session.add(newbie) cap = Region.capital_for(newbie.team, session) if not cap: logging.fatal("Could not find capital for %d" % newbie.team) newbie.region = cap session.commit() logging.info("Created combatant %s", newbie) reply = ("Welcome to Chroma! You are now a %s " "in the %s army, commanding a force of loyalists " "%d people strong. You are currently encamped at %s" ) % (newbie.rank, num_to_team(newbie.team, self.config), newbie.loyalists, cap.markdown()) comment.reply(reply) else: #logging.info("Already registered %s", comment.author.name) pass
def before_request(): g.user = None try: if 'id' in session: g.user = User.get(User.id == session['id']) except User.DoesNotExist: g.user = None if "test" in request.headers: g.user = User.get(User.id == request.headers.get("test"))
def test_user_change_info(self): self.create_test_data() query = User().update(authentication_level=2, email='*****@*****.**', phone_number='1231231234', name='new_name', title='new_title').where(User.pk == self._user.pk) query.execute() pk = self._user.pk self._user_2 = User().get(pk=pk) self.assertEqual(self._user_2.authentication_level, 2) self.assertEqual(self._user_2.phone_number, '1231231234') self.assertEqual(self._user_2.name, 'new_name') self.assertEqual(self._user_2.title, 'new_title')
def post(self): oldpass = self.get_argument('oldpass', '') newpass = self.get_argument('newpass', '') newpass = hashlib.md5(newpass).hexdigest() user = User.by_sid(self.current_user['user_id']) if user.user_pass == hashlib.md5(oldpass).hexdigest(): user = User.by_sid(self.current_user['user_id']) user['user_pass'] = newpass user.save() self.redirect('/setting') else: self.redirect('/setting') # self.write('Wrong password')
def post(self): oldpass = self.get_argument("oldpass", "") newpass = self.get_argument("newpass", "") newpass = hashlib.md5(newpass).hexdigest() user = User.by_sid(self.current_user["user_id"]) if user.user_pass == hashlib.md5(oldpass).hexdigest(): user = User.by_sid(self.current_user["user_id"]) user["user_pass"] = newpass user.save() self.redirect("/setting") else: self.redirect("/setting") # self.write('Wrong password')
def create_test_data(self): self._company = Company().create(name='test_name', phone_number='1223456789', address='123 test road, testville test') self._user = User().create(name='test_name', email='*****@*****.**', title='the_boss', secret_question='what is the answer?', phone_number='1234567891', authentication_level=3, company=self._company.pk) self._user.set_password('test_password') self._user.set_secret_answer('42') self._admin = User().create(name='admin', email='*****@*****.**', title='the_boss', secret_question='what is the answer?', phone_number='1234567891', authentication_level=1, company=self._company.pk) self._admin.set_password('test_password') self._admin.set_secret_answer('42')
def get(self, name): user = User.find_one({'user_domain': name}) user.user_jointime = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(user.user_jointime)) likes = User.find({'user_id': user._id}) likenum = likes.count() for like in likes: share = Share.by_id(like.share_id) like.title = share.title like.id = share.id like.type = share.sharetype user.gravatar = get_avatar(user.user_email, 100) self.render("userlike.html", user=user, likenum=likenum, likes=likes)
def create(): new = User() new.userId = request.form['id'] new.userPw = request.form['pw'] new.nickname = request.form['nickname'] if new.userId and new.userPw and new.nickname : db.session.add(new) try: db.session.commit() except IntegrityError: return "이미 있습니다." return "%s (%s %s)" % (new.nickname, new.userId, new.userPw) else: return "내용을 전부 채워야합니다"
def on_post(self, req, resp): doc = req.context['doc'] users=Session.query(User).all() unique=True for user in users: if doc['email'] == user.email: unique=False if unique: user = User(name=doc['name'], email=doc['email'].lower(), signedin=False,registerTime=datetime.datetime.today()) print(datetime.datetime.today()) user.salt = bcrypt.gensalt() user.pw_hash = bcrypt.hashpw(doc['password'].encode('utf-8'), user.salt) s=smtplib.SMTP_SSL('smtp.gmail.com',465) s.ehlo() s.login('*****@*****.**','helloworld@ppclub') code=randint(1000000,10000000) user.code=code msg=MIMEText('Hi '+user.name+', your verification URL is: '+'http://192.168.1.127:8000/confirmation/'+str(code)) msg['From']='*****@*****.**' msg['To']=user.email msg['Subject']='PhoenixNow Account Confirmation' s.send_message(msg) s.close() Session.add(user) Session.flush() Session.commit() req.context['user'] = user.id req.context['result'] = {"result": "success", "action": "register"} else: user=get_user(req,resp) td=datetime.timedelta(minutes=30) if datetime.datetime.today()-td<user.registerTime or user.emailVerified==True: description = "User was already made" title = "User creation conflict" raise falcon.HTTPConflict(title=title, description=description) else: Session.delete(user) Session.flush() user = User(name=doc['name'], email=doc['email'], signedin=False,registerTime=datetime.datetime.today()) print(datetime.datetime.today()) user.salt = bcrypt.gensalt() user.pw_hash = bcrypt.hashpw(doc['password'].encode('utf-8'), user.salt) s=smtplib.SMTP_SSL('smtp.gmail.com',465) s.ehlo() s.login('*****@*****.**','helloworld@ppclub') code=randint(1000000,10000000) user.code=code msg=MIMEText('Hi '+user.name+', your verification URL is: '+'http://192.168.1.127:8000/confirmation/'+str(code)) msg['From']='*****@*****.**' msg['To']=user.email msg['Subject']='PhoenixNow Account Confirmation' s.send_message(msg) s.close() Session.add(user) Session.flush() Session.commit() req.context['user'] = user.id req.context['result'] = {"result": "success", "action": "register"}
def _get_and_validate_user(self, username, password): user = User.get_by_user_id(username) if user == None or not user.validate_password(password): raise AuthenticationError( 'Username or password does not match.' ) return user
def post(self): id = self.get_argument("id", None) tags = self.get_argument("tags", '') user_id = self.current_user["user_id"] res = { 'title': self.get_argument("title"), 'markdown': self.get_argument("markdown"), 'sharetype': self.get_argument("type"), 'slug': self.get_argument("slug", ''), 'tags': tags, 'updated': time.time(), } if id: share = Share.by_sid(id) if not share: self.redirect("/404") share.update(res) share.save() else: share = Share res['user_id'] = user_id share = share.new(res) user = User.by_sid(user_id) user.user_leaf += 10 user.save() for i in tags.split(' '): Tag.new(i, share.id) self.redirect("/share/" + str(share.id))
def get_user_rating(): name = request.args.get('name') if name is None: abort(400) fmt = request.args.get('format', 'json') try: user = User.get(User.user == name) except User.DoesNotExist: abort(404) if fmt == 'xml': def quoteattr(s): return '"{0}"'.format(str(s) .replace('&', '&') .replace('<', '<') .replace('>', '>') .replace('"', '"')) xml = '<?xml version="1.0" encoding="UTF-8"?>\n<mmwatch>\n' for field in ( ('name', user.user.encode('utf-8')), ('rank', user.rank), ('edits', user.edits), ('joined', user.joined.isoformat()) ): xml = xml + ' <{0} value={1} />\n'.format(field[0], quoteattr(field[1])) xml = xml + '</mmwatch>' return Response(xml, mimetype='application/xml') return jsonify(name=user.user, rank=user.rank, edits=user.edits, joined=user.joined.isoformat())
def post(self): user = User.by_sid(self.current_user['user_id']) user['user_name'] = self.get_argument('name', None) user['user_city'] = self.get_argument('city', None) user['user_say'] = self.get_argument('say', None) user.save() self.redirect('/setting')
def validate(self): rv = Form.validate(self) if not rv: return False print self.admin user = User(self.admin.data) if user is None: self.admin.errors.append('Unknown admin') return False if not user.check_password(self.password.data): self.password.errors.append('Invalid password') return False return True
def get(self): email = self.get_argument('e', '') emailverify = self.get_argument('k', '') if User.by_email_verify(email, emailverify): self.render('setpass.html') else: self.render('forgotpass.html')
def bind(self, verifier): s = Session.get_by_key_name(self._jid) if s: token = oauth.OAuthToken.from_string(s.data) consumer = oauth.OAuthConsumer(config.OAUTH_CONSUMER_KEY, config.OAUTH_CONSUMER_SECRET) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, verifier=verifier, http_url=config.ACCESS_TOKEN_URL) signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request.sign_request(signature_method_hmac_sha1, consumer, token) try: result = urlfetch.fetch(oauth_request.to_url(), method=oauth_request.http_method) except urlfetch.Error: return 'Network Error!' try: token = oauth.OAuthToken.from_string(result.content) except BaseException: return 'Wrong verifier!' u = User.get_by_key_name(self._jid) if u: u.access_key = token.key u.access_secret = token.secret u.put() else: User(key_name=self._jid, access_key=token.key, access_secret=token.secret).put() s.data = None s.put() return 'Successfully bind your account.'
def get(self): email = self.get_argument("e", "") emailverify = self.get_argument("k", "") if User.by_email_verify(email, emailverify): self.render("setpass.html") else: self.render("forgotpass.html")
def post(self): name = self.get_argument("name", '') password = self.get_argument("password", '') password = hashlib.md5(password).hexdigest() email = self.get_argument("email", '') domain = self.get_argument("domain", '') if domain == '': domain = name if User.find({'user_email': email}).count() > 0: self.write('用户已经存在,请直接登录') self.redirect("/login") else: res = User res['id'] = res.find().count() + 1 res['user_name'] = name res['user_pass'] = password res['user_email'] = email res['user_domain'] = domain res.new(res) user = {'user_id': res.id, 'user_name': res.user_name, 'user_email': res.user_email, 'user_domain': res.user_domain} self.set_secure_cookie("user", tornado.escape.json_encode(user)) self.redirect(self.get_argument("next", "/"))
def get_userinfo(email): try: userinfo = User.get(User.email == email) except Exception: return False else: return userinfo
def post(self): name = self.get_argument('name', '') password = self.get_argument('password', '') email = self.get_argument('email', '') domain = self.get_argument('domain', '') password = utils.make_password(password) if domain == '': domain = name if User.by_email(email): self.redirect('/login') # self.write('用户已经存在,请直接登录') else: res = User res['id'] = res.find().count() + 1 print(name, type) res['user_name'] = name res['user_pass'] = password res['user_email'] = email res['user_domain'] = domain res.new(res) send_joinus_email(email, name) user_info = { 'user_id': res.id, 'user_name': res.user_name, 'user_email': res.user_email, 'user_domain': res.user_domain} self.set_secure_cookie( 'user', tornado.escape.json_encode(user_info)) self.redirect(self.get_argument('next', '/'))
def get(self, node='home'): page = self.get_argument("page", 1) # share_res = Share.find({'status': 0}).sort( # 'score', DESCENDING).limit(11).skip((int(page) - 1) * 11) share_res = Share.find({'status': {'$gte': 1}}).sort( '_id', DESCENDING).limit(11).skip((int(page) - 1) * 11) pagesum = (share_res.count() + 10) / 11 shares = [] for share in share_res: if share.id in (48, 47): continue user = User.by_sid(share.user_id) share.name = user.user_name share.published = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(share.published)) share.domain = user.user_domain share.markdown = cutter( markdown2.markdown(share.markdown)) share.title = share.title.split('_')[0] shares.append(share) self.render( "node.html", shares=shares, pagesum=pagesum, page=page, node=node, )
def post(self): user = User.by_sid(self.current_user["user_id"]) user["user_name"] = self.get_argument("name", None) user["user_city"] = self.get_argument("city", None) user["user_say"] = self.get_argument("say", None) user.save() self.redirect("/setting")
def post(self): name = self.get_argument("name", "") password = self.get_argument("password", "") email = self.get_argument("email", "") domain = self.get_argument("domain", "") password = utils.make_password(password) if domain == "": domain = name if User.by_email(email): self.redirect("/login") # self.write('用户已经存在,请直接登录') else: res = User res["id"] = res.find().count() + 1 res["user_name"] = name res["user_pass"] = password res["user_email"] = email res["user_domain"] = domain res.new(res) send_joinus_email(email, name) user_info = { "user_id": res.id, "user_name": res.user_name, "user_email": res.user_email, "user_domain": res.user_domain, } self.set_secure_cookie("user", tornado.escape.json_encode(user_info)) self.redirect(self.get_argument("next", "/"))
def register(bot, update, args): args_msg = """Error, please register using the command: ``` /register [ssc_email] [ssc_password] ``` *WARNING: Your account information will be stored in plain text, use this bot at your own risk*""" exists_msg = """Error, account already exists. To update your account information please use the command: ``` /update [ssc_email] [ssc_password] ``` *WARNING: Your account information will be stored in plain text, use this bot at your own risk*""" success_msg = "Registered successfully!" if len(args) != 2: bot.send_message(chat_id=update.message.chat_id, text=args_msg, parse_mode="Markdown") return telegram_id = update['message']['chat']['id'] username = update['message']['chat']['username'] ssc_username = args[0] ssc_password = args[1] session = Session() user = session.query(User).filter_by(telegram_id=telegram_id).first() if user: bot.send_message(chat_id=update.message.chat_id, text=exists_msg, parse_mode="Markdown") session.close() return user = User(telegram_id, username, ssc_username, ssc_password) status = Status(telegram_id) session.add(user) session.add(status) session.commit() session.close() bot.send_message(chat_id=update.message.chat_id, text=success_msg, parse_mode="Markdown") return
def user_status_update(self, user_id: int, status: str) -> Any: """ Disable User""" try: db_user = User.objects(id=user_id).first() if status == "enable": db_user.is_active = True elif status == "disable": db_user.is_active = False db_user.save() return db_user except Exception as e: fastapi_logger.exception("user_status_update") return None
def oauth(): resp = openstreetmap.authorized_response() if resp is None: return 'Denied. <a href="' + url_for('login') + '">Try again</a>.' session['osm_token'] = ( resp['oauth_token'], resp['oauth_token_secret'] ) user_details = openstreetmap.get('user/details').data uid = int(user_details[0].get('id')) session['osm_uid'] = uid try: User.get(User.uid == uid) except User.DoesNotExist: User.create(uid=uid) if session.get('next'): redir = session['next'] del session['next'] else: redir = url_for('front') return redirect(redir)
def decode_password_token(self, token: str, verify_exp: bool = False) -> Dict[str, Any]: assert token, 'Token required' assert jwt.get_unverified_header(token).get( 'tok') == 'pas', 'Password reset token required' user = jwt.decode(token, verify=False).get('own') with session_scope() as session: password = User.get_by_id(session, user).password return jwt.decode(token, key=password, algorithms=[self.alg], options={'verify_exp': verify_exp})
def add_users(): for u in get_users(): user = User(id_in_services=u["id"], name=u["username"], email=u["email"], city=u["address"]["city"], company=u["company"]["name"], website=u["website"]) s.add(user) s.commit() logger.success("Пользователь {}({}) успешно добавлен!", u["username"], u["email"]) s.close()
def create_user(name, username, email, password): user = get_user_by_email(email) if user is not None: return False, user new_user = User(name=name, username=username, email=email, password=password) db.session.add(new_user) db.session.commit() return True, new_user
def create_user(self, email, password, fname=None, lname=None): author = User(seq('users'), email, password, fname, lname) if not self.check_password(password): raise UserPasswordNotStrongEnough try: self.session.add(author) self.session.commit() except sqlalchemy.exc.IntegrityError: self.session.rollback() raise UsernameAlreadyExistsException
def post(self): """Add user""" json_data = request.get_json(force=True) name = json_data['name'] email = json_data['email'] try: repository.add_user(User(id=email, name=name)) return {'status': "done"} except RepositoryException as err: return ReturnDocument(err.__doc__, "error").asdict() except KeyError as err: return ReturnDocument(f"{err.__str__()}-{err.__doc__}", "error").asdict()
def update_user_profile(id: int, food: List[int] = None, pantry: bool = None, eager: int = None): with session_scope() as session: user = User.get_by_id(session, id) if food: UserFoodPreference.update(session, id, food) if pantry: user.pitt_pantry = pantry if eager: user.eagerness = eager session.merge(user)
async def associate(self, context, kol_id=None): """ Member is asking to associate their Discord and KoL accounts """ if kol_id is None: await context.send("Please specify your KoL id") return kol = self.bot.kol member = context.author token = str(uuid4())[:8] User.replace(kol_id=kol_id, discord_id=member.id, token=token).execute() try: await kol.kmail.send(recipient=kol_id, message="$verify {}".format(token)) await context.send( "Verification token sent to your account via kmail. Paste the command from there into this DM." ) except UserNotFoundError: await context.send("User id is invalid") except Error as e: print(e) await context.send("There was an error sending you a kmail")
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict]: cpf = tracker.get_slot("cpf") email = tracker.get_slot("email") user = User.where(User.document == cpf).first() user.email = email session.commit() return []
def allUsers(self): users = [] sql = "select * from user;" cursor.execute(sql) data = cursor.fetchone() while data != None: user = User.User() user.setId(data[0]) user.setUsername(data[1]) user.setPassword(data[2]) users.append(user) data = cursor.fetchone() return users
def add_new_user(): if request.method == 'POST': first_name = request.form.get('first_name') last_name = request.form.get('last_name') address = request.form.get('address') city = request.form.get('city') new_address = Address(address=address, city=city) new_user = User(first_name=first_name, last_name=last_name, address=new_address) DBUser(new_user).add_entity() return redirect(url_for('/db.manage_data')) return render_template('add_user.html')
def get(self): def handle_result(rpc): try: result = rpc.get_result() except urlfetch.Error: return else: jid = self.jids[id(rpc)] emails_map = parse(result.content) emails = list() for email in emails_map: if not Mail.get_by_key_name(email['id']): if Mail(key_name=email['id']).put(): str = 'From: %(author)s\nTitle: %(title)s\nSummary: %(summary)s\nTime: %(time)s\n%(url)s' % email emails.insert(0, str) if emails: while CapabilitySet('xmpp').is_enabled(): try: xmpp.send_message(jid, '\n\n'.join(emails)) except xmpp.Error: pass else: break def create_callback(rpc): return lambda: handle_result(rpc) if not db.WRITE_CAPABILITY: return rpcs = [] self.jids = {} for u in Session.all().filter('data =', None): jid = u.key().name() u = User.get_by_key_name(jid) token = oauth.OAuthToken(u.access_key, u.access_secret) consumer = oauth.OAuthConsumer(config.OAUTH_CONSUMER_KEY, config.OAUTH_CONSUMER_SECRET) oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, token=token, http_url=config.RESOURCE_URL) signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1() oauth_request.sign_request(signature_method_hmac_sha1, consumer, token) rpc = urlfetch.create_rpc() rpc.callback = create_callback(rpc) urlfetch.make_fetch_call(rpc, oauth_request.http_url, headers=oauth_request.to_header()) rpcs.append(rpc) self.jids[id(rpc)] = jid for rpc in rpcs: rpc.wait()
def thanks(update, context): _log_msg(update.message.text, 'user', update, state='registration_final') try: awc_code = int(update.message.text) except: return _awc_code_error(update) if len(str(awc_code)) != 11: return _awc_code_error(update) context.user_data['awc_code'] = update.message.text # HACK: to calculate the cohort d1 = datetime(2019, 6, 26) d2 = datetime.utcnow() monday1 = (d1 - timedelta(days=d1.weekday())) monday2 = (d2 - timedelta(days=d2.weekday())) cohort = (monday2 - monday1).days // 7 # SAVE THE USER new_user = User( chat_id=update.effective_chat.id, first_name=context.user_data['preferred_name'], last_name=update.message.from_user.last_name, track=context.user_data['track'], phone_number=context.user_data['phone_number'], child_name=context.user_data['child_name'], child_gender=context.user_data['child_gender'], child_birthday=datetime.strptime( context.user_data['child_birthday'], '%Y-%m-%d'), current_state='echo', current_state_name='echo', aww=context.user_data['aww'], aww_number=context.user_data['aww_number'], awc_code=context.user_data['awc_code'], registration_date=datetime.utcnow(), cohort=cohort, test_user=False ) Database().insert(new_user) if settings.HINDI: send_text_reply( "धन्यवाद! अब आप पंजीकृत हैं।", update, state='registration_final') send_text_reply( "यदि आप मेरे द्वारा पहला संदेश भेजने से पहले थोड़ा अभ्यास करना चाहते हैं, तो कृपया 1 से 10 के बीच कोई भी संख्या दर्ज करें और मैं आपको बताउंगी कि मैंने क्या समझा।", update, state='registration_final') send_text_reply( "कृपया अपने पहले संदेश की प्रतीक्षा करें, जो अगले 7 दिनों के भीतर मेरे द्वारा आना चाहिए। आप मेरे द्वारा भेजे गए किसी भी सन्देश को फिर से पा सकते हैं, बस किसी भी समय हेल्लो टाइप करके!", update, state='registration_final') else: send_text_reply( "Thank you! You're registered. Please wait for your first message, that should come within the next 7 days. If you want to practice before I sent you the first message, please enter a number between 1 to 10 and I will tell you what I understood. You can access all content I have sent you after that just by typing hello at any time!", update, state='registration_final') return ConversationHandler.END
def post(self): body = request.get_json() if not User.objects(email=body["email"]): if len(body["password"]) >= 6: user = User(email=body["email"], password=body["password"]) user.hash_password() user.save() return {'id': str(user.id)}, 200 return {"error": "Short password"}, 401 return {"error": "Email was already used!"}, 401
def get_comments(share, like_commentids, dislike_commentids): comments = [] comment_res = Comment.find({'share_id': share.id}) for comment in comment_res: user = User.by_sid(comment.user_id) comment.name = user.user_name comment.domain = user.user_domain comment.gravatar = get_avatar(user.user_email, 50) print(like_commentids, comment.id) print(dislike_commentids, comment.id) comment.is_liking = comment.id in like_commentids comment.is_disliking = comment.id in dislike_commentids comments.append(comment) return comments
def registration_post(): email = request.form.get('email').strip() password = request.form.get('password').strip() if email != "" and password != "" and database.create_user( email, email, password): remember = request.form.get('remember') is not None user_id = database.check_user(email, email, password) login_user(User(user_id, database), remember=remember) return redirect("/") flask.flash('Не удалось создать учётную запись. ' 'Возможно, Вы уже зарегистрированы?') return redirect("/login")
def create_user(first_name, last_name, username, phone_number, email, password): user = get_user_by_email(email) if user is not None: return False, user new_user = User(first_name=first_name, last_name=last_name, username=username, phone_number=phone_number, mail=email, password=password) db.session.add(new_user) db.session.commit() return True, new_user
def create_new_user(self, email, password, **params): if not email or not password: raise SignUpError("invalid input") user = self.session.query(User).filter_by(login=email).first() if user is not None: raise SignUpError("email is already used") new_user = User(login=email, username=params.get("username", email), pwd_hash=password_hash(password)) self.activate_session_token(new_user)
def ufwlist(): json_list = request.get_json(silent=True) if json_list is None: abort(400, 'bad request - expected json payload') elif not isinstance(json_list, list): abort(400, 'bad request - expected a list') ret = [] for user in User.select().where(User.wallet_address.in_(json_list)): ret.append({ 'discord_id': user.user_id, 'user_name': user.user_name, 'created_ts': format_js_iso(user.created), }) return jsonify(ret)
def get(self): try: user=(request.form['User']) except: user = None if user != None: print(user) if not User.objects(username=user): return {"error": 'User not found'}, 404 else: return CustomerHistory.objects(userID = user).to_json(),200 else: print() return CustomerHistory.objects().to_json(),200
def get(self): share_res = Share.find() shares = [] for share in share_res: user = User.by_sid(share.user_id) share.name = user.user_name share.published = datetime.datetime.fromtimestamp(share.published) share.updated = datetime.datetime.fromtimestamp(share.updated) share.domain = user.user_domain share.content = markdown2.markdown(share.markdown) shares.append(share) self.set_header("Content-Type", "application/atom+xml") self.render("feed.xml", shares=shares)
def new_roadblock(bot: Bot, message: Message) -> None: if banned(message.from_user) or message.chat_id == roads_chat \ or spam(message): return user_id = message.from_user.id with db_session: U.get(user_id=user_id).roadblocks_count += 1 user = bot.get_chat_member(mods_chat, user_id) if user['status'] in ('creator', 'administrator', 'member'): bypass_moderators(bot, message) return message.reply_text(BOT_MSG_ACCEPT.format(message.from_user.name)) msg = BOT_REQUEST_CHECK.format(message.from_user.name) mods_message = bot.send_message(mods_chat, msg, reply_markup=mods_keyboard) message.forward(mods_chat) with db_session: Roadblock(author=message.from_user.id, chat_id=message.chat_id, chat_message_id=message.message_id, mods_message_id=mods_message.message_id)
def oauth(): resp = openstreetmap.authorized_response() if resp is None: return 'Denied. <a href="' + url_for('login') + '">Try again</a>.' session['osm_token'] = (resp['oauth_token'], resp['oauth_token_secret']) user_details = openstreetmap.get('user/details').data session['osm_uid'] = int(user_details[0].get('id')) name = user_details[0].get('display_name') user, created = User.get_or_create(uid=session['osm_uid'], defaults={'name': name}) if user.name != name or created: user.name = name user.save() return redirect(url_for('front'))
def create_user(email, password, first_name, last_name): optional_user = get_user_by_email(email) if optional_user: return False, optional_user user = User(email=email, password=password, firstName=first_name, lastName=last_name) db.session.add(user) db.session.commit() return True, user
async def process_group(msg: types.Message, state: FSMContext): async with state.proxy() as data: direction = data["direction"] if msg.text not in get_group_names_by_short_direction_name(direction): return await msg.answer("Выберите группу с клавиатуры!") data["group"] = msg.text user_data = msg.from_user user = User(user_data.id, user_data.first_name, user_data.last_name, user_data.username, user_data.language_code, user_data.is_bot, get_group_id_by_name(msg.text)) insert_user(user) await state.finish() await msg.answer("Ура! Теперь вам доступно расписание!", reply_markup=menu_kb)
def signup(email: str, password: str, name: str = None) -> Tuple[Optional['UserData'], Optional[str]]: """ Sign user up with :param email: :param password: :param name: :return: """ with session_scope() as session: user = User.create(session, User(email=email, password=password)) if user is not None: code = None threshold = int(get_property('user.threshold')) if threshold > 0: logging.info("passed threshold") code = UserVerification.add(session, user.id).code set_property('user.threshold', str(threshold - 1)) else: logging.info("failed threshold") return UserData(user), code return None, None
def login(): form = LoginForm() if request.method == 'POST' and form.validate_on_submit(): name = form.username.data pwd = form.password.data remember = form.remember.data user = User.objects(name=name, pwd=pwd).first() if user: flash('login success !', category='login success') login_user(user, remember=form.remember.data) return redirect('/admin') else: return render_template('login.html', form=form, status=1) return render_template('login.html', form=form)
def login(): form = LoginForm() if current_user.is_authenticated: return redirect('/user/me') elif request.method == 'POST' and form.validate_on_submit(): username = form.username.data remember = form.remember.data password = form.password.data user = User.objects(username=username).first() if user.check_password(password): login_user(user, remember=remember) return redirect('/user/me') return render_template('login.html', form=form, status=0) return render_template('login.html', form=form, status=1)