def initiate_reset(self, data): # Validate data needed = ["email", "password"] for item in needed: if item not in data: return False if data["password"]: # Attempt to keep bots at bay return False # Find user email = data["email"].lower() cursor = self.__database.cursor() # Send mail for row in cursor.execute(self.__user_select + "WHERE email=?", (email, )): user = User(*row) assert user translator = user.get_dictionary() timeout = int(translator.get("_reset_expiration_user_")) (sid, expires) = self.__create_session(exp_minutes=timeout) cursor.execute(self.__session_insert, (sid, email, self.SESSION_RESET, expires)) logging.debug("Initiate reset for " + email) mail = Email(user.get_email(), translator, "_reset_subject_") variables = {"__reset_link": sid, "__name": user.get_name()} mail.load_body("reset", variables) mail.run() self.__database.commit() return True logging.debug("Reset failed") return False
def register(): if request.method == 'GET': return render_template('register.html') else: data = urllib.parse.unquote(request.data.decode('utf-8')).split('&') data = [d.split('=')[1] for d in data] username = data[0] password = data[1] if user.exists(username): return "false" else: # Username is unique # The account gets added to the database u = User() pw_hash, salt = user.hash_password(password) u.username = username u.password_hash = pw_hash u.salt = salt user.add(u) return "true"
def post(self, payload): """Create a new user. Only authenticating user can post User ID is defined by the verified subject in the access token """ logger.info(f"POST request to create user " f"{payload['sub']} from {request.remote_addr}") message = "" try: user = User(**api.payload) user.id = payload['sub'] api.payload['id'] = payload['sub'] user.insert() code = 201 except ValueError as e: code = 422 message = str(e) except IntegrityError: code = 422 message = "Cannot add to existing user. " \ "Use Patch request instead" except Exception as e: logger.debug(e) code = 400 message = "The request data format is not valid" if code != 201: abort(code, message) return api.payload, 201
class GroupTests: def __init__(self): self.p1 = Protein(1, "p1", "P1", 1, -1) self.p2 = Protein(2, "p2", "P2", 1, -1) self.p3 = Protein(3, "p3", "P3", 2, -1) self.p4 = Protein(4, "p4", "P4", 1, -1) self.pg1 = ProteinGroup(1, "g1", [], {self.p1, self.p2}) self.pg2 = ProteinGroup(2, "g2", [], {self.p1, self.p3, self.p4}) self.pg3 = ProteinGroup(3, "g3", [self.pg1]) self.pg4 = ProteinGroup(4, "g4", [self.pg1, self.pg2, self.pg3]) self.ug1 = UserGroup(1, "all", {}, [(self.pg1, 0x01)]) self.ug2 = UserGroup(2, "jr", {self.ug1}, []) self.ug3 = UserGroup(3, "ys", {self.ug1}, [(self.pg2, 0x06), (self.pg3, 0x02)]) self.u1 = User(1, "jrenggli", "[email protected]", 42, {self.ug2}) self.u2 = User(2, "yschaerli", "[email protected]", 8282, {self.ug2, self.ug3}) def test_protein_groups(self): assert(self.pg1.get_proteins() != self.pg2.get_proteins()) assert(self.pg1.get_proteins() & self.pg2.get_proteins() == {self.p1}) assert(self.pg1.get_proteins() == self.pg3.get_proteins()) assert(self.pg4.get_proteins() & self.pg3.get_proteins() == self.pg4.get_proteins()) def test_user_groups(self): assert(self.ug1.get_proteins() == {self.p1 : 1, self.p2 : 1}) assert(self.ug2.get_proteins() == self.ug1.get_proteins()) assert(self.ug3.get_proteins() == {self.p1 : 0x07, self.p2 : 0x03, self.p3 : 0x06, self.p4 : 0x06}) assert(self.u1.get_proteins() == self.ug2.get_proteins()) assert(self.u2.get_proteins() == self.ug3.get_proteins())
class GroupTests: def __init__(self): self.p1 = Protein(1, "p1", "P1", 1, -1) self.p2 = Protein(2, "p2", "P2", 1, -1) self.p3 = Protein(3, "p3", "P3", 2, -1) self.p4 = Protein(4, "p4", "P4", 1, -1) self.pg1 = ProteinGroup(1, "g1", [], {self.p1, self.p2}) self.pg2 = ProteinGroup(2, "g2", [], {self.p1, self.p3, self.p4}) self.pg3 = ProteinGroup(3, "g3", [self.pg1]) self.pg4 = ProteinGroup(4, "g4", [self.pg1, self.pg2, self.pg3]) self.ug1 = UserGroup(1, "all", {}, [(self.pg1, 0x01)]) self.ug2 = UserGroup(2, "jr", {self.ug1}, []) self.ug3 = UserGroup(3, "ys", {self.ug1}, [(self.pg2, 0x06), (self.pg3, 0x02)]) self.u1 = User(1, "jrenggli", "[email protected]", 42, {self.ug2}) self.u2 = User(2, "yschaerli", "[email protected]", 8282, {self.ug2, self.ug3}) def test_protein_groups(self): assert (self.pg1.get_proteins() != self.pg2.get_proteins()) assert (self.pg1.get_proteins() & self.pg2.get_proteins() == {self.p1}) assert (self.pg1.get_proteins() == self.pg3.get_proteins()) assert (self.pg4.get_proteins() & self.pg3.get_proteins() == self.pg4.get_proteins()) def test_user_groups(self): assert (self.ug1.get_proteins() == {self.p1: 1, self.p2: 1}) assert (self.ug2.get_proteins() == self.ug1.get_proteins()) assert (self.ug3.get_proteins() == { self.p1: 0x07, self.p2: 0x03, self.p3: 0x06, self.p4: 0x06 }) assert (self.u1.get_proteins() == self.ug2.get_proteins()) assert (self.u2.get_proteins() == self.ug3.get_proteins())
def register(): if request.method == 'POST': request_json = request.get_json() name = request_json.get('name') email = request_json.get('email') if User.query.filter_by(email=email).first(): return jsonify( {'message': 'The email has already been registered'}), 401 password = request_json.get('password') role = request_json.get('role') company_code = request_json.get('company_code') user_public_id = str(uuid.uuid4()) user = User(user_public_id, name, email, role, company_code) user.hash_password(password) try: db.session.add(user) db.session.commit() access_token = create_access_token(identity=user.email) refresh_token = create_refresh_token(identity=user.email) response_object = {} response_object[ 'message'] = 'Register of {} was Successful'.format(user.email) response_object['access_token'] = access_token response_object['refresh_token'] = refresh_token return jsonify(response_object), 200 except: return jsonify({'message': 'Something went wrong'}), 500
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 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 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) # Doesn't exist? Add it to the database. if not User.get(unique_id): User.create(unique_id, users_name, users_email, picture) new_user = True return new_user # Begin user session by logging the user in login_user(user, remember=True, duration=timedelta(days=30)) # Send user back to homepage return redirect(url_for("home"))
def test_get(self): self.user.create_table() self.user.save() results = User.get() self.assertEqual(self.user, results[0], "Unable to get all data") import datetime d = datetime.datetime.now() - datetime.timedelta(minutes=2) results = User.get(d) self.assertEqual(self.user, results[0], "Unable to get new data")
def login_post(): data = request.get_json() is_authenticated = User.authenticate_user( db=DB, email=data['email'], password=data['password']) if is_authenticated: user_id = User.get_user_id_from_email(DB, email=data['email']) login_user(User.get_user(DB, user_id)) return json.dumps({'success':True}), 200, {'ContentType':'application/json'} return json.dumps({'success':False}), 401, {'ContentType':'application/json'}
def user_rules(): if not session.get('logged_in'): return jsonify({"status": False}) user = User(session['user_email']) resp = {} resp['rules'] = rules.fill_rules(user.get_rules()) resp['days'] = user.get_days() return jsonify(resp)
def forgot(): if request.method == 'POST': if not string_validator.is_valid_email(request.form['email']): return render_template('forgot.html', sitekey=conf.recaptcha_sitekey, server_error="Invalid email address") else: # Captcha if conf.recaptcha_sitekey and conf.recaptcha_secret: captcha_response = request.form['g-recaptcha-response'] captcha_verify = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data={ 'secret': conf.recaptcha_secret, 'response': captcha_response }) captcha_verify_json = json.loads(captcha_verify.text) if captcha_verify_json['success'] is False: return render_template('forgot.html', sitekey=conf.recaptcha_sitekey, server_error="Captcha failure") user = User(email=request.form['email']) if user.hash is None: return render_template('forgot.html', sitekey=conf.recaptcha_sitekey, server_error="Account not found") verify_token = timed_serializer.dumps(user.email, salt=conf.email_salt) url = conf.domain + "/resetpass/" + verify_token user.verify_token = verify_token user.update() render_map = { "url": url, } send_email("forget_email.html", "VulnFeed Password Reset", render_map, user.email) return render_template( 'forgot.html', sitekey=conf.recaptcha_sitekey, success_message= "A password recover email has been sent to your email address") else: return render_template('forgot.html', sitekey=conf.recaptcha_sitekey)
async def register(self, ctx): if ctx.channel.id == self.channel_id: try: user = User.objects(name=str(ctx.author)).get() response = f'{user.name} of level {user.level} exists!!' await ctx.channel.send(response) except DoesNotExist: user = User(name=str(ctx.author), level=1) user.save() response = f'{user.name} created with level {user.level}. Have fun!!' await ctx.channel.send(response)
def create_user(user_id: int, username: str, language: str, chat_id: str) -> User: user = User(telegram_id=str(user_id), username=username, language=language, chat_id=chat_id) try: user.save() except: print("error in create user") return user
async def levelup(self, ctx): if ctx.channel.id == self.channel_id: try: user = User.objects(name=str(ctx.author)).get() user.update(level=int(user.level) + 1) user.save() user = User.objects(name=str(ctx.author)).get() response = f'{user.name} is now of level {user.level}!!' await ctx.channel.send(response) except DoesNotExist: response = f'{ctx.author} not register please register' await ctx.channel.send(response)
def update_status(username, state): session = Session() res = session.query(User).filter(User.name == username).all() if len(res) < 1: user = User(username, state) session.add(user) session.commit() session.close() if len(res) == 1: user = session.query(User).filter(User.name == username).first() user.state = state session.commit() session.close()
def post(self): username = self.request.get("username") password = self.request.get("password") p = check.valid_password(password) u = check.valid_username(username) if p and u and ve: self.redirect('/') else: u = User(name = username, hash_pw = password) u.put() self.render("register.html", username = username, email = email)
def start(cls): """Run starting commands need sql to run""" User.table_setup() if User.do_select().where( User.is_admin == True).count() == 0: # noqa E712 password = cls.generate_password() with open(File.location("adminpasssword"), "w") as f: f.write(password) User.insert(username="******", password=cls.__password_encryption(password), is_admin=True).execute()
def __init__(self): self.p1 = Protein(1, "p1", "P1", 1, -1) self.p2 = Protein(2, "p2", "P2", 1, -1) self.p3 = Protein(3, "p3", "P3", 2, -1) self.p4 = Protein(4, "p4", "P4", 1, -1) self.pg1 = ProteinGroup(1, "g1", [], {self.p1, self.p2}) self.pg2 = ProteinGroup(2, "g2", [], {self.p1, self.p3, self.p4}) self.pg3 = ProteinGroup(3, "g3", [self.pg1]) self.pg4 = ProteinGroup(4, "g4", [self.pg1, self.pg2, self.pg3]) self.ug1 = UserGroup(1, "all", {}, [(self.pg1, 0x01)]) self.ug2 = UserGroup(2, "jr", {self.ug1}, []) self.ug3 = UserGroup(3, "ys", {self.ug1}, [(self.pg2, 0x06), (self.pg3, 0x02)]) self.u1 = User(1, "jrenggli", "[email protected]", 42, {self.ug2}) self.u2 = User(2, "yschaerli", "[email protected]", 8282, {self.ug2, self.ug3})
def logout(self): #get auth token auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] else: auth_token = ' ' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): #mark the token as blacklisted # blacklist_token = Token(token=0) #blacklisted token try: #insert the token # db.session.add(blacklist_token) db.session.commit() response_object = { 'status': 'success', 'message': 'Successfully logged out.' } return jsonify(response_object), 200 except Exception as e: response_object = {'status': 'fail', 'message': str(e)} return jsonify(response_object), 200 else: response_object = {'status': 'fail', 'message': resp} return jsonify(response_object), 401 else: response_object = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return jsonify(response_object), 403
def get_users(): if current_user.is_admin: users = User.get_registered_non_admin_users(db=DB) return jsonify(users) else: return json.dumps( {'success':False}), 401, {'ContentType':'application/json'}
def login(): if request.method == 'POST': message = "" user = User(request.form['email']) if user.login(request.form['password']): session['logged_in'] = True session['user_email'] = request.form['email'] return redirect("/", code=302) else: session['logged_in'] = False session['user_email'] = "" message = "Incorrect user/password" return render_template('login.html', server_error=message) else: return render_template('login.html')
def login(): if request.method == 'POST': if address_failed_login(request.remote_addr): return render_template( 'login.html', server_error= "You have exceeded the number of fail logins. Try again later") user_email = request.form['email'] if not string_validator.is_valid_email(user_email): session['logged_in'] = False session['user_email'] = "" message = "Incorrect user/password" message = "" user = User(email=user_email) if user.login(request.form['password']) and user.is_confirmed(): session['logged_in'] = True session['user_email'] = user_email clear_failed_login(request.remote_addr) session['csrftoken'] = serializer.dumps(binascii.hexlify( os.urandom(128)).decode('utf-8'), salt=conf.email_salt) if user.feed_id is None: user.generate_feed_id() user.update() return redirect("/", code=302) # User doesn't exist elif user.hash == None: session['logged_in'] = False session['user_email'] = "" message = "Incorrect user/password" # User is not confirmed elif not user.is_confirmed(): session['logged_in'] = False session['user_email'] = "" message = "You have not verified your email address" else: session['logged_in'] = False session['user_email'] = "" message = "Incorrect user/password" return render_template('login.html', server_error=message) else: return render_template('login.html')
def resetpass(token): try: email = timed_serializer.loads(token, salt=conf.email_salt, max_age=7200) except Exception as e: return "Could not parse token" if not string_validator.is_valid_email(email): return "Invalid email" user = User(email=email) if user.verify_token != token: return "Invalid token" if request.method == 'POST': if request.form['password'] != request.form['password2']: return render_template('signup.html', sitekey=conf.recaptcha_sitekey, server_error="Passwords do not match!") else: user.new_password(request.form['password']) user.verify_token = "" user.update() return redirect("/login", code=302) else: if user.hash is not None: return render_template('resetpass.html', user_token=token) else: return "Invalid token"
def user_with_email_exists(): data = request.get_json() user_with_email_exists = User.user_with_email_exists( db=DB, email=data['email']) if user_with_email_exists: return json.dumps({'success':True}), 200, {'ContentType':'application/json'} else: return json.dumps( {'success':False}), 400, {'ContentType':'application/json'}
def update_user_rules(): if not session.get('logged_in'): return jsonify({"status": False}) user = User(session['user_email']) # try: new_config = request.get_json() user.set_rules(new_config['rules']) user.set_days(new_config['days']) user.update() return jsonify({"status": True})
def change_password(): data = request.get_json() successfully_updated = User.update_password( db=DB, email=data['email'], password=data['password']) if successfully_updated: return json.dumps( {'success':True}), 200, {'ContentType':'application/json'} else: return json.dumps( {'success':False}), 500, {'ContentType':'application/json'}
def insert_user(username, state): session = Session() user = User(username, state) res = session.query(User).filter(User.name == username).all() if len(res) < 1: session.add(user) session.commit() session.close() else: print('User already exists')
def check_logged_in(cls) -> int: """Check if logged in""" if "sessionid" in cherrypy.request.cookie.keys(): sessionid = cherrypy.request.cookie["sessionid"].value if sessionid in cls.__temp_sessions: user: User = User.get_by_id(cls.__temp_sessions[sessionid]) is_admin = user.is_admin if is_admin: return cls.ADMIN return cls.USER return cls.GUEST
def last_report(): if not session.get('logged_in'): return redirect("/login", code=302) user = User(email=session['user_email']) if user: return render_template('last_report.html', last_scored_reports=user.last_scored_list, last_unscored_reports=user.last_unscored_list) else: return "ERROR: User not found!"
def test_eq(self): """ Equals method """ web1 = Web("test") web2 = Web("test") web3 = Web("na") user = User("test") self.assertEqual(web1, web2) self.assertNotEqual(web1, web3) self.assertNotEqual(web1, user) self.assertNotEqual(web1, None)
def register(): body = request.get_json() errors = register_schema.validate(body) if errors: return jsonify({'error': errors}), 400 user = User(**body) user.hash_password() user.email_verification_token = random_str() # Create default project for user # INSERT INTO project (name) VALUES (%s) # INSERT INTO user (...) VALUES () # INSERT INTO user_project (user_id, project_id, `role`) VALUES (%s, %s, %s) project = Project(name='First project') user_project = UserProject(user=user, project=project, role=UserProjectRole.ADMIN) project.user_project.append(user_project) db.session.add(user) db.session.commit() welcome_email(user) return jsonify(user_schema.dump(user)), 201
def profile(): if not session.get('logged_in'): return redirect("/login", code=302) user = User(email=session['user_email']) raw_data = json.dumps(user.get_minimized_raw(), indent=4, separators=(',', ': ')) user_rules = rules.get_rules(user=user.id) return render_template( 'profile.html', email=user.email, last_status=user.last_status, rule_count=len(user.get_rules()), last_sent=user.get_last_run_date().strftime('%m/%d/%Y'), my_rules=user_rules, raw_profile=raw_data, feed_id=user.feed_id)
def post(self): user_name = self.request.get("username") password = self.request.get("password") u = User.login(user_name, password) if u: self.login(u) self.redirect('/') else: msg = "invalid login" self.render('login.html', error = msg, username = user_name)
def test_pubkeys(self): from collections import Counter self.user.create_table() self.user.save() self.user.add_key("pubkey") self.user.add_key('second_pubkey') self.user.add_key('third_pubkey') self.assertEqual(Counter(['pubkey', 'second_pubkey', 'third_pubkey']), Counter([i.c_key for i in self.user.get_keys()]), 'did not save keys') user = User.get_exactly(self.user.c_id) self.assertEqual(Counter(['pubkey', 'second_pubkey', 'third_pubkey']), Counter([i.c_key for i in user.get_keys()]), 'did not load keys')
def change_password(): error_message = None if request.method == 'POST': user = User.get(g.user.id) original_password = request.form.get('original_password') new_password = request.form.get('new_password') if new_password != request.form.get('new_password_check'): error_message = 'New passwords do not match.' elif not check_password_hash(user.password_hash, original_password): error_message = 'Your password is not correct.' elif len(new_password) < 8: error_message = 'New password must be at least 8 characters.' else: user.password_hash = generate_password_hash(new_password) save_changes() return render_template('/pages/admin/change_password.html', error_message=error_message)
def setUp(self): Database.db_file = None # else the runtime destroys testsing framework Database(self.gentest_config()) self.user = User("Douglas") self.connection = Database.db_connection self.cursor = self.connection.cursor()
def test_get_exactly(self): self.user.create_table() self.user.save() user = User.get_exactly(self.user.c_id) self.assertEqual(user, self.user, "Could not deserialize data")
def test_override(self): """ This function tests the default override procedure. """ self.user.create_table() self.user.save() user2 = User('Douglas') user2.save()
class UserTest(unittest.TestCase): """ Tests for user.py """ def gentest_config(self): conffile = "test.conf" with open(conffile, "w") as file: file.write("""[Backend] Hostname = localhost User = foo SSH-Port = 22 Database = test.db Manifest_store = /dev/null authorized_keys = auth_keys""") return conffile def setUp(self): Database.db_file = None # else the runtime destroys testsing framework Database(self.gentest_config()) self.user = User("Douglas") self.connection = Database.db_connection self.cursor = self.connection.cursor() def tearDown(self): self.connection.close() os.remove(self.gentest_config()) os.remove(Database.db_file) def test_create_table(self): self.user.create_table() self.cursor.execute("""SELECT name FROM sqlite_master WHERE name = 'User';""") table_exists = False result = self.cursor.fetchone() self.assertFalse(result is None, "Table user could not been found") for i in result: if 'User' in i: table_exists = True self.assertTrue(table_exists) def test_drop_table(self): self.user.create_table() self.user.drop_table() self.cursor.execute("""SELECT name FROM sqlite_master WHERE name = 'User';""") self.assertTrue(self.cursor.fetchone() is None, "Database could not been droped") def test_getitem(self): self.user.create_table() self.assertEqual(self.user["c_id"], "Douglas") # self.assertEqual(self.user["c_pubkey"], "pubkey") try: self.user["db_file"] self.assertTrue(False, "Was able to caught wrong attribute") except AttributeError: pass def test_get_attributes(self): self.user.create_table() attrs = self.user.get_attributes() self.assertTrue("c_id" in attrs) # self.assertTrue("c_pubkey" in attrs) self.assertFalse("__doc__" in attrs) def test_save(self): with self.assertRaises(NoSuchTable): self.user.save() self.user.create_table() self.user.save() # Restarting database connection self.connection.close() Database() # Try to read original data self.cursor = Database.db_connection.cursor() # First, try to get data self.cursor.execute("""SELECT * FROM User""") result = self.cursor.fetchall() self.assertEqual(len(result), 1, "too much or too less objects") self.cursor.execute("""SELECT * FROM User WHERE c_id = 'Douglas';""") result = self.cursor.fetchone() self.assertIsNotNone(result, "Couldn't read data from database") result = tuple(result) self.assertEqual(result[3], 'Douglas') def test_remove(self): self.user.create_table() self.user.save() for key in self.user.get_keys(): key.save() self.user.remove() self.cursor.execute("""SELECT * FROM User WHERE c_id = 'Douglas';""") self.assertTrue(self.cursor.fetchone() is None, "Removing Entries has failed") def test_get(self): self.user.create_table() self.user.save() results = User.get() self.assertEqual(self.user, results[0], "Unable to get all data") import datetime d = datetime.datetime.now() - datetime.timedelta(minutes=2) results = User.get(d) self.assertEqual(self.user, results[0], "Unable to get new data") def test_get_exactly(self): self.user.create_table() self.user.save() user = User.get_exactly(self.user.c_id) self.assertEqual(user, self.user, "Could not deserialize data") def test_override(self): """ This function tests the default override procedure. """ self.user.create_table() self.user.save() user2 = User('Douglas') user2.save() def test_pubkeys(self): from collections import Counter self.user.create_table() self.user.save() self.user.add_key("pubkey") self.user.add_key('second_pubkey') self.user.add_key('third_pubkey') self.assertEqual(Counter(['pubkey', 'second_pubkey', 'third_pubkey']), Counter([i.c_key for i in self.user.get_keys()]), 'did not save keys') user = User.get_exactly(self.user.c_id) self.assertEqual(Counter(['pubkey', 'second_pubkey', 'third_pubkey']), Counter([i.c_key for i in user.get_keys()]), 'did not load keys')
def load_user(user_id): from database.user import User return User.get(user_id)