Exemplo n.º 1
0
    def test_hashed_password(self, user='******'):
        old_password = '******'
        new_password = '******'

        update_password(user, new_password)

        auth = frappe.db.sql('''select `password`, `salt` from `__Auth`
			where doctype='User' and name=%s and fieldname="password"''',
                             user,
                             as_dict=True)[0]

        self.assertTrue(auth.password != new_password)
        self.assertTrue(auth.salt)

        # stored password = password(plain_text_password + salt)
        self.assertEquals(
            frappe.db.sql('select password(concat(%s, %s))',
                          (new_password, auth.salt))[0][0], auth.password)

        self.assertTrue(check_password(user, new_password))

        # revert back to old
        update_password(user, old_password)
        self.assertTrue(check_password(user, old_password))

        # shouldn't work with old password
        self.assertRaises(frappe.AuthenticationError, check_password, user,
                          new_password)
Exemplo n.º 2
0
    def test_hashed_password(self, user='******'):
        old_password = '******'
        new_password = '******'

        update_password(user, new_password)

        auth = frappe.db.sql('''select `password` from `__Auth`
			where doctype='User' and name=%s and fieldname="password"''',
                             user,
                             as_dict=True)[0]

        # is not plain text
        self.assertTrue(auth.password != new_password)

        # is valid hashing
        self.assertTrue(passlibctx.verify(new_password, auth.password))

        self.assertTrue(check_password(user, new_password))

        # revert back to old
        update_password(user, old_password)
        self.assertTrue(check_password(user, old_password))

        # shouldn't work with old password
        self.assertRaises(frappe.AuthenticationError, check_password, user,
                          new_password)
Exemplo n.º 3
0
	def find_by_credentials(cls, user_name: str, password: str, validate_password: bool = True):
		"""Find the user by credentials.

		This is a login utility that needs to check login related system settings while finding the user.
		1. Find user by email ID by default
		2. If allow_login_using_mobile_number is set, you can use mobile number while finding the user.
		3. If allow_login_using_user_name is set, you can use username while finding the user.
		"""

		login_with_mobile = cint(
			frappe.db.get_value("System Settings", "System Settings", "allow_login_using_mobile_number")
		)
		login_with_username = cint(
			frappe.db.get_value("System Settings", "System Settings", "allow_login_using_user_name")
		)

		or_filters = [{"name": user_name}]
		if login_with_mobile:
			or_filters.append({"mobile_no": user_name})
		if login_with_username:
			or_filters.append({"username": user_name})

		users = frappe.db.get_all("User", fields=["name", "enabled"], or_filters=or_filters, limit=1)
		if not users:
			return

		user = users[0]
		user["is_authenticated"] = True
		if validate_password:
			try:
				check_password(user["name"], password, delete_tracker_cache=False)
			except frappe.AuthenticationError:
				user["is_authenticated"] = False

		return user
Exemplo n.º 4
0
    def find_by_credentials(cls,
                            user_name: str,
                            password: str,
                            validate_password: bool = True):
        """Find the user by credentials.
		"""
        login_with_mobile = cint(
            frappe.db.get_value("System Settings", "System Settings",
                                "allow_login_using_mobile_number"))
        filter = {
            "mobile_no": user_name
        } if login_with_mobile else {
            "name": user_name
        }

        user = frappe.db.get_value("User",
                                   filters=filter,
                                   fieldname=['name', 'enabled'],
                                   as_dict=True) or {}
        if not user:
            return

        user['is_authenticated'] = True
        if validate_password:
            try:
                check_password(user_name, password)
            except frappe.AuthenticationError:
                user['is_authenticated'] = False

        return user
Exemplo n.º 5
0
    def test_set_password(self):
        from frappe.utils.password import check_password

        self.execute("bench --site {site} set-password Administrator test1")
        self.assertEqual(self.returncode, 0)
        self.assertEqual(check_password('Administrator', 'test1'),
                         'Administrator')
        # to release the lock taken by check_password
        frappe.db.commit()

        self.execute("bench --site {site} set-admin-password test2")
        self.assertEqual(self.returncode, 0)
        self.assertEqual(check_password('Administrator', 'test2'),
                         'Administrator')
Exemplo n.º 6
0
def pin_login(user, pin, device=None):
    """
  Login using the user's email and the quick login pin
  :param user: The active user
  :param pin: The quick login pin
  :param device: Clear all sessions of device
  """
    from frappe.sessions import clear_sessions
    login = LoginManager()

    if not frappe.cache().get_value(
            f'can_use_quick_login_pin', user=user, expires=True):
        login.fail('Quick Login PIN time expired', user=user)

    login.check_if_enabled(user)
    if not check_password(
            user, pin, doctype='User', fieldname='quick_login_pin'):
        login.fail('Incorrect password', user=user)

    login.login_as(user)
    login.resume = False
    login.run_trigger('on_session_creation')
    if device:
        clear_sessions(user, True, device)
    return frappe.session.user
Exemplo n.º 7
0
def get_token(user, pwd, expires_in=3600, expire_on=None, device=None):
    """
  Get the JWT Token
  :param user: The user in ctx
  :param pwd: Pwd to auth
  :param expires_in: number of seconds till expiry
  :param expire_on: yyyy-mm-dd HH:mm:ss to specify the expiry (deprecated)
  :param device: The device in ctx
  """
    if not frappe.db.exists("User", user):
        raise frappe.ValidationError(_("Invalide User"))

    from frappe.sessions import clear_sessions
    login = LoginManager()
    login.check_if_enabled(user)
    if not check_password(user, pwd):
        login.fail('Incorrect password', user=user)
    login.login_as(user)
    login.resume = False
    login.run_trigger('on_session_creation')
    _expires_in = 3600
    if cint(expires_in):
        _expires_in = cint(expires_in)
    elif expire_on:
        _expires_in = (get_datetime(expire_on) -
                       get_datetime()).total_seconds()

    token = get_bearer_token(user=user, expires_in=_expires_in)
    frappe.local.response["token"] = token["access_token"]
    frappe.local.response.update(token)
Exemplo n.º 8
0
	def check_password(self, user, pwd):
		"""check password"""
		try:
			# returns user in correct case
			return check_password(user, pwd)
		except frappe.AuthenticationError:
			self.fail('Incorrect password')
Exemplo n.º 9
0
def login(email, password):
	result = dict(
		success=False,
		msg="Internal Unhandled Error"
	)

	log("Are we still using this method?\n{0}".format(get_trace()))

	try:

		quotation = cart.get_cart_quotation()["doc"]

		user_doc = check_password(email, password)
		frappe.local.login_manager.login_as(email)
		frappe.set_user(email)
		user = frappe.get_doc("User", email)

		# move quotation to logged in user
		transfer_quotation_to_user(quotation, user)

		result["success"] = True
		result["msg"] = ""
		result["user"] = {
			"full_name": user.full_name,
			"name": user.name
		}
	except frappe.AuthenticationError as ex:
		result["success"] = False
		result["msg"] = str(ex)

	return result
Exemplo n.º 10
0
 def check_password(self, user, pwd):
     """check password"""
     try:
         # returns user in correct case
         return check_password(user, pwd)
     except frappe.AuthenticationError:
         self.fail('Incorrect password')
Exemplo n.º 11
0
	def check_password(self, user, pwd):
		"""check password"""
		try:
			# returns user in correct case
			return check_password(user, pwd)
		except frappe.AuthenticationError:
			self.update_invalid_login(user)
			self.fail('Incorrect password', user=user)
Exemplo n.º 12
0
 def check_password(self, user, pwd):
     """check password"""
     try:
         # returns user in correct case
         return check_password(user, pwd)
     except frappe.AuthenticationError:
         self.update_invalid_login(user)
         self.fail('Incorrect password', user=user)
Exemplo n.º 13
0
def check_credentials(user, password):
    if not user or not password:
        frappe.throw("Please provide credentials")
        return {'status': 'missing credentials'}

    user = check_password(user, password)
    if user:
        role = frappe.get_value("User", user, "pflanzenfreund_group")
        return {'status': 'OK', 'user': user, 'role': role}
    return {'status': 'failed'}
Exemplo n.º 14
0
def change_password(old_password, new_password):
  """
  Update the password when old password is given
  :param old_password: The old password of the User
  :param new_password: The new password to set for the user
  """
  from frappe.core.doctype.user.user import test_password_strength, handle_password_test_fail

  check_password(user=frappe.session.user, pwd=old_password)

  user = frappe.get_doc("User", frappe.session.user)
  user_data = (user.first_name, user.middle_name,
               user.last_name, user.email, user.birth_date)
  result = test_password_strength(new_password, '', None, user_data)
  feedback = result.get("feedback", None)

  if feedback and not feedback.get('password_policy_validation_passed', False):
    handle_password_test_fail(result)

  update_password(user.name, new_password)
  return True
Exemplo n.º 15
0
	def test_hashed_password(self, user='******'):
		old_password = '******'
		new_password = '******'

		update_password(user, new_password)

		auth = get_password_list(dict(doctype='User', name=user))[0]

		# is not plain text
		self.assertTrue(auth.password != new_password)

		# is valid hashing
		self.assertTrue(passlibctx.verify(new_password, auth.password))

		self.assertTrue(check_password(user, new_password))

		# revert back to old
		update_password(user, old_password)
		self.assertTrue(check_password(user, old_password))

		# shouldn't work with old password
		self.assertRaises(frappe.AuthenticationError, check_password, user, new_password)
Exemplo n.º 16
0
	def test_hashed_password(self, user='******'):
		old_password = '******'
		new_password = '******'

		update_password(user, new_password)

		auth = frappe.db.sql('''select `password` from `__Auth`
			where doctype='User' and name=%s and fieldname="password"''', user, as_dict=True)[0]

		# is not plain text
		self.assertTrue(auth.password != new_password)

		# is valid hashing
		self.assertTrue(passlibctx.verify(new_password, auth.password))

		self.assertTrue(check_password(user, new_password))

		# revert back to old
		update_password(user, old_password)
		self.assertTrue(check_password(user, old_password))

		# shouldn't work with old password
		self.assertRaises(frappe.AuthenticationError, check_password, user, new_password)
Exemplo n.º 17
0
	def test_hashed_password(self, user='******'):
		old_password = '******'
		new_password = '******'

		update_password(user, new_password)

		auth = frappe.db.sql('''select `password`, `salt` from `__Auth`
			where doctype='User' and name=%s and fieldname="password"''', user, as_dict=True)[0]

		self.assertTrue(auth.password != new_password)
		self.assertTrue(auth.salt)

		# stored password = password(plain_text_password + salt)
		self.assertEquals(frappe.db.sql('select password(concat(%s, %s))', (new_password, auth.salt))[0][0], auth.password)

		self.assertTrue(check_password(user, new_password))

		# revert back to old
		update_password(user, old_password)
		self.assertTrue(check_password(user, old_password))

		# shouldn't work with old password
		self.assertRaises(frappe.AuthenticationError, check_password, user, new_password)
Exemplo n.º 18
0
def get_token(user, pwd, expire_on=None, device=None):
  if not frappe.db.exists("User", user):
    raise frappe.ValidationError(_("Invalide User"))

  from frappe.sessions import clear_sessions
  login = LoginManager()
  login.check_if_enabled(user)
  if not check_password(user, pwd):
    login.fail('Incorrect password', user=user)
  login.login_as(user)
  login.resume = False
  login.run_trigger('on_session_creation')
  clear_sessions(user, True, device)
  if expire_on:
    frappe.flags.jwt_expire_on = expire_on
Exemplo n.º 19
0
def login_checkin(user, password, logged_in='False'):
    if logged_in == 'False':
        #Check user password. Will raise error if incorrect
        check_user = check_password(user, password)

    employee = frappe.db.get_value("Employee", {'user_id': user}, 'name')
    if employee:
        last_status = frappe.db.sql('''SELECT 
						log_type
					FROM 
						`tabEmployee Checkin` AS checkin 
					WHERE 
						checkin.employee=%(user)s
					ORDER BY time DESC LIMIT 1''', {"user": employee},
                                    as_dict=1)
        if len(last_status) > 0:
            if last_status[0].log_type == 'OUT':
                add_log_based_on_employee_field(employee,
                                                frappe.utils.now(),
                                                log_type='IN',
                                                employee_fieldname='name')
                return {"next_log": 'Check Out'}
            elif last_status[0].log_type == 'IN':
                add_log_based_on_employee_field(employee,
                                                frappe.utils.now(),
                                                log_type='OUT',
                                                employee_fieldname='name')
                #Get last two checkins
                logs = frappe.db.sql('''SELECT *
											FROM 
												`tabEmployee Checkin` 
											WHERE 
												employee=%(employee)s AND attendance IS NULL
											ORDER BY time DESC LIMIT 2''', {'employee': employee},
                                     as_dict=1)
                if len(logs) == 2:
                    mark_attendance_and_link_log(
                        logs,
                        'Present',
                        logs[1].time.strftime('%Y-%m-%d'),
                    )
                return {"next_log": 'Checkin'}
        else:
            add_log_based_on_employee_field(employee,
                                            frappe.utils.now(),
                                            log_type='IN',
                                            employee_fieldname='name')
            return {"next_log": 'Checkout'}
Exemplo n.º 20
0
def get_token(user, pwd, expire_on=None, device=None):
    """
  Get the JWT Token
  :param user: The user in ctx
  :param pwd: Pwd to auth
  :param expire_on: yyyy-mm-dd HH:mm:ss to specify the expiry
  :param device: The device in ctx
  """
    if not frappe.db.exists("User", user):
        raise frappe.ValidationError(_("Invalide User"))

    from frappe.sessions import clear_sessions
    login = LoginManager()
    login.check_if_enabled(user)
    if not check_password(user, pwd):
        login.fail('Incorrect password', user=user)
    login.login_as(user)
    login.resume = False
    login.run_trigger('on_session_creation')
    clear_sessions(user, True, device)
    if expire_on:
        frappe.flags.jwt_expire_on = expire_on
Exemplo n.º 21
0
def login(**kwards):
    data = json.loads(kwards['data'])
    if 'email' not in data or 'password' not in data:

        return {
            "status": {
                "message": "missing credentials",
                "success": False,
                "code": 422
            }
        }

    if 'udid' not in data:
        return {
            "status": {
                "message": "missing udid",
                "success": False,
                "code": 422
            }
        }

    email = data['email']
    password = data['password']
    udid = data['udid']
    log = frappe.get_doc({"doctype": "Api Log"})

    if not frappe.get_all("User", ['name'], filters={"email": email}):
        frappe.local.response['http_status_code'] = 403
        log.response = "Incorrect credentials"
        log.request = "login"
        log.flags.ignore_permissions = True
        log.insert()
        frappe.db.commit()

        return {
            "status": {
                "message": "Incorrect credentials",
                "success": False,
                "code": 403
            }
        }

    user_list = frappe.get_all("User", ['name'], filters={"email": email})
    user_doc = frappe.get_doc("User", user_list[0].name)
    user = None
    try:
        user = check_password(user_doc.name, password)

    except Exception, e:
        frappe.local.response['http_status_code'] = 403
        log.response = "password wrong"
        log.request = "login"
        log.flags.ignore_permissions = True
        log.insert()
        frappe.db.commit()

        return {
            "status": {
                "message": "Incorrect credentials",
                "success": False,
                "code": 401
            }
        }