def login(self, email, password): encrypted_password = helpers.encrypt_password(password) doc = { "email": email, "password": encrypted_password } return self.db.customers.find_one(doc)
def change_password(): post_args = flask.request.get_json() post_headers = flask.request.headers if not authenticate_route(post_headers): return {"status": 401, "error": "Missing session key."}, 200 username = global_vars.sessions.get(post_headers.get("Session-Key")) conn = sqlite3.connect("db.db") c = conn.cursor() c.execute( "SELECT password FROM users WHERE username = '******'".format(username)) old_password = post_args.get("old_password") old_hashed_password = c.fetchone()[0] new_password = post_args.get("new_password") if check_encrypted_password(old_password, old_hashed_password): c.execute( "UPDATE users SET password = '******' WHERE username = '******'".format( encrypt_password(new_password), username)) conn.commit() conn.close() return {"status": 200}, 200 else: conn.commit() conn.close() return { "error": "Your password does not match your current password.", "status": 401, }, 200
def test_create_customer(self): customer_doc = { "name": "Carlos Andrade", "email": "*****@*****.**", "password": "******" } # Valid Registration answer = self.app.post("/api/customers", params=customer_doc) self.assertEqual(answer.status_int, 200) # Check that was saved correctly customer_id = answer.json["id"] customer = self.db.get_customer(customer_id) self.assertEqual(customer["name"], customer_doc["name"]) self.assertEqual(customer["email"], customer_doc["email"]) self.assertEqual(customer["password"], helpers.encrypt_password(customer_doc["password"])) # Registration with same email answer = self.app.post("/api/customers", params=customer_doc, expect_errors=True) #self.assertEqual(answer.status_int, 400) # Registration with invalid email customer_doc = { "name": "Carlos Andrade", "email": "carlosfe.up.pt", "password": "******" } answer = self.app.post("/api/customers", params=customer_doc, expect_errors=True) self.assertEqual(answer.status_int, 400)
def register(): post_args = flask.request.get_json() # verify that a username and password was sent if post_args["username"] and post_args["password"]: username = post_args.get("username") password = post_args.get("password") else: return { "status": 401, "error": "Username or password is missing." }, 200 # authenticate the account conn = sqlite3.connect("db.db") c = conn.cursor() c.execute( "SELECT username FROM users WHERE username = '******'".format(username)) queried_user = c.fetchone() if queried_user: if queried_user[0] == username: return {"status": 401, "error": "That username is taken."}, 200 c.execute( "INSERT INTO users (username, password, settings) VALUES ('{}', '{}', '')" .format(username, encrypt_password(password))) conn.commit() conn.close() return {"status": 200}, 200
def authenticate(cls, username, password): try: user = cls.get(username=username, password=encrypt_password(password)) except cls.DoesNotExist: return False token = generate_token() set_cache(token, user.pk, config.SESSION_TIME) return token
def _publish_database_relation(relid, superuser): # The Casandra service needs to provide a common set of credentials # to a client unit. The leader creates these, if none of the other # units are found to have published them already (a previously elected # leader may have done this). The leader then tickles the other units, # firing a hook and giving them the opportunity to copy and publish # these credentials. username, password = _client_credentials(relid) if username is None: if hookenv.is_leader(): # Credentials not set. The leader must generate them. We use # the service name so that database permissions remain valid # even after the relation is dropped and recreated, or the # juju environment rebuild and the database restored from # backups. service_name = helpers.get_service_name(relid) if not service_name: # Per Bug #1555261, we might not yet have related units, # so no way to calculate the remote service name and thus # the user. return # Try again later. username = '******'.format(helpers.get_service_name(relid)) if superuser: username += '_admin' password = host.pwgen() pwhash = helpers.encrypt_password(password) with helpers.connect() as session: helpers.ensure_user(session, username, pwhash, superuser) # Wake the peers, if any. helpers.leader_ping() else: return # No credentials yet. Nothing to do. # Publish the information the client needs on the relation where # they can find it. # - authentication credentials # - address and port # - cluster_name, so clients can differentiate multiple clusters # - datacenter + rack, so clients know what names they can use # when altering keyspace replication settings. config = hookenv.config() hookenv.relation_set(relid, username=username, password=password, host=helpers.rpc_broadcast_ip_address(), native_transport_port=config['native_transport_port'], rpc_port=config['rpc_port'], cluster_name=config['cluster_name'], datacenter=config['datacenter'], rack=config['rack'])
def setup(args): # read all of the databases from the yaml file connections = get_connections( args.db_file) if args.db_file else get_connections() # make sure the directory that stores the credentials exists if (not os.path.isdir('./program_creds')): os.mkdir('./program_creds') # get the user's master password print('\nFirst things first, lets encrypt your passwords.\n') master_pass = input( 'Your passwords will be encrypted with a master password, type it in now: ' ) # store the if (str.lower( input( 'Would you like to store your master password in your OS\'s keychain? (y/n): ' )) == 'y'): keyring.set_password('socialchorus_query_tool', 'master_pass', master_pass) # get and encrypt the password for each database for conn, values in connections.items(): input_pass = input( f'\nEnter the password for the {conn} database or enter S to skip: ' ) # check if the user wants to skip setting up this database if (str.lower(input_pass) == 's'): continue # encrypt the password encrypted_pass = encrypt_password(input_pass, master_pass) creds_file_name = f'./program_creds/{values["db_name"]}_creds' # if the credentials file already exists ask if they want to create a new one if (os.path.isfile(creds_file_name)): if (str.lower( input( f'The credentials file for this database already exists, would you like to delete it and create a new one? (y/n): ' )) == 'y'): os.remove(creds_file_name) # create the file write the password to it so we can read it in when establishing connections with open(creds_file_name, 'wb') as f: f.write(encrypted_pass)
def create_customer(self, name, email, password): self.db.customers.ensure_index("email", unique=True) if not helpers.email_is_valid(email) or not helpers.name_is_valid(name) or not helpers.password_is_valid(password): return False encrypted_password = helpers.encrypt_password(password) customer_doc = { "name": name, "email": email, "password": encrypted_password, "auction": "" } try: result = self.db.customers.insert(customer_doc) except errors.DuplicateKeyError: result = False return result
def reset_default_password(): if hookenv.leader_get('default_admin_password_changed'): hookenv.log('Default admin password already changed') return # Cassandra ships with well known credentials, rather than # providing a tool to reset credentials. This is a huge security # hole we must close. try: # We need a big timeout here, as the cassandra user actually # springs into existence some time after Cassandra has started # up and is accepting connections. with helpers.connect('cassandra', 'cassandra', timeout=120, auth_timeout=120) as session: # But before we close this security hole, we need to use these # credentials to create a different admin account for the # leader, allowing it to create accounts for other nodes as they # join. The alternative is restarting Cassandra without # authentication, which this charm will likely need to do in the # future when we allow Cassandra services to be related together. helpers.status_set('maintenance', 'Creating initial superuser account') username, password = helpers.superuser_credentials() pwhash = helpers.encrypt_password(password) helpers.ensure_user(session, username, pwhash, superuser=True) helpers.set_unit_superusers([hookenv.local_unit()]) helpers.status_set('maintenance', 'Changing default admin password') helpers.query(session, 'ALTER USER cassandra WITH PASSWORD %s', cassandra.ConsistencyLevel.ALL, (host.pwgen(), )) except cassandra.AuthenticationFailed: hookenv.log('Default superuser account already reset') try: with helpers.connect(): hookenv.log("Leader's superuser account already created") except cassandra.AuthenticationFailed: # We have no known superuser credentials. Create the account # the hard, slow way. This will be the normal method # of creating the service's initial account when we allow # services to be related together. helpers.create_unit_superuser_hard() hookenv.leader_set(default_admin_password_changed=True)
def request_unit_superuser(): relid = helpers.peer_relid() if relid is None: hookenv.log('Request deferred until peer relation exists') return relinfo = hookenv.relation_get(unit=hookenv.local_unit(), rid=relid) if relinfo and relinfo.get('username'): # We must avoid blindly setting the pwhash on the relation, # as we will likely get a different value everytime we # encrypt the password due to the random salt. hookenv.log('Superuser account request previously made') else: # Publish the requested superuser and hash to our peers. username, password = helpers.superuser_credentials() pwhash = helpers.encrypt_password(password) hookenv.relation_set(relid, username=username, pwhash=pwhash) hookenv.log('Requested superuser account creation')
def test_create_customer(self): payload = self.customer1 r = requests.post("http://localhost:8080/api/customers", params=payload) answer = r.json() customer = data.get_customer(answer["id"]) self.assertEqual(customer["name"], payload["name"]) self.assertEqual(customer["email"], payload["email"]) self.assertEqual(customer["password"], helpers.encrypt_password(payload["password"])) self.assertEqual(customer["nif"], payload["nif"]) self.assertEqual(customer["creditCard"]["type"], payload["ccType"]) self.assertEqual(customer["creditCard"]["number"], payload["ccNumber"]) self.assertEqual(customer["creditCard"]["validity"], payload["ccValidity"]) self.assertEqual(customer["_id"], ObjectId(answer["id"])) self.assertEqual(customer["pin"], answer["pin"]) r = requests.post("http://localhost:8080/api/customers", params=payload) self.assertEqual(r.status_code, 400) data.delete_customer(answer["id"])
def _publish_database_relation(relid, superuser): # The Casandra service needs to provide a common set of credentials # to a client unit. The leader creates these, if none of the other # units are found to have published them already (a previously elected # leader may have done this). The leader then tickles the other units, # firing a hook and giving them the opportunity to copy and publish # these credentials. username, password = _client_credentials(relid) if username is None: if hookenv.is_leader(): # Credentials not set. The leader must generate them. We use # the service name so that database permissions remain valid # even after the relation is dropped and recreated, or the # juju environment rebuild and the database restored from # backups. username = '******'.format(helpers.get_service_name(relid)) if superuser: username += '_admin' password = host.pwgen() pwhash = helpers.encrypt_password(password) with helpers.connect() as session: helpers.ensure_user(session, username, pwhash, superuser) # Wake the peers, if any. helpers.leader_ping() else: return # No credentials yet. Nothing to do. # Publish the information the client needs on the relation where # they can find it. # - authentication credentials # - address and port # - cluster_name, so clients can differentiate multiple clusters # - datacenter + rack, so clients know what names they can use # when altering keyspace replication settings. config = hookenv.config() hookenv.relation_set(relid, username=username, password=password, host=hookenv.unit_public_ip(), native_transport_port=config['native_transport_port'], rpc_port=config['rpc_port'], cluster_name=config['cluster_name'], datacenter=config['datacenter'], rack=config['rack'])
def reset_default_password(): if hookenv.leader_get('default_admin_password_changed'): hookenv.log('Default admin password already changed') return # Cassandra ships with well known credentials, rather than # providing a tool to reset credentials. This is a huge security # hole we must close. try: # We need a big timeout here, as the cassandra user actually # springs into existence some time after Cassandra has started # up and is accepting connections. with helpers.connect('cassandra', 'cassandra', timeout=120, auth_timeout=120) as session: # But before we close this security hole, we need to use these # credentials to create a different admin account for the # leader, allowing it to create accounts for other nodes as they # join. The alternative is restarting Cassandra without # authentication, which this charm will likely need to do in the # future when we allow Cassandra services to be related together. helpers.status_set('maintenance', 'Creating initial superuser account') username, password = helpers.superuser_credentials() pwhash = helpers.encrypt_password(password) helpers.ensure_user(session, username, pwhash, superuser=True) helpers.set_unit_superusers([hookenv.local_unit()]) helpers.status_set('maintenance', 'Changing default admin password') helpers.query(session, 'ALTER USER cassandra WITH PASSWORD %s', cassandra.ConsistencyLevel.ALL, (host.pwgen(),)) except cassandra.AuthenticationFailed: hookenv.log('Default superuser account already reset') try: with helpers.connect(): hookenv.log("Leader's superuser account already created") except cassandra.AuthenticationFailed: # We have no known superuser credentials. Create the account # the hard, slow way. This will be the normal method # of creating the service's initial account when we allow # services to be related together. helpers.create_unit_superuser_hard() hookenv.leader_set(default_admin_password_changed=True)
def test_encrypt_password(self): config.PASSWORD_SALT = 'salt' self.assertEqual(encrypt_password('password'), 'd514dee5e76bbb718084294c835f312c')
def set_password(self, password): self.password = encrypt_password(password) self.save()
def add(cls, username, password, email=None): return cls.create(username=username, password=encrypt_password(password), email=email)