Authenticates using username and domain key.
351175
def pre_auth(self, transport, account_name):
        
        auth_token = AuthToken()
        auth_token.account_name = account_name

        domain = util.get_domain(account_name)
        if domain == None:
            raise AuthException('Invalid auth token account')

        if domain in self.domains:
            domain_key = self.domains[domain]
        else:
            domain_key = None

        if domain_key == None:
            raise AuthException('Invalid domain key for domain %s' % domain)

        self.log.debug('Initialized domain key for account %s'
                      % account_name)

        expires = 0
        timestamp = int(time() * 1000)
        pak = hmac.new(domain_key, '%s|%s|%s|%s' %
                       (account_name, sconstant.E_NAME, expires, timestamp),
                       hashlib.sha1).hexdigest()

        attrs = {sconstant.A_BY: sconstant.V_NAME}
        account = SOAPpy.Types.stringType(data=account_name, attrs=attrs)

        attrs = {sconstant.A_TIMESTAMP: timestamp, sconstant.A_EXPIRES: expires}
        preauth = SOAPpy.Types.stringType(data=pak,
                                          name=sconstant.E_PREAUTH,
                                          attrs=attrs)

        params = {sconstant.E_ACCOUNT: account,
                  sconstant.E_PREAUTH: preauth}

        self.log.debug('Authenticating account %s using domain key'
                       % account_name)
        try:
            res = transport.invoke(zconstant.NS_ZIMBRA_ACC_URL,
                                   sconstant.AuthRequest,
                                   params,
                                   auth_token)
        except SoapException as exc:
            raise AuthException(unicode(exc), exc)

        auth_token.token = res.authToken
        auth_token.session_id = res.sessionId

        self.log.info('Authenticated account %s, session id %s'
                      % (account_name, auth_token.session_id))

        return auth_token
647839
def create_authentication_string(username, password):
    '''
    
    '''

    username_utf8 = username.encode('utf-8')
    userpw_utf8 = password.encode('utf-8')
    username_perc = quote(username_utf8)
    userpw_perc = quote(userpw_utf8)

    authinfostring = username_perc + ':' + userpw_perc
    authinfostring_base64 = base64.b64encode(authinfostring.encode('utf-8')).decode('utf-8')
    return authinfostring_base64
356275
def authenticate(username, password, permission=None):
    
    try:
        author = Author.objects.get(
            **{'%s__exact' % Author.USERNAME_FIELD: username})
    except Author.DoesNotExist:
        raise Fault(LOGIN_ERROR, _('Username is incorrect.'))
    if not author.check_password(password):
        raise Fault(LOGIN_ERROR, _('Password is invalid.'))
    if not author.is_staff or not author.is_active:
        raise Fault(PERMISSION_DENIED, _('User account unavailable.'))
    if permission:
        if not author.has_perm(permission):
            raise Fault(PERMISSION_DENIED, _('User cannot %s.') % permission)
    return author
1179825
def authenticate_with_credentials(username, password, offering_id=nil)
      body = {:grant_type => 'password', :client_id => api_key, :client_secret => api_secret, :username => username, :password => password}
      body[:offering_id] = offering_id if offering_id.present?

      response = @oauth_connection.post do |req|
        req.url '/oauth/token'
        req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        req.body = body
      end

      @oauth_token = OAuthToken.new(response.body)
      configure_oauth
      @oauth_token
    end
713272
def _Authenticate(self):
		""""""
		super(HttpRpcServer, self)._Authenticate()
		if self.save_cookies:
			StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
			self.cookie_jar.save()
205837
def authenticate(self, username, password):
        
        # If username is an email address, then try to pull it up
        user = self.get_by_username_or_email(username)

        if not user:
            return None

        if user.check_password(password):
            return user

        return None
1256230
def _authenticate_user(self, user, password):
        
        headers = self._get_headers()
        params = {
                'username': user,
                'password': password,
                'grant_type': 'password',
                }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate %s" % (user))
            response.raise_for_status()
990960
def authenticate_user(self, response, **kwargs):
        """"""

        host = urlparse(response.url).hostname

        try:
            auth_header = self.generate_request_header(response, host)
        except KerberosExchangeError:
            # GSS Failure, return existing response
            return response

        log.debug("authenticate_user(): Authorization header: {0}".format(
            auth_header))
        response.request.headers['Authorization'] = auth_header

        # Consume the content so we can reuse the connection for the next
        # request.
        response.content
        response.raw.release_conn()

        _r = response.connection.send(response.request, **kwargs)
        _r.history.append(response)

        log.debug("authenticate_user(): returning {0}".format(_r))
        return _r
245414
def authenticate(self, user, password):
        """"""
        assert user['password_hash'] == '_'.join((password, 'hash'))
        self.logger.debug('User %s has been successfully authenticated',
                          user['uid'])
1301684
@Override
    public Principal authenticate(String username, String credentials) {
        GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
        if (null != principal) {
            try {
                if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
                    principal = null;
                }
            } catch (CannotPerformOperationException | InvalidHashException e) {
                LOGR.log(Level.WARNING, e.getMessage());
                principal = null;
            }
        }
        return principal;
    }
225885
public T authentication(String username, String password) {
        return authentication(username, password, false);
    }
543534
@Override
  public Access authenticate() {
    try {
      JSONObject user = new JSONObject();
      user.put("id", mUserId);
      user.put("password", mPassword);
      JSONObject password = new JSONObject();
      password.put("user", user);
      JSONArray methods = new JSONArray();
      methods.add("password");
      JSONObject identity = new JSONObject();
      identity.put("methods", methods);
      identity.put("password", password);
      JSONObject project = new JSONObject();
      project.put("id", mProjectId);
      JSONObject scope = new JSONObject();
      scope.put("project", project);
      JSONObject auth = new JSONObject();
      auth.put("identity", identity);
      auth.put("scope", scope);
      JSONObject requestBody = new JSONObject();
      requestBody.put("auth", auth);
      HttpURLConnection connection =
          (HttpURLConnection) new URL(mAuthUrl).openConnection();
      connection.setDoOutput(true);
      connection.setRequestProperty("Accept", "application/json");
      connection.setRequestProperty("Content-Type", "application/json");
      OutputStream output = connection.getOutputStream();
      output.write(requestBody.toString().getBytes());
      HttpStatusChecker.verifyCode(STATUS_CHECKERS, connection.getResponseCode());
      final String res;
      try (final BufferedReader bufReader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        res = bufReader.readLine();
      }
      JSONParser parser = new JSONParser();
      JSONObject jsonResponse = (JSONObject) parser.parse(res);

      String token = connection.getHeaderField("X-Subject-Token");
      PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token,
          mPrefferedRegion);
      connection.disconnect();
      return access;
    } catch (IOException | ParseException e) {
      LOG.error(e.getMessage());
      throw new CommandException("Unable to execute the HTTP call or to convert the HTTP Response",
              e);
    }
  }
1259392
def authenticate(self):
        """"""
        valid = self._session_check()
        if self._is_authenticated and valid:
            self._log.debug("[!] User has already authenticated")
            return
        init = self._session.get(url=self.LOGIN_URL, headers=self.HEADERS)
        soup = BeautifulSoup(init.content, "html.parser")
        soup_login = soup.find('form').find_all('input')
        post_data = dict()
        for u in soup_login:
            if u.has_attr('name') and u.has_attr('value'):
                post_data[u['name']] = u['value']
        post_data['Email'] = self._email
        post_data['Passwd'] = self._password
        response = self._session.post(url=self.AUTH_URL, data=post_data,
                                      headers=self.HEADERS)
        if self.CAPTCHA_KEY in str(response.content):
            raise AccountCaptcha('Google is forcing a CAPTCHA. To get around this issue, run the google-alerts with the seed option to open an interactive authentication session. Once authenticated, this module will cache your session and load that in the future')
        cookies = [x.name for x in response.cookies]
        if 'SIDCC' not in cookies:
            raise InvalidCredentials("Email or password was incorrect.")
        with open(SESSION_FILE, 'wb') as f:
            cookies = requests.utils.dict_from_cookiejar(self._session.cookies)
            pickle.dump(cookies, f, protocol=2)
            self._log.debug("Saved session to disk for future reference")
        self._log.debug("User successfully authenticated")
        self._is_authenticated = True
        self._process_state()
        return
447451
public static boolean authenticate(String userName, String userPassword) {
        LOGGER.entering(userName, StringUtils.isBlank(userPassword) ? userPassword : userPassword.replaceAll(".", "*"));
        boolean validLogin = false;
        byte[] currentAuthData;
        byte[] hashedInputData;
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(userPassword)) {
            return validLogin;
        }
        try {
            File authFile = new File(AUTH_FILE_LOCATION);
            if (!authFile.exists()) {
                authFile.createNewFile();
                createAuthFile(authFile, DEFAULT_USERNAME, DEFAULT_PASSWORD);
            }
            currentAuthData = getBytesFromFile(authFile);
            hashedInputData = hashData(userName, userPassword);
            validLogin = Arrays.equals(currentAuthData, hashedInputData);
        } catch (Exception e) {
            validLogin = false;
        }
        LOGGER.exiting(validLogin);
        return validLogin;
    }
485600
def authenticate(self, request, **credentials):
        
        username = credentials.get('username')
        password = credentials.get('password')
        login_server = credentials.get('login_server')
        port = credentials.get('port')

        user_model = get_user_model()
        try:
            user = user_model.objects.get(username=username)
        except user_model.DoesNotExist:
            return None
        try:
            response = poplib.POP3_SSL(host=login_server, port=port)
            response.user(user=username)
            password_string = response.pass_(pswd=password)
            if b'OK' in password_string:
                response.quit()
                return user
        except poplib.error_proto:
            return None
        except (ValueError, TypeError) as e:
            raise e
470706
def authenticate(cls, request, route, server_config):
        
        if not server_config.getboolean("auth", False):
            return

        user = server_config.get("user", "").strip()
        password = server_config.get("password", "").strip()

        if len(user) == 0:
            return

        if "AUTHORIZATION" in request.headers:
            if request.headers["AUTHORIZATION"] == aiohttp.helpers.BasicAuth(user, password, "utf-8").encode():
                return

        log.error("Invalid auth. Username should %s", user)

        response = Response(request=request, route=route)
        response.set_status(401)
        response.headers["WWW-Authenticate"] = 'Basic realm="GNS3 server"'
        # Force close the keep alive. Work around a Qt issue where Qt timeout instead of handling the 401
        # this happen only for the first query send by the client.
        response.force_close()
        return response
593914
def authenticate(self):  # pylint: disable=too-many-locals
        
        mapping_override = self.config.resolve('lexicon:auto:mapping_override')
        mapping_override_processed = {}
        if mapping_override:
            for one_mapping in mapping_override.split(','):
                one_mapping_processed = one_mapping.split(':')
                mapping_override_processed[one_mapping_processed[0]
                                           ] = one_mapping_processed[1]

        override_provider = mapping_override_processed.get(self.domain)
        if override_provider:
            provider = [
                element for element in AVAILABLE_PROVIDERS.items()
                if element[0] == override_provider][0]
            LOGGER.info('Provider authoritatively mapped for domain %s: %s.',
                        self.domain, provider.__name__)
            (provider_name, provider_module) = provider
        else:
            (provider_name, provider_module) = _relevant_provider_for_domain(self.domain)
            LOGGER.info('Provider discovered for domain %s: %s.',
                        self.domain, provider_name)

        new_config = ConfigResolver()
        new_config.with_dict({'lexicon:provider_name': provider_name})

        target_prefix = 'auto_{0}_'.format(provider_name)
        for config_source in self.config._config_sources:  # pylint: disable=protected-access
            if not isinstance(config_source, ArgsConfigSource):
                new_config.with_config_source(config_source)
            else:
                # ArgsConfigSource needs to be reprocessed to rescope the provided
                # args to the delegate provider
                new_dict = {}
                for key, value in config_source._parameters.items():  # pylint: disable=protected-access
                    if key.startswith(target_prefix):
                        new_param_name = re.sub(
                            '^{0}'.format(target_prefix), '', key)
                        new_dict['lexicon:{0}:{1}'.format(
                            provider_name, new_param_name)] = value
                    elif not key.startswith('auto_'):
                        new_dict['lexicon:{0}'.format(key)] = value
                new_config.with_dict(new_dict)

        self.proxy_provider = provider_module.Provider(new_config)
        self.proxy_provider.authenticate()