def enroll(rein): Base.metadata.create_all(rein.engine) user = rein.user mediator_extras = '' if user.will_mediate: mediator_extras = "\nMediator public key: %s\nMediator fee: %s%%" % \ (pubkey(user.dkey), user.mediator_fee) enrollment = "Rein User Enrollment\nUser: %s\nContact: %s\nMaster signing address: %s" \ "\nDelegate signing address: %s\nWilling to mediate: %s%s" % \ (user.name, user.contact, user.maddr, user.daddr, user.will_mediate, mediator_extras) if rein.testnet: enrollment += '\nTestnet: True' f = open(rein.enroll_filename, 'w') f.write(enrollment) f.close() click.echo("%s\n" % enrollment) done = False while not done: filename = click.prompt(hilight("File containing signed statement", True, True), type=str, default=rein.sig_enroll_filename) if os.path.isfile(filename): done = True else: click.echo("File not found. Please check the file name and location and try again.") f = open(filename, 'r') signed = f.read() res = validate_enrollment(signed) if res: User.set_enrolled(rein, user) # insert signed document into documents table as type 'enrollment' document = Document(rein, 'enrollment', signed, sig_verified=True, testnet=rein.testnet) rein.session.add(document) rein.session.commit() return res
def set_seen_by(self, user=None): if user: User.set_last_media(user, self) if user and not user.id in self.seen: self.seen.append(user.id) self.put() return None
def login(): msg = None remember = False if request.method == "POST" and "username" in request.form: username = request.form["username"] password = request.form["password"] if "remember" in request.form: remember = True print "remember %s" % remember user = User(username) if getattr(app, 'fakelogin', False): sigel = "NONE" else: sigel = user.authorize(password, app.config) if sigel == None: sigel = "" msg = u"Kunde inte logga in. Kontrollera användarnamn och lösenord." else: user.sigel = sigel session['sigel'] = sigel login_user(user, remember) session.permanent = remember print "User logged in" print "User %s logged in with sigel %s" % (user.username, user.sigel) return redirect("/") return render_template("partials/login.html", msg = msg, remember = remember)
def create_user(uid): user = User() user.set('uid', uid) if not create_user_dir(user): return None add_user(user) return user
def test_login_fails_and_returns_false_with_invalid_username_or_password(self): user1 = User("br", "admin") user2 = User("tst", "wrongpass") file_input = ["bkr,admin,brennon rogers", "tst,admin2,test entry"] portal_db_reader = PortalDBReader(file_input) self.assertFalse(user1.login(portal_db_reader)) self.assertFalse(user2.login(portal_db_reader))
def _sync_children(self): from list import List from preferences import Preferences Preferences.sync() List.sync() User.sync()
def decorated_function(*a,**kw): u = User() u.name = session.get('name', None) u = get_user(u) if not u or not u.isbaron: return render_template("not_baron.html", user=get_user_by_name(session.get('name'))), 401 return fn(*a, **kw)
def removeUserFollowing(user_id_follower, user_id_following): user_follower = User.get_by_id(user_id_follower) user_following = User.get_by_id(user_id_following) follow_query = Follow.all() follow_query.filter("user_follower =", user_follower) follow_query.filter("user_following =", user_following) db.delete(follow_query.get())
def start(session): print("Dividing numbers rounds them to second decimal!") points = 0 username = input("Enter your playername>") user = User(name=username, score=points) print("Welcome {}! Let the game begin!".format(username)) last_answer_correct = True while(last_answer_correct): expression = Expression.generate_expression() print("What is the answer to {} {} {}".format( expression[0], expression[2], expression[1])) answer = input("?>") if(float(answer) == expression[3]): print("?>Correct!") points += 1 else: score = calculate_score(points) print("Incorrect! Ending game. You score is: {}".format(score)) last_answer_correct = False if user.score < score: user.score = score session.query(User).filter(User.name==username).update({"score": score}) if(session.query(exists().where(User.name == username)).scalar() == 0): session.add(user) session.commit()
def login(): error = None if 'name' in session: #check if usr is already logged in return redirect('/') if request.method == 'POST': u = User() u.name = request.form['username'].lower() u = get_user(u) if u is None: error = 'User does not exist!' return render_template('login.html', error=error, user=get_user_by_name(session.get('name'))) #if u.password != request.form['password']: # bcrypt.checkpy(plaintxt, hash) if not bcrypt.checkpw(request.form['password'], u.password): error = 'Wrong password!' return render_template('login.html', error=error, user=get_user_by_name(session.get('name'))) session['name'] = u.name return redirect('/') return render_template('login.html', error=error, user=get_user_by_name(session.get('name')))
def post(self): try: body = json.loads(self.request.body) name = body['name'] pw = body['pw'] target_url = body.get('next') except (KeyError, ValueError, TypeError) as e: self.application.log.info('User creation request malformed, error={}, url={}, body={}'.format(e, self.request.uri, self.request.body)) self.send_error(httplib.BAD_REQUEST) return exists = yield User.exists(name) if exists: self.send_error(httplib.CONFLICT) return user = User(name, pw) yield user.save() self.set_current_user(user.guid) if target_url: self.redirect(target_url) else: self.set_header('Location', self.reverse_url(UserMaintenanceHandler.__name__, user.guid)) self.write(self.application.user_representation(user)) self.set_status(httplib.CREATED)
def get(self): name = self.request.get('name') email = self.request.get('post') user = User(name=name, email=email) user.put() message = '<ul><li>%s, %s</li></ul>' % (name, email) self.response.write(message)
def user_reg(email, password, sex, name): from afconfig import af_conf email = email.lower() if User.is_exist({'email':email}): return 6 #'existed user' if af_conf['needinvite']: if not Invitation.is_exist({'email':email}): return 7 #'not invited' password = encrypt(password) token = unicode(random_string(20), 'utf-8') usr = User(attrs={'email':email}) doc = { 'sex' : sex, 'name' : name, 'password' : password, 'token' : token, 'domain' : usr.uid, 'account_status' : 'unverified', } usr.set_propertys(**doc) m_status = email_verification(usr) if m_status is False: logging.error('+'*30) logging.error('Email send Failed') logging.error('%s %s %s' % (email, token, name)) logging.error('+'*30) return 8 #'mail error' return 0
def get_user_info(save_file, uid_list, start): f = open(save_file, 'a') f2 = open('log', 'a') find = (start == -1) i = 0 while i < len(uid_list): if find: print 'processing uid#%s' % uid_list[i] url = 'http://mac.pcbeta.com/space-uid-%s.html' % uid_list[i] user = User() html = http_get(url) if html is None: time.sleep(10) continue user.parse(html) if user.is_valid(): f.write(str(user) + '\n') print 'write to file' else: login() i -= 1 else: if uid_list[i] == str(start): find = True i += 1 f.close() f2.close()
def get(self): username = self.request.get("user") password = self.request.get("password") self.response.headers['Content-Type'] = 'application/json; charset=utf-8' if not username or not password: # some fields were missing in the request self.response.write(json_error('invalid', '')) else: # check if username exists in db query_user = User.query(User.username == username).fetch() if query_user: # check if password is correct query = User.query(ndb.AND(User.username == username, User.pswd == password)).fetch() if query: # generate 64 char session cookie and send it back cookie = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(64)) session = Session(cookie = cookie, user = username) session.put() self.response.write(login_response('ok', cookie)) else: # password was incorrect self.response.write(json_error('failure', 'password')) else: # user didn't exist self.response.write(json_error('failure', 'user'))
def user_related_resources(id, related_collection_name, related_resource): response = None if request.method == 'GET': response = User.get_related_resources(request.args, id, related_collection_name, related_resource) if request.method == 'DELETE': response = User.set_related_resources_inactive(id, related_collection_name, related_resource) return response
def _sync_user_credentials(self, data, addr): """ Received user credentials and send its uuid :param data: data send by client :param addr: client address """ self._logger.debug("User trying to login from %s", addr[0]) self._logger.debug("Checking credentials...") # format user information received data.replace("\n", "") user = User() user._email = data.split(":")[0] user._password = data.split(":")[1] # search user user_found = self._find_user(user) if user_found != None: # send the generated uuid to client self._socket.sendto(user_found._uuid, (addr[0], addr[1])) self._logger.debug("User found") self._logger.debug("User (email: %s) is logged", user_found._email) self._logger.debug("UUID: \"%s\" sent to %s", user_found._uuid, addr[0]) else: # send empty string to client self._socket.sendto("none", (addr[0], addr[1])) self._logger.debug("none string sent to %s", addr[0]) self._logger.debug("User not found") self._logger.debug("User (email: %s) failed to login", user._email)
def dispatch(cmd): # get module if ('m' in cmd): module = cmd['m'] else: return response(101) # get action if ('a' in cmd): action = cmd['a'] else: return response(102) # get param if ('p' in cmd): param = cmd['p'] else: param = {} if module == 'user': moduleObj = User() elif module == 'sys': moduleObj = System() else: return response(100, {'error':'unknown module!'}) code, result = moduleObj.handle(action, param) return response(code, result)
def user_relationships(id, related_collection_name, related_resource): response = None if request.method == 'GET': response = User.get_relationship(request.args, id, related_collection_name, related_resource) elif request.method == 'DELETE': response = User.delete_relationship(id, related_collection_name, related_resource) return response
def authorize(): client_id = int(request.form.get("client_id")) login = request.form.get("login") password = request.form.get("password") state = request.form.get("state", None) user_db = User.db() if not user_db(login=login): return redirect( db.client[client_id]["redirect_uri"] + "?error=access_denied" + ("" if state is None else "&state=" + state), code=302, ) if User.db()(login=login)[0]["password"] != sha256(password.encode("UTF-8")).hexdigest(): print(sha256(password.encode("UTF-8")).hexdigest()) print(password) return redirect( db.client[client_id]["redirect_uri"] + "?error=access_denied" + ("" if state is None else "&state=" + state), code=302, ) code = sha256(str(uuid4()).encode("UTF-8")).hexdigest() db.authorization_code.insert( user_id=User.db()(login=login)[0]["__id__"], code=code, expire_time=datetime.now() + timedelta(minutes=10) ) db.authorization_code.commit() return redirect( db.client[client_id]["redirect_uri"] + "?code=" + code + ("" if state is None else "&state=" + state), code=302 )
def get(self): http = decorator.http() service = build("plus", "v1", http=http) # Call the service using the authorized Http object. request = service.people().get(userId="me") response = request.execute(http=http) user_id=response['id'] name=response['displayName'] image=response['image']['url'] self.render("home.html") try: # Get the db.User that represents the user on whose behalf the # consumer is making this request. #user = oauth.get_current_user("https://www.googleapis.com/auth/userinfo.email") if response: greeting = ('Welcome, %s! (<a href="%s">sign out</a>)' % (name, users.create_logout_url('/'))) entity = User.by_user_id(user_id) self.write(greeting) if entity is None: entity = User(user_id=user_id, picture=image, name=name) entity.put() template_values = {"user":entity, "greeting":greeting} #self.redirect('/profile') else: self.render("home.html") except oauth.OAuthRequestError, e: self.write("Error")
def markItemAsRead(itemId): # If user isn't there in session, throw error if 'user' not in session: return "not logged in" # Pick up the email email = session['user'] # Get a user object user = User(email) # Mark that item as read markID = user.mark_item(itemId) # Assume that it has been marked to true markStatus = True if markID == -1: # Until told otherwise markStatus = False # Create a response object responseObj = { "mark_as_read":markStatus } # Make a JSON repsonse and return it response = make_response() response.mimetype="application/json" response.data = json.dumps(responseObj) return response
def monitor(sock, data): u = User.find_user_by_sock(sock) print 'command from:', u.username command = data['command'] room_name = data['destination'] if command == 'users': li = [] for el in User.users: if el.username: li.append([el.username, el.network]) print 'Number users on:', len(li), '---', len(User.users) for el in li: print el if command == 'rooms': r = Room.find_room_by_name(room_name) try: print 'room alias:', r.alias print 'room users_name:', adapter(r.users_name) except: print 'no room' if command == 'message': u = User.find_user_by_name('*****@*****.**', 'dev-socialbase') info = {"type": "chat", "payload": {"command": "test_user", "details": str(u)}} u.connection.write_message(info) print 'B.sended to ', u.username, info
def __init__(self, retention): self.retention = retention for x in range(0, self.initial_amount): new_user = User() new_user.idle = random.random() < retention self.users.append(new_user)
def _login_user(self): """ Ask user login """ # send message to arduino to bling the LED self._send_message_to_arduino("3") self._logger.info("Please enter your email and password to login") user = User() sys.stdout.write("email: ") user._email = sys.stdin.readline() sys.stdout.write("password: "******"Login failed. Please check your internet and/or serial connection and retry") self._login_user() elif user._uuid == "none": self._logger.info("Login failed") self._login_user() elif re.compile("[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}").match(user._uuid): self._save_user_settings(user) self._logger.info("Login successful") # send message to arduino to put off LED self._send_message_to_arduino("4")
def fun_invite_reg(email, pwd, sex, name): tmp = User.is_exist(email=email) if tmp is True: return [1,'邮箱已经被注册!'] AFW_Group = BasicGroup(_id=AFWConfig.afewords_group_id) tmp_email = email.replace(r'.', r'#') if AFW_Group.invitation_lib[tmp_email] is None: return [1, '很抱歉您并未被邀请!'] af_pwd = encrypt(pwd) af_random = random_string(20) token = unicode((af_pwd + af_random), "utf-8") usr = User() usr.set_propertys(**{'email':email, 'sex':sex, 'name':name, 'token':token, 'domain':unicode(usr._id)}) tmp_avatar = usr.avatar tmp_avatar.thumb_name = '/static/avatar/small/afewords-user.jpg' #print 'beta.afewords.com/check?email=', email, '&token=',token mail_ok, mail_info = send_mail_reg(email, token, name) if mail_ok == 1: logging.error('+'*30) logging.error('Email send Failed') logging.error('%s %s %s' % (email, token, name)) logging.error('+'*30) return [1,'验证邮件发送失败!'] else: return [0, '']
def create_initial_testing_data(self): DB.session.add(AccountType(1, u'Cash')) DB.session.add(AccountType(2, u'Credit')) DB.session.commit() account = Account(1, u'Cash', 3, 0) user = User('test_username', 'test_password', []) user.hash_password('test_password') user.accounts = [account] DB.session.add(user) DB.session.commit() DB.session.add(CategoryType(1, u'Income')) DB.session.add(CategoryType(2, u'Spending')) DB.session.add(TransactionType(1, u'Income')) DB.session.add(TransactionType(2, u'Spending')) DB.session.add(TransactionType(3, u'Transfer')) DB.session.commit() DB.session.add(Category(1, u'Sample income category', None, 1)) DB.session.add(Category(1, u'Sample spending category', None, 2)) DB.session.add(Category(1, u'Sample child spending category', 2, 2)) DB.session.add(Currency(1, u'US dollar', 'USD', u'$')) DB.session.add(Currency(2, u'Euro', 'EUR', u'€')) DB.session.add(Currency(3, u'Ukrainian hryvna', 'UAH', u'₴')) DB.session.add(Currency(4, u'British pound', 'GBP', u'£')) DB.session.add(Currency(5, u'Russian ruble', 'RUB', u'₽')) DB.session.commit()
def friend_list_request_handle(con, content_json): obj = {} friend_list = [] num = 0 user = User(content_json["uid"]) friend_list = user.get_friend_list() print "friend_list=", friend_list obj["list"] = [] for i, friend_id in enumerate(friend_list): friend_obj = {} num += 1 friend = User(friend_id) friend_obj["loginid"] = i friend_obj["nickname"] = friend.nickname friend_obj["address"] = friend.address friend_obj["phone_num"] = friend.phone_num friend_obj["sex"] = friend.sex friend_obj["signature"] = friend.signature friend_obj["mail"] = friend.mail friend_obj["online"] = friend.online friend_obj["age"] = friend.age obj["list"].append(friend_obj) obj["friend_num"] = num data = json.dumps(obj, indent=4) print data # send_packet(con,0,4,data,len(data)) packet = wrap_packet(con, 0, 4, data, len(data)) return packet
def post(self): """ Handle the sign-up request. """ email = self.request.get("email") pwd = self.request.get("password") verify = self.request.get("verify") # there is verification on browser by JS, but validating again won't hurt if not self._validate(email, pwd, verify): logging.error("How could the invalid input pass the JS test? @auth.SignUpHandler.post()") self.redirect("/signup") return if User.exists(email): # telling user that the email has been taken self._error("Email registered by others") else: hashed = encrypt.hash_pwd(email, pwd) u = User(email=email, pwd_hashed=hashed, parent=utils.get_key_public('User')) u.put() self._init_user(u) self._set_id_cookie(email) self.redirect('/me')
def delete(self): """ """ # Only owner can delete an instance if not self.own_by(User.get_current_user()): raise OwnerException("user '%s' try to update a namespace owns by '%s'."%(User.get_current_user().username, self.owner.username)) return super(Tiddlywiki, self).delete()
#!flask/bin/python from flask import Flask, jsonify, abort, make_response, request from auth import Auth from user import User users = [ User(1, 'user1', 'abcxyz'), User(2, 'user2', 'abcxyz'), ] auth = Auth() app = Flask(__name__) app.debug = True @app.route('/') def index(): return 'Hello, World!' @app.route('/login', methods=['POST']) def login(): data = request.get_json() print(data) encoded = auth.getJWT(data['username']) return jsonify({'user': data['username'], 'jwt': str(encoded)}) @app.errorhandler(404) def not_found(error):
def identity(payload): user_id = payload['identity'] return User.find_by_id(user_id)
def _train_users(self, data): ''' @ret: users list - with user object for each trained user. ''' data_hash1 = hashlib.md5(pickle.dumps(data)).hexdigest() users = [] start_time = time.time() np.random.seed(self.params.seed) if self.params.verbose: print('total num users are ', len(data)) for i, yi in enumerate(data): if i >= self.params.quick_test_num and self.params.quick_test: break # All reps of this user. Each element in Xi represents the features of # the typed password. if yi in self.params.skip_users: print 'skipped user ', yi continue # So we can separate out the mouse training process. if self.params.keystrokes or self.params.android: ''' TODO: Create new function. Basically deals with the point till we create a user, including a lot of ugly stuff. ''' train_samples = data[yi] if len(train_samples) < 50: print( 'skipping user {} because too few samples'.format(yi)) continue self._sanity_check(train_samples) if self.params.android: # impostors = self._get_first_impostors(data, yi) impostors = self._get_impostors(data, yi, num=len(train_samples), samples_per_user=2) train_impostors = [] elif 'mturk' in self.params.dataset: # Not using train impostors so far... train_impostors = self._get_impostors(data, yi, num=100, samples_per_user=5, seed=2468) # Also, I'm not using get_first_impostors here, because then we # will at least have 600 (or more) impostor samples, as opposed to # just 50 genuine samples... impostors = self._get_impostors(data, yi, num=len(train_samples) / 2, samples_per_user=1) else: # FIXME: decide how to select train_impostors... train_impostors = self._get_impostors( data, yi, num=len(train_samples) / 2, samples_per_user=5) impostors = self._get_first_impostors(data, yi) if self.params.induced_eer: impostors = self._get_kmeans_impostors( data, yi, num=len(train_samples) / 2) self._sanity_check(impostors) user = User(yi, np.copy(train_samples), np.copy(impostors), np.copy(train_impostors), self) elif self.params.mouse: if len(data[yi].tasks) < 10: continue impostors = self._get_mouse_impostors(data, yi, num_per_user=25) user = MouseUser(yi, data[yi], impostors, self) else: assert False, 'not supported experiment kind' if self.params.svm: user.train(lambda: OneClassSVM(), name='SVM1') if self.params.ae: user.train(lambda: Autoencoder([5, 4, 3]), name='Autoencoder') if self.params.var_ae: user.train( lambda: VariationalAutoencoder(dict(n_hidden_recog_1=5, n_hidden_recog_2=5, n_hidden_gener_1=5, n_hidden_gener_2=5, n_z=3), batch_size=2), name='VariationalAutoencoder') if self.params.con_ae: start_ac = time.time() user.train(lambda: ContractiveAutoencoder(400, lam=1.5), name='ContractiveAutoencoder') end_ac = time.time() if self.params.manhattan: user.train(lambda: Manhattan(), name='Manhattan') if self.params.random_forests: user.train( lambda: RandomForests(n_estimators=self.params.rf_trees), two_class=True, name='RandomForests') if self.params.knc: user.train(lambda: KNC(n_neighbors=self.params.knc_neighbors), two_class=True, name='KNC') if self.params.fc_net: user.train(lambda: FullyConnectedNetwork(), two_class=True, name='FC_Net') if self.params.gaussian: user.train(lambda: Gaussian(), name='Gaussian') if self.params.nearest_neighbors: user.train(lambda: NN(), name='NearestNeighbors') #TODO: this still doesn't work because of the way fit works right # now. if self.params.pohmm: user.train(lambda: Pohmm(n_hidden_states=2, init_spread=2, emissions=['lognormal', 'lognormal'], smoothing='freq', init_method='obs', thresh=1e-2)) if self.params.gaussian_mixture: user.train(lambda: GM(), name='Gaussian Mixture') users.append(user) # This doesn't seem particularly useful. Maybe get stats later, but # people did generally well...can just use EER stats instead. # Full on test on every random guy we got: if self.params.complete_check: self._complete_check(data, yi, user) data_hash2 = hashlib.md5(pickle.dumps(data)).hexdigest() assert data_hash1 == data_hash2, 'data hashes diff!' end_time = time.time() # print 'total time for _train_users function ',(end_time-start_time) # Just update the list of used classifiers - not the ideal place to do # it but whatever. for user in users: for cl in user.classifiers: self.params.classifiers_list.append(cl) break return users
def author_info(self, topic): author_url = home_page_url + "/api/members/show.json?username=" + topic.author response = session.get(author_url) data = json.loads(response.content) user = User() user.id = data.get('id') user.name = data.get('username') user.website = data.get('website') user.twitter = data.get('twitter') user.github = data.get('github') user.location = data.get('location') user.tagline = data.get('tagline') user.bio = data.get('bio') user.time = format_time(data.get('created')) return user
from werkzeug.security import safe_str_cmp from user import User users = [User(1, 'john', 'asdf')] username_mapping = {u.username: u for u in users} user_id_mapping = {u.id: u for u in users} def authenticate(username, password): user = username_mapping.get(username, None) if user and safe_str_cmp(user.password, password): return user def identity(payload): user_id = payload['identity'] return user_id_mapping.get(user_id, None)
from user import User users = [User(1, "bob", "hello")] username_mapping = {u.username: u for u in users} # search through users to create mapping userid_mapping = {u.id: u for u in users} def authenticate(username, password): user = username_mapping.get(username, None) # user == None if no match if user and user.password == password: return users def identity(payload): user_id = payload["identity"] return userid_mapping.get(user_id, None)
def new_user(uid): usr = User(uid) save_user(usr)
def load_user(user_id): user_json = user_coll.find_one({'_id': ObjectId(user_id)}) return User(user_json)
def get(self): """List all users""" return list(User.objects().order_by('-id'))
from movie import Movie from user import User import json with open('my_file.txt', 'r') as f: json_data = json.load(f) user = User.from_json(json_data) print(user.json())
from werkzeug.security import safe_str_cmp from user import User users = [User(1, 'bob', 'asdf'), User(2, 'alice', 'cdfg')] username_mapping = {u.username: u for u in users} userid_mapping = {u.id: u for u in users} def authenticate(username, password): user = username_mapping.get(username, None) if user and safe_str_cmp(user.password, password): return user def identity(payload): user_id = payload['identity'] return userid_mapping.get(user_id, None)
def get(self): username = request.args.get('username') password = request.args.get('password') LoggingUser = User(username, password) return {'authentification status': [LoggingUser.authentificate()]}
# Clean DB remove_empty_slots(database) # Load movie dict db_dict = pickle.load(open(DICT_FILE_PATH, 'rb'), encoding='latin1') # Load goal file user_goals = pickle.load(open(USER_GOALS_FILE_PATH, 'rb'), encoding='latin1') # Init. Objects if USE_USERSIM: user = UserSimulator(user_goals, constants, database) else: user = User(constants) emc = ErrorModelController(db_dict, constants) state_tracker = StateTracker(database, constants) dqn_agent = DQNAgent(state_tracker.get_state_size(), constants) def test_run(): """ Runs the loop that tests the agent. Tests the agent on the goal-oriented chatbot task. Only for evaluating a trained agent. Terminates when the episode reaches NUM_EP_TEST. """ print('Testing Started...')
def load_user(user_id): user_password = DB.get_user(user_id) if user_password: return User(user_id)
from user import User from database import Database from twitter_utils import * Database.initialize(user='******', password='******', host='localhost', database='learning') screen_name = input('Please enter your email:') # returns true if user is found on the database with the provided email address, returns false otherwise user = User.loadFromDbByScreenName(screen_name) # if not found, takes the user to authorize and later puts necessary credentials into the database if not user: request_token = getRequestToken() oauth_verifier = getOauthVerifier(request_token) access_token = getAccessToken(request_token, oauth_verifier) first_name = input("Your First name : ") last_name = input("And your Last name : ") user = User(screen_name, access_token['oauth_token'], access_token['oauth_token_secret'], None) user.SaveToDB() # now, creating an authenticated token object so as to perform Twitter API calls. authorized_token = oauth2.Token(user.oauth_token, user.oauth_token_secret) authorized_client = oauth2.Client(consumer, authorized_token)
conn.sendall(pickle.dumps(reply)) except: break print('Lost connection') conn.close() def write_json(data, filename='users.json'): with open(filename, 'r+') as file: json.dump(data, file, indent=4) current_user = 0 while True: conn, addr = s.accept() print('Connected to:', addr) with open('users.json', 'r+') as file: print('im here') new_data = {str(current_user): ["", str(current_user), 'USER', []]} data = json.loads(file.read()) data.update(new_data) write_json(data) print('appending...') users.append(User("", str(current_user), "", [])) start_new_thread(threaded_client, (conn, current_user)) current_user += 1
def login(): user = User() login_user(user) return redirect(url_for('dashboard'))
from user import User from database import Database from twitter_utils import * Database.initialise(user='******', password='******', database='learning', host='localhost') email = input("Enter email id: ") user = User.load_from_db_by_email(email) if not user: request_token = get_request_token() verifier = get_oauth_verifier(request_token) access_token = get_access_token(request_token, verifier) print(access_token) first_name = input("First Name: ") last_name = input("Last Name: ") user = User(email, first_name, last_name, access_token['oauth_token'], access_token['oauth_token_secret'], None) user.save_to_db() tweets = user.twitter_request( 'https://api.twitter.com/1.1/search/tweets.json?q=computers+filter:images') for tweet in tweets['statuses']: print(tweet['text'])
class TestCredentials(unittest.TestCase): ''' Test class that defines test cases for the credentials class behaviours. Args: unittest.TestCase: helps in creating test cases ''' def test_check_user(self): ''' Function to test whether the login in function check_user works as expected ''' self.new_user = User('Charles', 'Ndayisaba', 'ps123') self.new_user.save_user() user2 = User('Geek', 'Ndayisaba', 'ps123') user2.save_user() for user in User.users_list: if user.first_name == user2.first_name and user.password == user2.password: current_user = user.first_name return current_user self.assertEqual( current_user, Credential.check_user(user2.password, user2.first_name)) def setUp(self): ''' Function to create an account's credentials before each test ''' self.new_credential = Credential('Charles', 'Facebook', 'nccharles', 'ps123') def test__init__(self): ''' Test to if check the initialization/creation of credential instances is properly done ''' self.assertEqual(self.new_credential.user_name, 'Charles') self.assertEqual(self.new_credential.site_name, 'Facebook') self.assertEqual(self.new_credential.account_name, 'nccharles') self.assertEqual(self.new_credential.password, 'ps123') def test_save_credentials(self): ''' Test to check if the new credential info is saved into the credentials list ''' self.new_credential.save_credentials() twitter = Credential('Montana', 'Twitter', 'nccharles', 'ps123') twitter.save_credentials() self.assertEqual(len(Credential.credentials_list), 2) # def test_generate_password(self): # ''' # Test to check if the generate password generates 8 character long alphanumeric numbers # ''' # self.twitter = Credential('Twitter','nccharles','') # self.twitter.password = generate_password() # self.assertEqual() def tearDown(self): ''' Function to clear the credentials list after every test ''' Credential.credentials_list = [] User.users_list = [] def test_display_credentials(self): ''' Test to check if the display_credentials method, displays the correct credentials. ''' self.new_credential.save_credentials() twitter = Credential('Montana', 'Twitter', 'nccharles', 'ps123') twitter.save_credentials() gmail = Credential('Montana', 'Gmail', 'nccharles', 'pswd200') gmail.save_credentials() self.assertEqual( len(Credential.display_credentials(twitter.user_name)), 2) def test_find_by_site_name(self): ''' Test to check if the find_by_site_name method returns the correct credential ''' self.new_credential.save_credentials() twitter = Credential('Montana', 'Twitter', 'nccharles', 'ps123') twitter.save_credentials() credential_exists = Credential.find_by_site_name('Twitter') self.assertEqual(credential_exists, twitter) def test_copy_credential(self): ''' Test to check if the copy a credential method copies the correct credential ''' self.new_credential.save_credentials() twitter = Credential('Montana', 'Twitter', 'nccharles', 'ps123') twitter.save_credentials() find_credential = None for credential in Credential.user_credentials_list: find_credential = Credential.find_by_site_name( credential.site_name) return pyperclip.copy(find_credential.password) Credential.copy_credential(self.new_credential.site_name) self.assertEqual('ps123', pyperclip.paste()) print(pyperclip.paste())
def load_user(user_id): return User()
def create_user(firstname,password): ''' Function to create a new user ''' new_user = User(firstname,password) return new_user
def setUp(self) -> None: self.task = User(ttask=2)
def check_existing(firstname): ''' Function that check if a user exists with the firstname and return a Boolean ''' return User.user_exist(firstname)
def setUp(self): ''' Function to create a user account before each test ''' self.new_user = User('Charles', 'Ndayisaba', 'ps123')
from user import User users = [User(1, 'bob', 'asdf')] username_mapping = {u.username: u for u in users} userid_mapping = {u.id: u for u in users} def authenticate(username, password): user = username_mapping.get(username, None) if user and user.password == password: return user def identity(playload): user_id = playload['identity'] return userid_mapping.get(user_id, None)
def display_user(): ''' Function that returns all the saved users ''' return User.display_users()
def save_user(user): ''' Function to save a new user account ''' User.save_user(user)
def find_users(firstname): ''' Function that finds a user by firstname and returns the user ''' return User.find_user(firstname)
def authenticate(username, password): user = User.find_by_username(username) if user and safe_str_cmp(user.password, password): return user
def setUp(self): ''' Set up method to run before each test cases. ''' self.new_user = User("PerisOduol", "oduol254") # create contact object