def post(self): error = "" get_username = self.request.get("username") get_password = self.request.get("password") get_verify = self.request.get("verify") get_email = self.request.get("email") if get_email and not MAIL_RE.match(get_email): error = "Invalid e-mail" if get_password != get_verify: error = "Passwords do not match." if not PASS_RE.match(get_password): error = "Invalid password." if not USER_RE.match(get_username): error = "Invalid Username. Please try again." if db.GqlQuery("SELECT __key__ FROM Users WHERE username = :1", get_username).count() != 0: error = "User already exists. Please choose a different username" if error: self.render(username=get_username, password=get_password, verify=get_verify, email=get_email, error=error) else: hashed_result = SaltHasher(get_password) user_db = Users(username=get_username, password=hashed_result.get_result()[0], email=get_email, salt=hashed_result.get_result()[1]) user_db.put() user_id = str(user_db.key().id()) self.response.headers.add_header('Set-Cookie', 'user_id=%s|%s; Path=/' % (user_id, hashed_result.get_result()[0])) self.redirect("/unit6/blog/welcome")
def __init__(self, my_ip): self.binary_flag = '' self.connection_type = '' self.ip = my_ip # ip to send to client when transferring data self.port = 0 # port to send self.last_file_position = 0 users = Users(ORIGINAL_DIR.replace('\\%s' % FILE_DIR, '')) self.user_data = users.get_users_pass() self.command_dict = { 'USER': self.user_check, #'FEAT': self.get_features, haven't implemented opts 'SYST': self.syst_command, 'CWD': self.cwd, 'PWD': self.pwd, 'DELE': self.delete, 'TYPE': self.set_binary_flag, 'PASV': self.passive_connection, 'LIST': self.list_command, 'PORT': self.active_connection, 'HELP': self.help_command, 'RETR': self.retrieve_file, 'CDUP': self.cwd, 'SIZE': self.return_size, 'REST': self.reset_transfer, 'RNFR': self.rename, 'STOR': self.store_something }
def login(): try: payload = converts_keys(json.loads(request.data), case='snake') except ValueError: raise EmptyPayloadError check_only_required_payload_props(payload, 'login', 'password', 'remember_me') if payload.pop('remember_me'): max_age = REMEMBER_ME_MAX_AGE else: max_age = None with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: if 'token' in request.cookies: try: cursor.execute(Users.logout(), request.cookies) except Exception: pass cursor.execute(Users.login(), payload) record = cursor.fetchone() try: token = record['token'] except TypeError: raise AuthenticationError response = make_response(jsonify(), 201) response.set_cookie('token', value=token, max_age=max_age, samesite=None, secure=False, httponly=False) return response
async def wrapper(answer: Message, telegram_id): data = [(i.vk_id, i.telegram_id) for i in Users.select() if i.vk_id == answer.from_id] if not data: Users.create(vk_id=answer.from_id, telegram_id=telegram_id) await answer('Отправь мне аудиозаписи во вложении') else: await answer('Отправь мне аудиозаписи во вложении')
def getUserInfo(self, comic_id, user): ui = self.getSession().query(Users).filter(Users.id == int(user)).filter(Users.comic_id == int(comic_id)).first() if ui is None: #Build user/comic record. record = Users() record.id = user record.comic_id = comic_id self.getSession().add(record) logging.debug(u"User Info: {0}".format(ui)) return ui
def create(self, user): self.__setUserDate(user) empty = self.__isEmpty(["name", "password", "role", "email"]) if len(empty) > 0: return {"code": 403, "empty": empty} users = Users(name=self.name, email=self.email, website=self.website, password=self.password, role=self.role) created = users.create() if created is None: return {"code": 401, "message": "user or email already exits"} return {"code": 200, "name": self.name, "role": self.role, "id": created}
def initAuth(self): if self.type is None: return{'code':405, 'message': 'miss type'} users = Users(type=self.type, oauthId=self.oauthId, email=self.email) user = users.get() print(user) if user is None: userData = users.create() return {'code': 301, 'userName': userData['name'], 'userId': userData['id']} return {'code': 200, 'userName': user['name']}
def update(self, user): self.__setUserDate(user) empty = self.__isEmpty(["name", "email"]) if len(empty) > 0: return {"code": 403, "message": empty[0] + " is required"} users = Users(name=self.name, website=self.website, email=self.email, id=self.id) user = users.get() if user["id"] != self.id: return {"code": 301, "message": "name or email already exits"} users.update() return {"code": 200}
def login(self): empty = self.__isEmpty(["email", "password"]) if len(empty) > 0: return {"code": 403, "empty": empty} users = Users(email=self.email) user = users.get() if user is None: return {"code": 404, "message": "user doesn't exits"} if self.__pwdCrypto(self.password) != user["password"]: return {"code": 401, "message": "Incorrect email or password"} return {"code": 200, "name": user["name"], "role": user["role"], "id": user["id"]}
def me(): cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() cursor.execute(Users.me(), record) me = cursor.fetchone() return jsonify(converts_keys(me, case='camel'))
def new_user(): username = request.json.get('username') password = request.json.get('password') if username is None or password is None: abort(400) # missing arguments if db.session.query(Users).filter_by( username=username).first() is not None: abort(400) # existing user user = Users(username=username) user.hash_password(password) db.session.add(user) db.session.commit() return jsonify({'username': user.username}), 201
def setup(): db.drop_all() db.create_all() user = Users(username='******', email=environ.get('EMAIL_ADDRESS')) user.password = environ.get('PASSWORD') db.session.add(Tags(name='flask')) db.session.add(Tags(name='biology')) db.session.add(Tags(name='chemistry')) db.session.add(user) db.session.commit()
def singup(): register_form = Registration() if register_form.validate_on_submit(): email = register_form.mail.data name = register_form.nickname.data password = register_form.password.data existing_user = Users.query.filter_by(mail=email).first() if existing_user: abort(400) user = Users(name=name, mail=email) user.set_password(password) db.session.add(user) db.session.commit() return redirect(url_for('homepage')) return render_template('singup.html', form=register_form)
def get_comments(): params = converts_keys(request.args.to_dict(), case='snake') set_filter_params(DEFAULT_COMMENT_LIMIT, MAX_COMMENT_LIMIT, params) cookies = request.cookies if 'token' in cookies: with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() user_id = record['user_id'] else: user_id = 0 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Comments.filter(**params), { 'user_id': user_id, **params }) comments = cursor.fetchall() cursor.execute(Comments.count(**params), params) record = cursor.fetchone() for comment in comments: put_out_author(comment) return jsonify( converts_keys({ 'comments': comments, **record }, case='camel'))
def register(): # 注册 if request.method == 'POST': data = json.loads(request.get_data().decode('utf-8')) res = Login.pwd(data['pwd']) if res != "true": return jsonify( success = True, data = res ) else: db.session.commit() user = Users.query.filter(Users.id == data['name']).first() if user is None: user = Users(id = data['name'],pwd = data['pwd']) db.session.add(user) db.session.commit() user = Relationship(id = data['name'],books = '') db.session.add(user) db.session.commit() return jsonify( success = True, data = "Register Successfully!" ) else: return jsonify( success = True, data = "This Account has been Existed!" ) else: return render_template("register.html")
class Login(flask.views.MethodView): def __init__(self): self.users = Users() self.profile = Profile() def get(self): if 'email' in session: return self.profile.get() else: return flask.render_template('login.html') def post(self): print request.form['username'] session['email'] = request.form['username'] success = self.users.loginCheck(request.form['username'],request.form['password']) print success if(success): #r = requests.get('http://localhost/profile') return self.profile.get() #Response( # r.text, # status=r.status_code, # content_type=r.headers['content-type'], # ) else: return flask.render_template('login.html')
def requesthandler(self): """ Combined GET and POST requesthandler.""" doc = self.request.get('doc') if user_service == 'google': if doc =='y': www.serve(self,self.__doc__,title = '/users/logout') else: user = users.get_current_user() if user is not None: self.redirect(users.create_logout_url(self.request.uri)) else: self.redirect('/') else: success = False cookies = Cookies(self,max_age=3600) t = '<table><form action=/users/logout method=post>' t = t + '<tr><td>Session ID</td><td><input type=text name=session></td></tr>' t = t + '<tr><td colspan=2><input type=submit value=Logout></td></tr></table></form>' if doc == 'y': www.serve(self,t, sidebar = self.__doc__, title = '/users/logout') else: try: session = cookies['session'] except: session = self.request.get('session') if len(session) > 0 and len(session) < 256: success = Users.logout(session=session) cookies['session']='' self.response.headers['Content-Type']='text/plain' if success: self.response.out.write('ok') else: self.response.out.write('error') else: www.serve(self,t, sidebar=self.__doc__, title = '/users/logout')
def createUser(login_session): newUser = Users(name=login_session['username'], email=login_session['email']) session.add(newUser) session.commit() user = session.query(Users).filter_by(email=login_session['email']).one() return user.id
def addUser(): args = request.json new_user = Users(username=args['username'], permission=args['permission']) db_session.add(new_user) db_session.commit() resp = jsonify(success=True) return resp
def get_posts(): params = converts_keys(request.args.to_dict(), case='snake') set_filter_params(DEFAULT_POST_LIMIT, MAX_POST_LIMIT, params) cookies = request.cookies if 'token' in cookies: with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() user_id = record['user_id'] else: user_id = 0 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: if 'search' in params: params['search'] = '%' + params['search'] + '%' cursor.execute(Posts.filter(**params), { 'user_id': user_id, **params }) posts = cursor.fetchall() cursor.execute(Posts.count(**params), params) record = cursor.fetchone() for post in posts: put_out_author(post) return jsonify(converts_keys({'posts': posts, **record}, case='camel'))
def list(): if request.method == 'POST': task = request.form["task"] name = request.form["name"] taskData = session.query(Task).all() engine.connect() # if user exist, do not store in users table. # otherwise insert into the table. user_id = _searchUserNumber(name) if (not _isUserExist(name)): session.add(Users(id=user_id, name=name)) session.commit() session.add( Task(task_id=len(taskData) + 1, task=task, isdone=False, user_id=user_id)) session.commit() else: session.add( Task(task_id=len(taskData) + 1, task=task, isdone=False, user_id=user_id)) session.commit() session.rollback() return redirect('http://localhost:8080/') else: return _get()
def requesthandler(self): """ Combined GET and POST request handler""" username = clean(self.request.get('username')) email = clean(self.request.get('email')) remote_addr = self.request.remote_addr pw = clean(self.request.get('pw')) doc = self.request.get('doc') firstname = clean(self.request.get('firstname')) lastname = clean(self.request.get('lastname')) description = clean(self.request.get('description')) skype = self.request.get('skype') facebook = self.request.get('facebook') linkedin = self.request.get('linkedin') tags = clean(self.request.get('tags')) city = self.request.get('city') state = self.request.get('state') country = self.request.get('country') if len(city) < 1: location = geo.get(remote_addr) else: location['city']=city location['state']=state location['country']=country if type(location) is dict: city = location.get('city', '') state = location.get('state','') country = location.get('country', '') try: latitude = location['latitude'] longitude = location['longitude'] except: latitude = None longitide = None else: city = '' state = '' country = '' latitude = None longitude = None callback = self.request.get('callback') if len(username) > 5 and len(pw) > 5 and user_service != 'google': self.response.headers['Content-Type']='text/plain' result = Users.new(username, email, pw, remote_addr, firstname=firstname, lastname=lastname, description=description, skype=skype, facebook=facebook, linkedin=linkedin, city=city, state=state, country=country, latitude=latitude, longitude=longitude) if len(callback) > 0: self.redirect(callback) elif result: self.response.out.write('ok') else: self.response.out.write('error') else: t = '<form action=/users/new method=post accept-charset=utf-8><table>' t = t + '<tr><td>Username</td><td><input type=text name=username></td></tr>' t = t + '<tr><td>Email</td><td><input type=text name=email></td></tr>' t = t + '<tr><td>Password</td><td><input type=password name=pw></td></tr>' t = t + '<tr><td colspan=2><input type=submit value="Create Account"></td></tr>' t = t + '</form></table>' www.serve(self,t, sidebar=self.__doc__, title = '/users/new')
async def wrapper(answer: Message): for attachment in answer.attachments: telegram_id = Users.get(Users.vk_id == str(answer.from_id)).telegram_id telegram.send_audio( chat_id=telegram_id, audio=attachment.audio.url, caption=f"{attachment.audio.artist} - {attachment.audio.title}") await answer('Мы отправили Вам аудиозаписи в Telegram')
def check_cookie(self): user_cookie = self.request.cookies.get("user_id") if user_cookie and user_cookie != "": user_id = int(user_cookie.split("|")[0]) _user_db_data = Users.get_by_id(user_id) user = _user_db_data.user_name return user else: return None
def __init__(self, **kwargs): super(DatabaseUsers, self).__init__(**kwargs) self.users = Users(ORIGINAL_DIR) self.user_pass = self.users.get_users_pass() self.layout = GridLayout(cols=1, size_hint_y=None) self.layout.bind(minimum_height=self.layout.setter('height')) for user, password in self.user_pass: self.user_button = OptionsButton(text='user: %s, pass: %s' % (user, password), size_hint_y=None, user=user, password=password) self.user_button.bind(font_size=lambda x: self.width / 4) self.user_button.bind( on_press=self.user_button.dropdown_options.open) self.layout.add_widget(self.user_button) self.add_widget(self.layout)
def lookup(cookies, ip): cookie = facebook.get_user_from_cookie(cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET) if cookie: # Store a local instance of the user data so we don't need # a round-trip to Facebook on every request user = Users.find(facebookid=cookie["uid"]) try: if not user: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") Users.add(ip, facebookid=str(profile['id']), name=profile['name'], profile_url=profile['link']) else: graph = facebook.GraphAPI(cookie["access_token"]) profile = graph.get_object("me") Users.add(ip, facebookid=str(profile['id']), name=profile['name'], profile_url=profile['link']) return profile except: return else: return
def requesthandler(self): username = self.request.get('username') pw = self.request.get('pw') parm = self.request.get('parm') value = self.request.get('value') remote_addr = self.request.remote_addr result = Users.setparm(username, pw, parm, value) if result: self.response.out.write('ok') else: self.response.out.write('error')
def isUser(self, session): if self.userId is None: if 'userId' in session: return {'code': 301, 'id': session['userId']} return {'code': 404} if 'userId' in session and self.userId != session['userId']: return {'code': 301, 'id': session['userId']} users = Users(id=self.userId) user = users.get() if user is None: return {'code': 404, 'message': 'not exists'} userName = None if 'user' in session: userName = session['user'].lower() session.pop('user') _users = Users(name=userName) _user = _users.get() if _user is not None: userName = userName + str(randint(1, 20)) return {'code': 200, 'userName': userName}
def create_user(): if request.method == "POST": user = Users(username=request.form["uname"], email=request.form["email"], phone=request.form["pnumber"], password=request.form["password"]) db.session.add(user) db.session.commit() return redirect(url_for('home')) return render_template('signup.html')
def logout(): with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.logout(), request.cookies) response = make_response(jsonify(), 205) response.set_cookie('token', value='', max_age=0, samesite=None, secure=False, httponly=False) return response
def get_user_data(user_id): cookies = request.cookies with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: if 'token' in cookies: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() try: follower_id = record['user_id'] except KeyError: cursor(Users.logout(), cookies) follower_id = 0 else: follower_id = 0 cursor.execute(Users.get_user_data(), { 'id': user_id, 'follower_id': follower_id }) profile = cursor.fetchone() put_out_contacts(profile) return jsonify(converts_keys(profile, case='camel'))
def get_followings(): cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() cursor.execute(Followings.get_followings(), {'follower_id': record['user_id']}) followings = cursor.fetchall() return jsonify(converts_keys({'followings': followings}, case='camel'))
def register(): user = Users() user.name = request.get_json()['name'] user.username = request.get_json()['username'] user.email = request.get_json()['email'] user.password = bcrypt.generate_password_hash( request.get_json()['password']).decode('utf-8') try: session.add(user) session.commit() except: error = { 'response': 500, 'name': user.name, 'username': user.username, 'email': user.email } return error # You don't really need jsonify anymore result = { 'response': 200, 'name': user.name, 'username': user.username, 'email': user.email } return jsonify(result)
def unfollow(user_id): cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() cursor.execute(Followings.unfollow(), { 'follower_id': record['user_id'], 'user_id': user_id }) return jsonify(), 204
def verify_password(username_or_token, password): #Try to see if it's a token first user_id = Users.verify_auth_token(username_or_token) print(user_id) if user_id: user = db.session.query(Users).filter_by(id=user_id).one() else: user = db.session.query(Users).filter_by( username=username_or_token).first() if not user or not user.verify_password(password): return False g.user = user return True
def get(self): """ Processes HTTP GET calls.""" username = self.request.get('username') d = self.request.get('doc') if len(username) > 7: self.response.headers['Content-Type']='text/plain' count = Users.count(username) self.response.out.write(str(count['edits']) + ',' + str(count['words'])) else: t = '<table><form action=/users/count method=get accept-charset=utf-8>' t = t + '<tr><td>Username</td><td><input type=text name=username><input type=submit value=OK></td></tr>' t = t + '<tr><td colspan=2><input type=submit value=OK></td></tr></table></form>' www.serve(self,t, sidebar = self.__doc__, title = '/users/count')
def done(self): username = self.user_name.group().lower() # Check if user already exists. if Users.by_name(username): self.errors(name_error="User already exists") else: password = self.passwd.group() email = None if self.email: email = self.email # hash the password before storing in database passwd_hash = Secure.make_salt_password(username, password) # Add the user, hashed password or email to the database usr_obj = Users.add(username, passwd_hash, email) cookie_val = self.make_cookie(str(usr_obj.key().id())) self.set_cookie("user_id", cookie_val) self.redirect("/blog/newpost")
def requesthandler(self): username = self.request.get('username') parm = self.request.get('parm') value = Users.getparm(username, parm) self.response.headers['Content-Type']='text/plain' if type(value) is int: txt = str(value) elif type(value) is list: txt = '' for v in value: txt = txt + ',' + v else: txt = str(value) self.response.out.write(txt)
def get(self): """Implements HTTP GET calls to this service""" k=self.request.get('key') doc=self.request.get('doc') if len(k) > 0: if Users.validate(k): self.redirect('/') else: self.redirect('/') else: t = '<table><form action=/users/validate method=get>' t = t + '<tr><td>Validation key</td><td><input type=text name=k size=32>' t = t + '<tr><td colspan=2><input type=submit value=OK></td></tr></table></form>' www.serve(self,t, sidebar=self.__doc__, title = '/users/validate')
def usersignup(): form = SignupForm() if request.method == 'POST': if form.validate() == False: return render_template('usersignup.html', form=form) else: newuser = Users(form.first_name.data, form.last_name.data, form.email.data, form.password.data) db.session.add(newuser) db.session.commit() return "User SignUp Success!" ##Change to more suitable page elif request.method == 'GET': return render_template('usersignup.html', form=form)
def create_post(): payload = converts_keys(loads(request.data), case='snake') check_only_required_payload_props(payload, 'category', 'content') cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() author_id = record['user_id'] cursor.execute(Posts.create(), {'author_id': author_id, **payload}) post = cursor.fetchone() put_out_author(post) return jsonify(converts_keys(post, case='camel')), 201
def delete_comment(comment_id): cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) user_id = cursor.fetchone()['user_id'] cursor.execute(Comments.get_author_id(), {'id': comment_id}) author_id = cursor.fetchone()['author_id'] if user_id != author_id: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Comments.delete(), {'id': comment_id}) return jsonify(), 205
def feed(): cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 params = converts_keys(request.args.to_dict(), case='snake') set_filter_params(DEFAULT_POST_LIMIT, MAX_POST_LIMIT, params) with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) follower_id = cursor.fetchone()['user_id'] cursor.execute(Followings.feed(), { 'follower_id': follower_id, **params }) posts = cursor.fetchall() return jsonify(converts_keys({'posts': posts}, case='camel'))
def get(self): user_cookie = self.request.cookies.get("user_id") if user_cookie: user_id, hashed_result = user_cookie.split("|") query = Users.get_by_id(int(user_id)) if query: username = query.username user_hashed_pw = query.password if user_hashed_pw == hashed_result: self.render(username="******" + username) return self.redirect("/unit5/blog/signup")
def register(): if session.get('logged_in'): flash("Already logged in!") return if request.method == 'POST': user = Users(request.form['username'], request.form['password']) db.session.add(user) global_chat = Chats.query.get(1) global_chat.users.append(user) try: db.session.commit() except: flash('A user with that username already exists') return render_template('register.html') print('\nRecord was successfully added\n') return redirect(url_for('index')) return render_template('register.html')
def unlike(): params = converts_keys(request.args.to_dict(), case='snake') cookies = request.cookies if 'token' not in cookies: return jsonify(), 401 with connect(DSN) as connection: with connection.cursor(cursor_factory=RealDictCursor) as cursor: cursor.execute(Users.get_user_id(), cookies) record = cursor.fetchone() if 'post_id' in params: cursor.execute(Posts.unlike(), {**record, **params}) elif 'comment_id' in params: cursor.execute(Comments.unlike(), {**record, **params}) elif 'reply_id' in params: cursor.execute(Replies.unlike(), {**record, **params}) else: jsonify(), 400 return jsonify(), 205
def register(): session['logged_in'] = False if request.method == 'POST': username = request.form['username'] password = hashlib.md5(request.form['password'].encode()).hexdigest() if Users.query.filter_by(username=username).first(): flash('The username is already taken. Please choose another one.') return render_template('register.html', form=request.form) else: new = Users(username='******'.format(username), password='******'.format(password)) db.session.add(new) db.session.commit() flash('You are registered.') session['logged_in'] = True session['username'] = username return redirect(url_for('index')) return render_template('register.html', form=request.form)
def add_user(first, last, email, password): new_user = Users(first_name=first, last_name=last, email=email) new_user.password = bcrypt.generate_password_hash(password) db.session.add(new_user)
def requesthandler(self): """ Combined GET and POST request handler.""" doc = self.request.get('doc') if user_service == 'google': if doc =='y': www.serve(self,self.__doc__, title = '/users/auth') else: user = users.get_current_user() if user is None: self.redirect(users.create_login_url(self.request.uri)) else: self.redirect('/') else: cookies = Cookies(self,max_age=3600) try: session = cookies['session'] except: session = self.request.get('session') username = clean(self.request.get('username')) pw = self.request.get('pw') callback = self.request.get('callback') remote_addr = self.request.remote_addr proxyurl = self.request.get('proxyurl') username_field = self.request.get('username_field') pw_field = self.request.get('pw_field') success_msg = self.request.get('success_msg') error_msg = self.request.get('error_msg') location = geo.get(remote_addr) city = location.get('city','') state = location.get('state', '') country = location.get('country', '') try: latitude = location['latitude'] longitude = location['longitude'] except: latitude = None longitude = None if len(username) > 2 or len(session) > 2: if len(proxyurl) > 0 and len(username_field) > 0 and len(pw_field) > 0: form=dict() form[username_field]=username form[pw_field]=pw form['user_ip']=remote_addr form_data = urllib.urlencode(form) result = urlfetch.fetch(url=proxyurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type' : 'application/x-www-form-urlencoded','Accept-Charset' : 'utf-8'}) if result.status_code == 200: text = clean(result.content) if string.count(text,success_msg) > 0: m = md5.new() m.update(username) m.update(str(datetime.datetime.now())) session = str(m.hexdigest()) sessioninfo = dict() sessioninfo['username'] = username sessioninfo['session'] = session memcache.set('sessions|' + session, sessioninfo, 1800) else: session = None else: session=None else: sessioninfo = Users.auth(username, pw, session, remote_addr, city=city, state=state, country=country, latitude=latitude, longitude=longitude) if sessioninfo is not None: cookies['session'] = sessioninfo.get('session','') self.response.headers['Content-Type']='text/plain' if len(callback) > 0: self.redirect(callback) else: if type(sessioninfo) is dict: self.response.out.write(sessioninfo.get('session','')) else: self.response.out.write('') else: t = '<form action=/users/auth method=post accept-charset=utf-8>' t = t + '<table><tr><td>Username</td><td><input type=text name=username></td></tr>' t = t + '<tr><td>Password</td><td><input type=password name=pw></td></tr>' t = t + '<tr><td>Proxy URL (External Auth Server)</td><td><input type=text name=proxyurl value=http://www.worldwidelexicon.org/users/proxy></td></tr>' t = t + '<tr><td>Username Field</td><td><input type=text name=username_field value=username></td></tr>' t = t + '<tr><td>Password Field</td><td><input type=text name=pw_field value=pw></td></tr>' t = t + '<tr><td>Success Message / String</td><td><input type=text name=success_msg value=welcome></td></tr>' t = t + '<tr><td>Error Message / String</td><td><input type=text name=error_msg value=invalid></td></tr>' t = t + '<tr><td colspan=2><input type=submit value=LOGIN></td></tr>' t = t + '</table></form>' www.serve(self,t, sidebar = self.__doc__, title = '/users/auth')
def requesthandler(self): """ Combined GET and POST request handler""" doc = self.request.get('doc') language1 = self.request.get('language1') language2 = self.request.get('language2') language3 = self.request.get('language3') tl = self.request.get('tl') allow_anonymous = self.request.get('allow_anonymous') allow_machine = self.request.get('allow_machine') allow_unscored = self.request.get('allow_unscored') minimum_score = self.request.get('minimum_score') callback = self.request.get('callback') remote_addr = self.request.remote_addr if len(tl) < 1 and len(language1) < 1 and len(language2) < 1 and len(language3) < 1 and len(allow_unscored) < 1 and len(allow_anonymous) < 1 and len(allow_machine) < 1 and len(minimum_score) < 1 and len(callback) < 1: t = '<table><form action=/users/setoptions method=get accept-charset=utf-8>' t = t + '<tr><td>Language #1 (ISO Code)</td><td><input type=text name=language1 maxlength=3></td></tr>' t = t + '<tr><td>Language #2 (ISO Code)</td><td><input type=text name=language2 maxlength=3></td></tr>' t = t + '<tr><td>Language #3 (ISO Code)</td><td><input type=text name=language3 maxlength=3></td></tr>' t = t + '<tr><td>Allow Anonymous Translations (y/n)</td><td><input type=text name=allow_anonymous maxlength=1></td></tr>' t = t + '<tr><td>Allow Machine Translations (y/n)</td><td><input type=text name=allow_machine maxlength=1></td></tr>' t = t + '<tr><td>Allow Unscored Translations (y/n)</td><td><input type=text name=allow_unscored maxlength=1></td></tr>' t = t + '<tr><td>Minimum Score</td><td><select name=minimum_score><option selected value=''></option' t = t + '<option value=1>1</option><option value=2>2</option><option value=3>3</option>' t = t + '<option value=4>4</option><option value=5>5</option></select></td></tr>' t = t + '<tr><td colspan=2><input type=submit value=OK></td></tr></table></form' www.serve(self,t, sidebar= self.__doc__, title = '/users/setoptions') else: cookies = Cookies(self,max_age=36000) try: session = cookies['session'] except: session = '' if len(tl) > 0: cookies['tl'] = tl if len(language1) > 0: cookies['language1'] = language1 if len(language2) > 0: cookies['language2'] = language2 if len(language3) > 0: cookies['language3'] = language3 if len(allow_anonymous) > 0: cookies['allow_anonymous'] = allow_anonymous if len(allow_machine) > 0: cookies['allow_machine'] = allow_machine if len(allow_unscored) > 0: cookies['allow_unscored'] = allow_unscored if len(minimum_score) > 0: cookies['minimum_score'] = minimum_score if len(session) > 0: username = Users.getuser(session) if username is not None: udb = db.Query(User) udb.filter('username = '******'google' or user_service == 'proxy': item = User() item.username = username item.language1 = language1 item.language2 = language2 item.language3 = language3 item.allow_anonymous = allow_anonymous item.allow_machine = allow_machine item.allow_unscored = allow_unscored item.minimum_score = minimum_score item.put() self.response.headers['Content-Type']='text/html' if len(callback) > 0: self.redirect(callback) else: self.response.out.write('')
def add(ip, facebookid=None, email=None, name=None, gender=None, profile_url=None, native_language=None): location = geolocate(ip) country = location.get('country','') city = location.get('city','') try: latitude = float(location.get('latitude','')) longitude = float(location.get('longitude','')) except: latitude = None longitude = None udb = db.Query(Users) if facebookid is not None or email is not None: anonymous = False else: anonymous = True if anonymous: udb.filter('ip = ', ip) elif facebookid is not None: udb.filter('facebookid = ', facebookid) else: udb.filter('email = ', email) item = udb.get() newuser = False if item is None: newuser = True item = Users() item.city = city item.country = country if latitude is not None: item.latitude = latitude if longitude is not None: item.longitude = longitude if facebookid is not None: item.facebookid = facebookid if email is not None: item.email = email if name is not None: item.name = name if gender is not None: item.gender = gender if profile_url is not None: item.profile_url = profile_url item.last_login = datetime.datetime.now() item.put() if newuser: p = dict() url = '/wwl/userstats' taskqueue.add(url=url, params=p) return True
def get(self): users = Users(email=self.email, id=self.id, type=self.type, oauthId=self.oauthId, name=self.name) user = users.get() if user is None: return {"code": 404, "message": "user doesn't exits"} return {"code": 200, "data": user}
def __init__(self): self.users = Users() self.profile = Profile()
def post(self): globals.init() current_url = self.request.url.split('/')[-1] if current_url == 'main': globals.main_page = True has_error = False user_input = self.request.get('username') password_input = self.request.get('password') verify_input = self.request.get('verify') email_input = self.request.get('email') valid_u = utils.valid_username(user_input) valid_p = utils.valid_password(password_input) valid_e = utils.valid_email(email_input) user_error = '' pass_error = '' email_error = '' verify_error = '' if not valid_u: user_error = 'Invalid username, please try again.' has_error = True if not valid_p: pass_error = 'Invalid password, please try again.' has_error = True if password_input != verify_input: verify_error = 'Passwords do not match, try again.' has_error = True if not valid_e and email_input != '': email_error = 'Invalid email, please try again.' has_error = True if has_error != False: if not globals.main_page: self.render("register.html",error_user = user_error ,error_pass = pass_error,error_verify = verify_error,error_email = email_error,username = user_input,email = email_input) else: self.render("register_main.html",error_user = user_error ,error_pass = pass_error,error_verify = verify_error,error_email = email_error,username = user_input,email = email_input) else: hash_pass = utils.make_pw_hash(user_input,password_input) user_input = str(user_input) user_taken = False email_taken = False data = db.GqlQuery("select * from Users order by user_name") for entry in data: user = entry.user_name email= entry.user_email if user == user_input: user_taken = True if email == email_input and email != '': email_taken = True if user_taken or email_taken: user_error = 'Sorry, the username you selected is already taken' email_error= 'Sorry, this email is already registered' if user_taken and email_taken: if not globals.main_page: self.render('register.html', error_user = user_error, error_email = email_error) else: self.render('register_main.html', error_user = user_error, error_email = email_error) if user_taken: if not globals.main_page: self.render('register.html', error_user = user_error, email = email_input) else: self.render('register_main.html', error_user = user_error, email = email_input) else: if not globals.main_page: self.render('register.html', error_email = email_error, username = user_input) else: self.render('register_main.html', error_email = email_error, username = user_input) else: new = Users(user_name = user_input, user_pass = hash_pass, user_email = email_input) new.put() self.response.headers.add_header('Set-Cookie', 'user_id=%s|%s; Path=/' % (new.key().id(),hash_pass)) if globals.main_page: self.redirect('/homework') else: self.redirect('/wiki/')
def initialize(self, *a, **kw): """initialize the variables across the board""" webapp2.RequestHandler.initialize(self, *a, **kw) uid = self.read_secure_cookie("user_id") self.user_cookie = uid and Users.get_id(int(uid))
def requesthandler(self): guid = self.request.get('guid') cl = self.request.get('cl') comment = clean(self.request.get('comment')) if len(cl) < 1 and len(comment) > 4: cl = TestLanguage.language(text=comment) remote_addr = self.request.remote_addr ip = self.request.get('ip') if len(ip) > 0: remote_addr = ip username = self.request.get('username') pw = self.request.get('pw') session='' location = geo.get(remote_addr) if type(location) is dict: try: city = location['city'] state= location['state'] country= location['country'] except: city = '' state = '' country = '' try: latitude=location['latitude'] longitude=location['longitude'] except: latitude = None longitude = None if len(comment) > 5 and len(guid) > 7: emptyform=False else: emptyform=True if not emptyform: spamchecked = False akismetkey = Settings.get('akismet') root_url = Settings.get('root_url') if len(root_url) > 0 and string.count(root_url, 'http://') < 1: root_url = 'http://' + root_url a = Akismet() a.setAPIKey(akismetkey, blog_url = root_url) if a.verify_key(): data = dict() data['user_ip']=remote_addr data['user_agent']=self.request.headers['User-Agent'] if a.comment_check(comment, data): spam=True else: spam=False spamchecked=True else: spam=False spamchecked=False result = False if len(username) > 0: session = Users.auth(username=username, pw=pw, session='') if len(session) < 8: username='' if not spam: tdb = db.Query(Translation) tdb.filter('guid = ', guid) item = tdb.get() if item is not None: md5hash = item.md5hash sl = item.sl tl = item.tl st = item.st tt = item.tt domain = item.domain url = item.url professional = item.professional author = item.username cdb = db.Query(Comment) cdb.filter('guid = ', guid) cdb.filter('remote_addr = ', remote_addr) item = cdb.get() if item is None: item = Comment() item.guid = guid item.md5hash = md5hash item.tl = tl item.cl = cl item.comment = comment item.username = username item.spamchecked = spamchecked item.spam = spam item.remote_addr = remote_addr timestamp = datetime.datetime.now() item.minute = timestamp.minute item.hour = timestamp.hour item.day = timestamp.day item.month = timestamp.month item.year = timestamp.year item.domain = domain item.url = url item.city = city item.state = state item.country = country try: item.latitude = latitude item.longitude = longitude except: pass item.put() if professional and len(author) > 0: LSP.comment(guid, comment, lsp=author, username=username, remote_addr=remote_addr) result = True self.response.headers['Content-Type']='text/plain' if result: self.response.out.write('ok') else: self.error(500) self.response.out.write('error') else: tdb = db.Query(Translation) tdb.order('-date') item = tdb.get() if item is not None: guid = item.guid else: guid = '' t = '<table><form action=/comments/submit method=post accept-charset=utf-8>' t = t + '<tr><td>GUID of Translation (guid)</td><td><input type=text name=guid value="' + guid + '"></td></tr>' t = t + '<tr><td>Comment (comment)</td<td><input type=text name=comment></td></tr>' t = t + '<tr><td>Username (username, optional)</td><td><input type=text name=username></td></tr>' t = t + '<tr><td>Password (pw, optional)</td><td><input type=text name=pw></td></tr>' t = t + '<tr><td colspan=2><input type=submit value=SUBMIT></td></tr></table></form>' www.serve(self,t,sidebar=self.__doc__, title = '/comments/submit')
def rename(self, session): users = Users(name=self.name, id=self.userId) users.update() session['user'] = self.name return {'code': 200}