async def setPassword(self, username, password): """ !!!Admin add: must be protected when calling """ # Needs admin if self.read_only: raise Exception('LDAP in Read only mode') self.bind() user_dn = self.user_filter.format(username=username) hashed_password = hashed(HASHED_SHA512, password) done = self.ldap_conn_mng.modify( user_dn, {'userPassword': [(MODIFY_REPLACE, [hashed_password])]} ) result = self.parse_async_add(done) if result == 'success': return True else: return False
def reset_password(self, user, password, logout_sessions=False): from ldap3 import HASHED_SALTED_SHA, MODIFY_REPLACE from ldap3.utils.hashed import hashed search_filter = "({0}={1})".format(self.ldap_email_field, user) conn = self.connect_to_ldap(self.base_dn, self.get_password(raise_exception=False), read_only=False) if conn.search( search_base=self.ldap_search_path_user, search_filter=search_filter, attributes=self.get_ldap_attributes(), ): if conn.entries and conn.entries[0]: entry_dn = conn.entries[0].entry_dn hashed_password = hashed(HASHED_SALTED_SHA, safe_encode(password)) changes = { "userPassword": [(MODIFY_REPLACE, [hashed_password])] } if conn.modify(entry_dn, changes=changes): if logout_sessions: from frappe.sessions import clear_sessions clear_sessions(user=user, force=True) frappe.msgprint(_("Password changed successfully.")) else: frappe.throw(_("Failed to change password.")) else: frappe.throw( _("No Entry for the User {0} found within LDAP!").format( user)) else: frappe.throw(_("No LDAP User found for email: {0}").format(user))
def modify_password(self, uid, password): dn = "{}={},ou=People,{}".format(self.user_dn_flag, uid, self.base_dn) password = hashed(HASHED_SALTED_SHA, password) self.conn.modify(dn, {'userPassword': (MODIFY_REPLACE, password)}) return self.conn.result
server = Server( os.environ['DATALAYER_LDAP_HOST'], get_info=ALL, ) conn = Connection(server, os.environ['DATALAYER_LDAP_BIND'], os.environ['DATALAYER_LDAP_BIND_PWD'], auto_bind=True) dn = 'ou=users,dc=datalayer,dc=io' print('Adding dn {0}'.format(dn)) server.schema.object_classes['organizationalUnit'] conn.add(dn, 'organizationalUnit') server.schema.object_classes['inetOrgPerson'] hashed_password = hashed(HASHED_SALTED_SHA, os.environ['DATALAYER_PWD']) def add_user(user): print('Adding user {0}'.format(user)) conn.add(user, 'inetOrgPerson', { 'sn': 'datalayer', 'mail': '*****@*****.**' }) conn.modify(user, {'userPassword': [(MODIFY_REPLACE, [hashed_password])]}) add_user('cn=datalayer,ou=users,dc=datalayer,dc=io') add_user('cn=admin,ou=users,dc=datalayer,dc=io')
def verify_password(self, password, password_hash): hash_method = prog.match(password_hash).group(1) return hashed(hash_method, password) == password_hash
def hash_password(self, password): return hashed(app.config["LDAP_PREFERRED_HASH_METHOD"], password)
def hashPassword(randomPassword): hashedPassword = hashed(HASHED_SALTED_SHA, randomPassword) return hashedPassword
def set_password(self, raw_password): # Hook into the password system for creating an additional hash for use # with LDAP. super().set_password(raw_password) self.ldap_password = hashed(HASHED_SALTED_SHA512, raw_password)
from ldap3.utils.hashed import hashed from ldap3 import Server, Connection, HASHED_MD5 server = Server('ldap://127.0.0.1:389') DN = 'cn=admin,dc=dexter,dc=com,dc=br' ldap = Connection(server, DN, '4linux') if ldap.bind(): print('Conectado ao server LDAP') else: print('usuario ou senha invalidos') user = { 'cn': 'Diogo', 'sn': 'Dionisio', 'mail': '*****@*****.**', 'UserPassword': hashed(HASHED_MD5, '4linux') } objectClass = ['person', 'inetOrgPerson', 'OrganizationalPerson', 'top'] dn = 'mail={0},dc=dexter,dc=com,dc=br'.format(user['mail']) if ldap.add(dn, objectClass, user): print('usuario cadatrado com sucesso') else: print('problema ao cadastrar o usuario')
def forgot_password(): errors = [] body = request.get_json() username = body['username'] password = body['password'] password_confirm = body['password_confirm'] if (len(username) < 3): errors.append('Username must be of minimal length 3') if (len(password) < 5): errors.append('Password must be of minimal length 5') if password != password_confirm: errors.append('Password do not match') if len(errors) > 0: return jsonify({ 'success': False, "errors": errors, }) ldap_conn = Connection( ldap_server, ldap_bind, ldap_bind_pwd, auto_bind=True, ) user = '******'.format(username) ldap_user = ldap_conn.search( user, '(objectclass=inetOrgPerson)', attributes=ALL_ATTRIBUTES, ) if not ldap_user: # errors.append('Username `{}` is not available'.format(username)) return jsonify({'success': True}) user_att = ldap_conn.entries[0] logging.info(user_att) email = user_att.mail.value logging.info(email) token = str(uuid.uuid4()) hashed_password = hashed(HASHED_SALTED_SHA, password) res = ldap_conn.modify(user, { 'description': [(MODIFY_REPLACE, ['_t_' + token + '_' + hashed_password])] }) if not res: errors.append( 'Something went wrong. Please contact [email protected]') return jsonify({ 'success': res, 'errors': errors, }) smtp_server = smtplib.SMTP(host=smtp_host, port=int(smtp_port)) smtp_server.starttls() smtp_server.login(smtp_username, smtp_password) # hostname = 'https://' + os.getenv('DLAHOST') hostname = "https://datalayer.io" text = """Thanks for using for Datalayer! Someone has requested to change the password of your Datalayer account. If you have not created this request, just FORGET this mail. Please click the link below if you have made this request: {}/iam/forgotpassword/confirm?t={}&u={} Datalayer is currently an early-release service. We appreciate your feedback, questions and suggestions. As appropriate, we encourage you to use the Datalayer issue tracker or email our support team. Issue Tracker: https://github.com/datalayer/datalayer/issues Email Support: [email protected] You may find the following resources helpful as you familiarize yourself with Datalayer. User Guide: https://docs.datalayer.io/use Happy Data Analysis! Sincerely, The Datalayer Team. """.format(hostname, token, username) logging.info('Sending mail to {} with content {}:'.format(email, text)) msg = MIMEText(text) msg['Subject'] = '[Datalayer] Password Reset Request' msg['From'] = 'Datalayer <*****@*****.**>' msg['To'] = email smtp_server.send_message(msg) smtp_server.quit() return jsonify({'success': True})
def signup(): errors = [] body = request.get_json() logging.info(body) username = str(body['username']).lower() first_name = body['first_name'] family_name = body['family_name'] email = body['email'] password = body['password'] password_confirm = body['password_confirm'] if (len(username) < 3): errors.append('Username must be of minimal length 3') if (len(username) > 16): errors.append('Username must be of maximal length 16') if not re.match(USERNAME_REGEXP, username): errors.append( 'Username should only contain alphanumeric or underscore') if not re.match(MAIL_REGEXP, email): errors.append('Provide a valid email address') if (len(password) < 6): errors.append('Password must be of minimal length 6') if (len(password) > 20): errors.append('Password must be of maximal length 20') if password != password_confirm: errors.append('Password do not match') if username in reserved_usernames: errors.append('Username `{}` is reserved'.format(username)) ldap_conn = Connection( ldap_server, ldap_bind, ldap_bind_pwd, auto_bind=True, ) user = '******'.format(username) if len(username) > 0 and ldap_conn.search(user, '(objectclass=inetOrgPerson)'): errors.append('Username `{}` is not available'.format(username)) else: users = 'ou=users,dc=datalayer,dc=io' if len(username) > 0 and ldap_conn.search( users, '(&(objectclass=inetOrgPerson)(mail={}))'.format(email)): errors.append('Account is not available'.format(username)) if len(errors) > 0: return jsonify({ 'success': False, "errors": errors, }) ldap_conn.add(user, ['inetOrgPerson', 'organizationalPerson', 'person', 'top'], { 'uid': username, 'cn': first_name, 'sn': family_name, 'mail': email, }) token = str(uuid.uuid4()) hashed_password = hashed(HASHED_SALTED_SHA, password) res = ldap_conn.modify(user, { 'userPassword': [(MODIFY_REPLACE, '_t_' + token + '_' + hashed_password)] }) if not res: return jsonify({'success': False}) smtp_server = smtplib.SMTP(host=smtp_host, port=int(smtp_port)) smtp_server.starttls() smtp_server.login(smtp_username, smtp_password) # hostname = 'https://' + os.getenv('DLAHOST') hostname = "https://datalayer.io" text = """Thanks for signing up for Datalayer! Please click the link below to confirm activation of your Datalayer account: {}/iam/join/confirm?t={}&u={} Datalayer is currently an early-release service. We appreciate your feedback, questions and suggestions. As appropriate, we encourage you to use the Datalayer issue tracker or email our support team. Issue Tracker: https://github.com/datalayer/datalayer/issues Email Support: [email protected] You may find the following resources helpful as you familiarize yourself with Datalayer. User Guide: https://docs.datalayer.io/use Happy Data Analysis! Sincerely, The Datalayer Team. """.format(hostname, token, username) logging.info('Sending mail to {} with content {}:'.format(email, text)) msg = MIMEText(text) msg['Subject'] = '[Datalayer] A warm welcome from Datalayer' msg['From'] = 'Datalayer <*****@*****.**>' msg['To'] = email smtp_server.send_message(msg) smtp_server.quit() return jsonify({'success': True})
def set_user_password(self, uid, password): user_dn = self.find_user_dn(uid) hashed_pw = hashed(HASHED_SALTED_SHA, password) self.get_connection().modify( user_dn, {'userPassword': [(MODIFY_REPLACE, [hashed_pw])]})
if not ldap.bind(): print('Problemas ao se autenticar') exit(1) # cadastra o grupo com add, existem outras opções como modify ou delete # as classes são um lista, já o objeto em sí um dicionário ldap.add('ou=users,dc=example,dc=com', ['organizationalUnit'], {'ou' : 'users'}) # define um objeto mais complexo com um dicionário ldif = { 'cn': 'Developer', 'sn': 'Desenvolvedor', 'mail': '*****@*****.**', 'uidNumber': 10001, 'gidNumber': 10001, 'homeDirectory': '/srv/home/developer', 'uid': 'developer', 'userPassword' : hashed(HASHED_SHA, '4linux') } # define algumas classes em um dicionário object_classes = ['top', 'posixAccount', 'person', 'inetOrgPerson'] ldap.add('uid=developer,ou=users,dc=example,dc=com', object_classes, ldif) entries = ldap.search('dc=example,dc=com', '(objectclass=*)') # o filtro é obrigatório if entries: for entry in ldap.entries: print(entry)