def __enter__(self) -> None: self.__configure(self.__port) self.__migrate() self.__tarantool_subprocess.stdin.close() sleep(1) User.set_host(self.__host) User.set_port(self.__port)
def loadUser(data, image): """Loads a user for the current session. Attempts to retrieve a user based on his email address. If a record cannot be found, create a new user with the data that is returned from the oAuth provider. If a user name cannot be found, the user is assigned a default user name consisting of the word user and a date & time string. Args: data : a list of user values returned by the oAuth provider. image : an image url for the current user. Return: A User object. """ user = getOne(User, 'email', data['email']) if not user: if data['name'] == '': data['name'] = 'User %s' % datetime.datetime.now() user = User(email=data['email'], name=data['name'], image=image) User.save(user) return user
def post(self): has_error = False self.username = self.request.get('username') self.password = self.request.get('password') self.confirm = self.request.get('confirm') self.email = self.request.get('email') params = dict(username = self.username, email = self.email) if not valid_name(self.username): params['error_username'] = "******" has_error = True if not valid_pass(self.password): params['error_password'] = '******' has_error = True elif self.password != self.confirm: params['error_confirm'] = "Passwords don't match" has_error = True if has_error: self.render('signup.html', **params) else: u = User.by_name(self.username) if u: message = "Username already exists" self.render('signup.html', error_username = message) else: user = User.register(self.username, self.password, self.email) user.put() self.login(user) self.redirect('/')
def get_user_info(form): users = UserModel() sessions = SessionModel() if not assert_keys_in_form_exist(form, ['sessionID']): return msg.error_msg("Invalid Session ID.") session_id = form['sessionID'] session = sessions.get_session(session_id) if len(session) == 0: return msg.error_msg("Unable to find the session.") (sessionid, uid, start_time, end_time) = session[0].values() user = users.get_user(uid=uid) if len(user) == 0: return msg.error_msg("Unable to find the user") (uid, name, email, phone, password, major, degree, enable) = user[0].values() return msg.success_msg({ "uid": uid, "name": name, "email": email, "phone": phone, "major": major, "degree": degree })
def add_session(form): if not assert_keys_in_form_exist(form, ['email', 'password']): return msg.error_msg("Please check the inputs.") sessions = SessionModel() users = UserModel() (email, password) = (form['email'], form['password']) users_founded = users.get_user(email=email, password=encrypt(password), enable=True) if users_founded == None: return msg.error_msg("Failed to validate user information.") if len(users_founded) == 0: return msg.error_msg("Invalid email address or password.") uid = users_founded[0]['user_id'] new_session_id = sessions.create_session_id() start_time = datetime.utcnow() res = sessions.start_session(new_session_id, uid, start_time) if res == None: return msg.error_msg("Failed to start a new session.") return msg.success_msg({ "sessionID": new_session_id, "uid": uid, "startTime": str(start_time), "userName": users_founded[0]['name'] })
def test_db_object(self): ''' Makes sure that __eq__ method overide works ''' user1 = User() user2 = User() self.assertEqual(user1, user2)
def make_user(login, nickname): try: return User.objects(test_login=login).get() except User.DoesNotExist: u = User(test_login=login, nickname=nickname) u.save() return u
def callback(): # Get authorization code Google sent back to you code = request.args.get("code") # Find out what URL to hit to get tokens that allow you to ask for # things on behalf of a user google_provider_cfg = get_google_provider_cfg() token_endpoint = google_provider_cfg["token_endpoint"] # Prepare and send a request to get tokens! Yay tokens! token_url, headers, body = client.prepare_token_request( token_endpoint, authorization_response=request.url, redirect_url=request.base_url, code=code) token_response = requests.post( token_url, headers=headers, data=body, auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET), ) # Parse the tokens! client.parse_request_body_response(json.dumps(token_response.json())) # Now that you have tokens (yay) let's find and hit the URL # from Google that gives you the user's profile information, # including their Google profile image and email userinfo_endpoint = google_provider_cfg["userinfo_endpoint"] uri, headers, body = client.add_token(userinfo_endpoint) userinfo_response = requests.get(uri, headers=headers, data=body) # You want to make sure their email is verified. # The user authenticated with Google, authorized your # app, and now you've verified their email through Google! if userinfo_response.json().get("email_verified"): unique_id = userinfo_response.json()["sub"] users_email = userinfo_response.json()["email"] picture = userinfo_response.json()["picture"] users_name = userinfo_response.json()["given_name"] else: return "User email not available or not verified by Google.", 400 # Create a user in your db with the information provided # by Google user = User(id_=unique_id, name=users_name, email=users_email, profile_pic=picture, address="") # Doesn't exist? Add it to the database. if not User.get(unique_id): User.create(unique_id, users_name, users_email, picture, "") # Begin user session by logging the user in login_user(user) # Send user back to homepage return redirect("/dashboard/users/" + unique_id)
def check_mail(request): user_db = User() mail = request.params['mail'] user = user_db.get_user_by_mail(mail) if user: return {'status': 'nok'} else: return {'status': 'ok'}
def check_user(request): user_db = User() name = request.params['name'] user = user_db.get_user_by_name(name) if user: return {'status': 'nok'} else: return {'status': 'ok'}
def test_user_create(self): user = User() result = User.create(username='******', password='******', description='Hi my name is James', location='Sydney', birthdate='DD/MM/YYYY', image='/file/img.png') self.assertEqual(user, result)
def get_or_create_user(claims): user_email = claims.get('email') user = User.load(db, user_email) if user is None: user_id = claims['sub'] user_name = claims.get('name') user = User(id=user_id, email=user_email, name=user_name) user.save(db) return user
def register(request): name = request.params['name'] mail = request.params['mail'] password = request.params['password'] print password m = hashlib.md5() m.update(password) passwordStr = m.hexdigest() user_db = User() user_db.add_user(name, passwordStr, mail, ['user']) return {'status': 'ok'}
def add_user(form): users = UserModel() if not assert_keys_in_form_exist( form, ['name', 'email', 'phone', 'password', 'major', 'degree']): return msg.error_msg("Please check your requests.") name = form['name'] email = form['email'] phone = form['phone'] password = form['password'] major = form['major'] degree = form['degree'] if name.strip() == "": return msg.error_msg("Username cannot be empty.") if password.strip() == "": return msg.error_msg("Password cannot be empty.") if len(password) < 6: return msg.error_msg("Password cannot less than 6 character.") if len(name) > 255: return msg.error_msg("Username cannot exceed 255 characters.") if len(password) > 255: return msg.error_msg("Password cannot exceed 255 characters.") findUser = users.get_user(email=email, enable=True) if findUser is None: return msg.error_msg("Failed to find user.") print('findUser', findUser) print(len(findUser)) if len(findUser) != 0: return msg.error_msg("User already exists. (Email already in use)") args = { "Name": name, "Email": email, "Phone": phone, "Password": encrypt(password), "Major": major, "Degree": degree, "Enable": True } res = users.add_user(args) if res is None: return msg.error_msg("Failed to add user.") return msg.success_msg({"msg": "User added successfully."})
def test_update_courses(self): u = User(name="unknown", email="*****@*****.**", status="inactive") _id = u.save() u = User.get(_id) self.assertFalse(u.courses, "Courses count") courses = [Course.get(1), Course.get(2), Course.get(3)] u.courses = courses u.update() u = User.get(_id) self.assertTrue(u.courses, "Courses count") self.assertEqual(u.courses, courses, "Update courses") u.delete()
def migrate(cls, host: str, port: int, user: str = 'admin', password: str = 'admin') -> None: admin = tarantool.connect(host, port, user, password) migrations_dir = cls.__get_migrations_dir() for file in sorted(os.listdir(migrations_dir)): with open(os.path.join(migrations_dir, file)) as f: admin.eval(f.read().strip()) User.set_host(host) User.set_port(port)
def update_user(form): users = UserModel() sessions = SessionModel() if not assert_keys_in_form_exist(form, [ 'sessionID', 'name', 'email', 'phone', 'newPassword', 'major', 'degree' ]): return msg.error_msg("Please check your requests.") name = form['name'] session_id = form['sessionID'] email = form['email'] phone = form['phone'] new_password = form['newPassword'] major = form['major'] degree = form['degree'] if new_password.strip() == "": return msg.error_msg("Password cannot be empty.") if len(name) > 255: return msg.error_msg("Username cannot exceed 255 characters.") if len(new_password) > 255: return msg.error_msg("Password cannot exceed 255 characters.") # Get User according to sessionID session = sessions.get_session(session_id) if len(session) == 0: return msg.error_msg("Unable to find the session.") (sessionid, uid, start_time, end_time) = session[0].values() if end_time is not None: return msg.error_msg("This session already canceled.") args = { "Name": name, "Email": email, "Phone": phone, "Password": encrypt(new_password), "Major": major, "Degree": degree, "UID": uid } ret = users.update_user(args) if ret is None: return msg.error_msg("Failed to update user profile.") return msg.success_msg({})
class UserInfo(object): def __init__(self): router = Router(META_SERVERS, sync=False) self._user = User(router) self._marker = Marker() def add(self, user, password, uid): ret = self._user.get(user, 'uid') if not ret: self._user.put(user, password=password, uid=uid) self._marker.mark(uid, DOMAIN_USR, AREA) return True def get_password(self, user): return self._user.get(user, 'password')
def on_post(self, request, response): user = User() response.content_type = 'application/json' if self.validate_json(request, validate_user_schema.validate_activate_user): user_json = self.result_json['user'] email = user_json['email'] payload = user_json['payload'] try: user.activate_user(payload=payload, email=email) response.data = ActivatedUserResponder.respond(user.activated_user_for_json()) response.status = falcon.HTTP_201 #created except BadSignature as e: response.status = falcon.HTTP_400 else: response.status = falcon.HTTP_400
def authorize_user(self, request): x_auth_key = request.headers['X-AUTH-KEY'] serializer = URLSafeSerializer(secret_key=settings.TOKEN_SECRET_KEY) try: user = User() user.id = serializer.loads(x_auth_key) self.is_authorized_user = user.get_user() self.user_id = user.id return self.is_authorized_user except BadSignature: return False except BadPayload: return False except: print sys.exc_info()[0] return False
def get_all_users(request): user_db = User() users = user_db.get_all_users() data = [] for user in users: print user['name'] data.append([user['name'], user['password'], ','.join(user['roles'])]) print data str = json.dumps(data, encoding="UTF-8", ensure_ascii=False) print str return json.dumps({ 'status': 'ok', 'data': str }, encoding="UTF-8", ensure_ascii=False)
def login(conn, info, repo): username, password = info.split(" ") user = User(username, password) # 构造响应 resp_dict = { "command": 5, "from": "server", "to": username } resp_info = json.dumps(resp_dict) try: repo.login(user) conn_list.append(conn) if username in user_dict.values(): raise ValueError("该用户已登陆") user_dict[conn] = username resp_content = "success" put_block(conn, resp_content, resp_info) return True except ValueError as e: (resp_content, ) = e.args put_block(conn, resp_content, resp_info) return False
def update_referral(): content = request.get_json() #get by referrer_token referral_3bot_name = content['referral_3bot_name'] user_id = content['user_id'] user = User.get_by_id(user_id) if user is None: return responses.errorObj(404, "User not found") if is_3bot_user(content): return responses.errorObj(404, "3bot login data invalid") #if users exists, add referral => TODO check POI if ReferralsDoneUser.check_already_referred_3bot_name(referral_3bot_name): return responses.successObj( 200, referral_3bot_name ) # the user installed 3bot connect so this is ok referral_done = ReferralsDoneUser( 0, user_id, referral_3bot_name ) #if jan invites piet, user_id is jan's; email is piet's referral_done.add() return responses.successObj(200, referral_3bot_name)
def api_login(): id = request.values.get('id') if "id" in request.form else None pw = request.values.get('pw') if "pw" in request.form else None logger.info("id : "+id) cursor = db.get_conn().cursor() # cursor 객체를 얻는다. cursor.callproc('get_user_by_id', (id,)) #argument 1개일 때도 ,하나 붙여줘야 제대로 인식함. r = cursor.fetchall() cursor.close() logger.info( "login user info : " + str(r)) if r: #id 존재 logger.info("pw 체크) DB에 있는 hashedpw: %s, 입력한pw:%s, check_password_hash():%s" % (r[0][4], pw, check_password_hash(str(r[0][4]), pw))) #if r[0][4] == pw: if check_password_hash(r[0][4], pw): # 아이디와 비밀번호가 일치하면 로그인 처리 # 직접 정의한 'User'클래스의 객체를 인자로 넘겨준다. login_user(User(id, name=r[0][2], auth=True)) flash("로그인 되었습니다.") return redirect(url_for('main_view.index')) else: flash("아이디 또는 비밀번호를 확인하세요.") return redirect(url_for('auth_view.login')) else: flash("아이디 또는 비밀번호를 확인하세요.") return redirect(url_for('auth_view.login'))
def init_db(): db.create_tables() session = db.create_session() with open('db_data.json') as f: data = json.load(f) for user in data['user']: u = User(username=user['username'], password=user['password'], name=user['name']) session.add(u) for tag in data['tag']: t = Tag(name=tag['name']) session.add(t) for product in data['product']: p = Product(name=product['name']) session.add(p) session.commit() i = Issue(description="Updater doesn't work on linux", reporter_id=1, product_id=1) session = db.create_session() session.add(i) session.commit() s = Screenshot(issue_id=1, path_to_screenshot=r'db_diagram.png') session = db.create_session() session.add(s) session.commit() c = Comment(issue_id=1, user_id=2, message="Are you sure? I ran it last week on a CentOS and it seemed to be working just fine") session = db.create_session() session.add(c) session.commit()
def get(self, request, *args, **kwargs): pk = kwargs.get('pk') if pk: obj = User.get(id=pk) if obj: obj.delete() return redirect(self.success_url)
def get(self): #assumes: id doesn't change for user id = str(request.headers.get('Authorization')) users = read_parquet("/app/users.parquet") if id not in users.id.values: newuser = { "id": id, "recipes_viewed": empty(0), "recipes_made": empty(0), "recipes_liked": empty(0), "ingredients_owned": empty(0), "weights": empty(0) } #add user to data users = users.append(newuser, ignore_index=True) users.to_parquet("/app/users.parquet") #recommend something u = users.query("id == @id") user = User(id, u["recipes_viewed"].to_list(), u["recipes_made"].to_list(), u["recipes_liked"].to_list(), u["ingredients_owned"].to_list(), u["weights"].to_list()) recipes = read_parquet("/app/recipes.parquet") results = get_recommendations(user, recipes, 30) formatted_results = [{ **lookup.query("id == @i").to_dict('records')[0], 'confidence': float(confidence) } for i, confidence in results] return jsonify(formatted_results)
def form_valid(self, form, **kwargs): user = User() user.name = form.cleaned_data['name'] user.email = form.cleaned_data['email'] user.phone = form.cleaned_data['phone'] user.mobile_phone = form.cleaned_data['mobile_phone'] user.status = form.cleaned_data['status'] user.save() context = self.get_context_data(**kwargs) messages.add_message(self.request, messages.INFO, 'User created successfully') return render(self.request, self.get_template_names(), context=context)
def test_squad_members_get_by_status(self): squad_members = [ User.create(username='******', password='******', description='Hi my name is James', location='Sydney', birthdate='DD/MM/YYYY', image='/file/img.png'), User.create(username='******', password='******', description='Hi my name is Tim', location='Syd', birthdate='DD/MM/YYYY', image='/file/imag.png') ] result = SquadMembers.get_by_status('Pending...', 0) self.assertListEqual(squad_members, result)
def get_referrals_done(user_referrer_token): user = User.get_by_referrer_token(user_referrer_token) if user is None: return responses.errorObj(404, "User not found") referrals = ReferralsDoneUser.get(user.id) return responses.successObj(200, json.dumps(referrals, cls=ObjectEncoder))
def __init__(self, auth_header): self.auth_header = auth_header s = URLSafeSerializer(secret_key=settings.TOKEN_SECRET_KEY) try: self.auth_key = s.loads(self.auth_header['X-AUTH-KEY']) # self.user_key = self.auth_header['X-AUTH-USER'] user = User() user.id = self.auth_key user.get_user() self.is_authorized_user = user.id == self.auth_key # users auth key is valid except BadSignature: self.is_authorized_user = False except BadPayload: self.is_authorized_user = False except: print sys.exc_info()[0] self.is_authorized_user = False
def __init__(self, payload, responder, db): super().__init__() self.payload = payload self.responder = responder self.db = db self.user = User(db) self.shop = Shop(db) self.page_id = '' self.page_sender_id = '' self.page_recipient_id = '' self.sent_text = '' self.recipient_reaction = None self.latitude = 0.0 self.longitude = 0.0 self.recipient_id = '' self.quick_reply_payload = ''
def verify(user_verify_token): user = User.get_by_verify_token(user_verify_token) if user is None: return responses.errorObj(404, "User not found") user.verified = True user.update() return responses.successObj(200, user)
def login_action(): email = request.values["email"] if "email" in request.form else "" pw = request.values["pwd"] if "pwd" in request.form else "" notice_no = request.values[ "notice_no"] if "notice_no" in request.values else '' rmb = request.values["rmb"] if "rmb" in request.form else "" print "rmb:" + str(rmb) cursor = dao.get_conn().cursor() cursor.execute("select * from recruit_user where user_email like '%s'" % (email)) result = cursor.fetchone() cursor.close() logger.info("login_action, check email : " + str(result)) try: if result: if check_password_hash(result[3], pw): login_user( User(email, name=result[2].decode('utf-8'), auth=True, no=result[0])) if notice_no != '': return redirect( url_for('notice_view.notice_post', p_no=notice_no)) else: response = make_response( redirect(url_for("main_view.index"))) if rmb == 'on': from aes_cipher import encrypt expire_date = datetime.now() + timedelta(days=90) enc_email = encrypt(current_app.config['SECRET_KEY'], email) response.set_cookie('rmber', value=enc_email, expires=expire_date) else: response.set_cookie('rmber', expires=0) flash("로그인 되었습니다.") return response else: flash("아이디 또는 비밀번호가 일치하지 않습니다.") return redirect(url_for("auth_view.login_form")) else: flash("아이디 또는 비밀번호가 일치하지 않습니다.") return redirect(url_for("auth_view.login_form")) except Exception as e: logger.info(str(e)) raise e
def login(request): name = request.params['name'] password = request.params['password'] user_db = User() user = user_db.get_user(name) if user is None: return {'status': 'nok', 'data': '该用户不存在!'} m = hashlib.md5() m.update(password) passwordStr = m.hexdigest() print passwordStr if passwordStr == user['password']: print 'before session' request.session['name'] = name roles = user['roles'] print 'ok' return {'status': 'ok', 'roles': roles} else: return {'status': 'nok', 'data': '密码错误!'}
def post(self): has_error = False self.username = self.request.get("username") self.password = self.request.get("password") self.confirm = self.request.get("verify") self.email = self.request.get("email") params = dict(username = self.username, email = self.email) if not valid_name(self.username): params["error_username"]="******" has_error = True if not valid_pass(self.password): params['error_password']='******' has_error = True if self.email !="": if not valid_email(self.email): params["error_email"] = "Invalid email" has_error = True if self.password != self.confirm: params["error_confirm"] = "Password does not match" has_error = True if has_error: self.render("signup.html", **params) else: u = User.by_name(self.username) if u: error = "Username already exists! Please choose another username" self.render("signup.html",error_username=error) else: user = User.register(self.username, self.password, self.email) user.put() self.login(user) self.redirect("/")
def post(self): username = self.request.get('username') password = self.request.get('password') valid_user = User.login(username, password) if valid_user: self.login(valid_user) self.redirect('/') else: msg = 'Incorrect login information' self.render('login.html', error_username = msg)
def initialize(self, *a, **kw): webapp2.RequestHandler.initialize(self, *a, **kw) user = self.check_cookie('user_id') self.user = user and User.by_id(int(user))
def get_group_user(user_id): user = User() user.id = user_id user.get_user() return user
def main(dry_run=False): if dry_run: print '<< dry run >>' since_id = Tweet.max_id() #since_id -= 10000000000000 * 3 if since_id: print since_id # 536342886862688258 # if testmode: since_id -= 10000000000000 * testmag statuses = twitter.api.home_timeline(since_id) else: statuses = twitter.api.home_timeline() statuses.reverse() is_harahe = False for status in statuses: if co33k.is_to_ignore(status): # print ' <', status.user.screen_name, ':', status.text continue if dry_run: # print user # print tweet print print '%s (%s, %d) <%s> %s:' % ( status.user.name, status.user.screen_name, status.user.id, status.id, status.created_at ) print ' %s' % (status.text,) user = User( (status.user.id, status.user.name, status.user.screen_name, status.user.location, status.user.description, status.user.profile_image_url, status.user.protected, False) ) # is_spam if not dry_run: user.save() tweet = Tweet( (status.id, util.datetime_to_unixtime(status.created_at), status.text, status.in_reply_to_status_id, status.in_reply_to_user_id, status.user.id, None, None, False) ) # is_mine if not dry_run: tweet.save() status_text = status.text status_text = status_text.replace('&', '&') status_text = status_text.replace('<', '<') status_text = status_text.replace('&qt;', '>') status_text = status_text.replace('"', '"') if u'はらへ' in status_text and u'_rin' in status.user.screen_name: is_harahe = True responses = co33k.responses_for_status(user, status, dry_run=dry_run) repondu = False if responses: responses.sort(reverse=True) for message, rate in responses: rate *= 3 print ' → %g%%) %s' % (rate, message.encode('utf-8')) #status.id if not repondu and util.p(rate): say(message, in_reply_to_status_id=status.id, dry_run=dry_run) repondu = True if is_harahe: say(u'はらへ', dry_run=dry_run)
def update_user(self, user_result_json, user_id): user = User() user.id = user_id user.set_user_properties(user_result_json) user.update_user()
def get_user_by_email(email): user = User() user.email = email user.get_user() return user
def __init__(self): router = Router(META_SERVERS, sync=False) self._user = User(router) self._marker = Marker()
interest = Interest() interest.name = 'Internet Startup' interest.description = 'How to build an Internet business' interest.create_interest() startup_id = interest.id interest = Interest() interest.name = 'Python Programming' interest.description = 'Programming with the Python language' interest.create_interest() python_id = interest.id #USERS #Marnee, Julian, Chris, Dan, Liz, Frank marnee = User() marnee.call_sign = 'AWESOME' marnee.email = '*****@*****.**' marnee.name = 'Marnee' marnee.is_admin = True marnee.about = 'This is about me.' marnee.mission_statement = 'This is my mission statement.' marnee.create_user() julian = User() julian.call_sign = 'RADICAL' julian.email = '*****@*****.**' julian.name = 'Julian' julian.is_admin = False julian.about = 'This is about me.' julian.mission_statement = 'This is my mission statement.'
def register_user(self, user_result_json): register = User() email = user_result_json['email'] register.register_user(email=email)
def get_user_by_id(user_id): user = User() user.id = user_id user.get_user() return user