Checking authentication.

@throws ConnectionException if user name or password is not correct or
unable to retrieve logged in member.
962060
public void checkAuthentication() throws ConnectionException {
        IServices services = new Services(createMetaModel(),
        	populateHeaders(new V1APIConnector(getApplicationURL() + "rest-1.v1/",
                        username, password, ApiClientInternals.getProxyProvider(proxySettings))));
        Oid loggedin;

        try {
            loggedin = services.getLoggedIn();
        } catch (Exception ex) {
            throw new ConnectionException(
                    "Unable to log in. Incorrect username or password.", ex);
        }

        if (loggedin.isNull()) {
            throw new ConnectionException(
                    "Unable to retrieve logged in member.");
        }
    }
277979
protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws
            SecurityProviderException, IOException {
        Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
        // If user is anonymous, authentication is required
        if (auth == null) {
            try {
                // Throw ex just to initialize stack trace
                throw new AuthenticationRequiredException("Authentication required to access the resource", e);
            } catch (AuthenticationRequiredException ae) {
                logger.debug("Authentication is required", ae);

                authenticationRequiredHandler.handle(context, ae);
            }
        } else {
            logger.debug("Access denied to user '" + auth.getProfile().getUsername() + "'", e);

            accessDeniedHandler.handle(context, e);
        }
    }
589980
public function onRestorePassword()
    {
        $rules = [
            'email' => 'required|email|between:6,255'
        ];

        $validation = Validator::make(post(), $rules);
        if ($validation->fails()) {
            throw new ValidationException($validation);
        }

        $user = UserModel::findByEmail(post('email'));
        if (!$user || $user->is_guest) {
            throw new ApplicationException(Lang::get(/*A user was not found with the given credentials.*/'rainlab.user::lang.account.invalid_user'));
        }

        $code = implode('!', [$user->id, $user->getResetPasswordCode()]);

        $link = $this->makeResetUrl($code);

        $data = [
            'name' => $user->name,
            'link' => $link,
            'code' => $code
        ];

        Mail::send('rainlab.user::mail.restore', $data, function($message) use ($user) {
            $message->to($user->email, $user->full_name);
        });
    }
1182545
private function checkConnect(): void
    {
        if (empty($this->connect['type']) ||
            empty($this->connect['host']) ||
            empty($this->connect['name']) ||
            empty($this->connect['user'])
        ) {
            throw new ConfigurationException(
                'Database adapter is not configured.
                Please check `db` configuration section: required type, host, db name and user'
            );
        }
    }
651746
public function isLogged()
    {
        $this->byPassIsLogged = true;
        try {
            // Is a session mechanism available?
            if (!session_id()) {
                if ($this->sessionManager) {
                    $this->sessionManager->start();
                } else {
                    throw new MoufException("The session must be initialized before checking if the user is logged. Please use session_start().");
                }
            }
            
            if (isset($_SESSION[$this->sessionPrefix.'MoufUserId'])) {
                return true;
            } else {
                foreach ($this->authProviders as $provider) {
                    /* @var $provider AuthenticationProviderInterface */
                    if ($provider->isLogged($this)) {
                        return true;
                    }
                }
            }
        } catch (\Exception $e) {
            $this->byPassIsLogged = false;
            throw $e;
        }
        $this->byPassIsLogged = false;
        return false;
    }
919238
protected function authenticateSetup()
    {
        $exception = null;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($this->tableName)) {
            $exception = 'A table must be supplied for the DbTable authentication adapter.';
        } /** @noinspection IsEmptyFunctionUsageInspection */ elseif (empty($this->identityColumn)) {
            $exception = 'An identity column must be supplied for the DbTable authentication adapter.';
        } /** @noinspection IsEmptyFunctionUsageInspection */ elseif (empty($this->credentialColumn)) {
            $exception = 'A credential column must be supplied for the DbTable authentication adapter.';
        }

        if (null !== $exception) {
            throw new Exception\RuntimeException($exception);
        }

        $this->setup();

        return true;
    }
75472
private function assertUserIsLoggedIn()
    {
        $token = $this->securityContext->getToken();

        $isAuthenticated = $token !== null &&
                           $token->isAuthenticated() && 
                           $token->getUser() instanceof User &&
                           $token->getUser()->isCredentialsNonExpired();

        if(!$isAuthenticated){
            throw new AccessDeniedException();
        }
    }
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);
    }
  }
66172
public void authenticate() {
    if (mAccount == null) {
      // Create account also performs authentication.
      createAccount();
    } else {
      mAccess = mAccount.authenticate();
      if (mRegion != null) {
        mAccess.setPreferredRegion(mRegion);
      }
    }
  }
1253160
def authentication(self, event):
        """"""

        try:
            self.log("Authorization has been granted by DB check:",
                     event.username, lvl=debug)

            account, profile, clientconfig = event.userdata

            useruuid = event.useruuid
            originatingclientuuid = event.clientuuid
            clientuuid = clientconfig.uuid

            if clientuuid != originatingclientuuid:
                self.log("Mutating client uuid to request id:",
                         clientuuid, lvl=network)
            # Assign client to user
            if useruuid in self._users:
                signedinuser = self._users[useruuid]
            else:
                signedinuser = User(account, profile, useruuid)
                self._users[account.uuid] = signedinuser

            if clientuuid in signedinuser.clients:
                self.log("Client configuration already logged in.",
                         lvl=critical)
                # TODO: What now??
                # Probably senseful would be to add the socket to the
                # client's other socket
                # The clients would be identical then - that could cause
                # problems
                # which could be remedied by duplicating the configuration
            else:
                signedinuser.clients.append(clientuuid)
                self.log("Active client (", clientuuid, ") registered to "
                                                        "user", useruuid,
                         lvl=debug)

            # Update socket..
            socket = self._sockets[event.sock]
            socket.clientuuid = clientuuid
            self._sockets[event.sock] = socket

            # ..and client lists

            try:
                language = clientconfig.language
            except AttributeError:
                language = "en"

            # TODO: Rewrite and simplify this:
            newclient = Client(
                sock=event.sock,
                ip=socket.ip,
                clientuuid=clientuuid,
                useruuid=useruuid,
                name=clientconfig.name,
                config=clientconfig,
                language=language
            )

            del (self._clients[originatingclientuuid])
            self._clients[clientuuid] = newclient

            authpacket = {"component": "auth", "action": "login",
                          "data": account.serializablefields()}
            self.log("Transmitting Authorization to client", authpacket,
                     lvl=network)
            self.fireEvent(
                write(event.sock, json.dumps(authpacket)),
                "wsserver"
            )

            profilepacket = {"component": "profile", "action": "get",
                             "data": profile.serializablefields()}
            self.log("Transmitting Profile to client", profilepacket,
                     lvl=network)
            self.fireEvent(write(event.sock, json.dumps(profilepacket)),
                           "wsserver")

            clientconfigpacket = {"component": "clientconfig", "action": "get",
                                  "data": clientconfig.serializablefields()}
            self.log("Transmitting client configuration to client",
                     clientconfigpacket, lvl=network)
            self.fireEvent(write(event.sock, json.dumps(clientconfigpacket)),
                           "wsserver")

            self.fireEvent(userlogin(clientuuid, useruuid, clientconfig, signedinuser))

            self.log("User configured: Name",
                     signedinuser.account.name, "Profile",
                     signedinuser.profile.uuid, "Clients",
                     signedinuser.clients,
                     lvl=debug)

        except Exception as e:
            self.log("Error (%s, %s) during auth grant: %s" % (
                type(e), e, event), lvl=error)
690147
public function auth() {

        try {
            $this->authResponse = $this->authAdapterInterface->authenticate();
        } catch (\Exception $ex) {
            throw $ex;
        }

        $message = $this->authResponse->getMessage();

        if ($message->getCode() == AuthResponse::AUTHRESPONSE_SUCCESS) {
            $this->session->set($message->getKeysession(), $message->getAttrsession());
        }

        return;
    }
712512
protected void checkAuthenticatedAccount(UserIdentityContext userIdentityContext) {
        if (userIdentityContext.getEffectiveAccount() == null) {
            throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic realm=\"Restcomm realm\"").build());
        }
    }
257708
@Override
    public synchronized void authenticate() throws PortalSecurityException {
        this.isauth = false;
        ILdapServer ldapConn;

        ldapConn = LdapServices.getDefaultLdapServer();

        String creds = new String(this.myOpaqueCredentials.credentialstring);
        if (this.myPrincipal.UID != null
                && !this.myPrincipal.UID.trim().equals("")
                && this.myOpaqueCredentials.credentialstring != null
                && !creds.trim().equals("")) {
            DirContext conn = null;
            NamingEnumeration results = null;
            StringBuffer user = new StringBuffer("(");
            String first_name = null;
            String last_name = null;

            user.append(ldapConn.getUidAttribute()).append("=");
            user.append(this.myPrincipal.UID).append(")");
            log.debug("SimpleLdapSecurityContext: Looking for {}", user.toString());

            try {
                conn = ldapConn.getConnection();

                // set up search controls
                SearchControls searchCtls = new SearchControls();
                searchCtls.setReturningAttributes(attributes);
                searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

                // do lookup
                if (conn != null) {
                    try {
                        results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                        if (results != null) {
                            if (!results.hasMore()) {
                                log.error(
                                        "SimpleLdapSecurityContext: user not found: {}",
                                        this.myPrincipal.UID);
                            }
                            while (results != null && results.hasMore()) {
                                SearchResult entry = (SearchResult) results.next();
                                StringBuffer dnBuffer = new StringBuffer();
                                dnBuffer.append(entry.getName()).append(", ");
                                dnBuffer.append(ldapConn.getBaseDN());
                                Attributes attrs = entry.getAttributes();
                                first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                                last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                                // re-bind as user
                                conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                                conn.removeFromEnvironment(
                                        javax.naming.Context.SECURITY_CREDENTIALS);
                                conn.addToEnvironment(
                                        javax.naming.Context.SECURITY_PRINCIPAL,
                                        dnBuffer.toString());
                                conn.addToEnvironment(
                                        javax.naming.Context.SECURITY_CREDENTIALS,
                                        this.myOpaqueCredentials.credentialstring);
                                searchCtls = new SearchControls();
                                searchCtls.setReturningAttributes(new String[0]);
                                searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                                String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                                log.debug(
                                        "SimpleLdapSecurityContext: Looking in {} for {}",
                                        dnBuffer.toString(),
                                        attrSearch);
                                conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                                this.isauth = true;
                                this.myPrincipal.FullName = first_name + " " + last_name;
                                log.debug(
                                        "SimpleLdapSecurityContext: User {} ({}) is authenticated",
                                        this.myPrincipal.UID,
                                        this.myPrincipal.FullName);

                                // Since LDAP is case-insensitive with respect to uid, force
                                // user name to lower case for use by the portal
                                this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                            } // while (results != null && results.hasMore())
                        } else {
                            log.error(
                                    "SimpleLdapSecurityContext: No such user: {}",
                                    this.myPrincipal.UID);
                        }
                    } catch (AuthenticationException ae) {
                        log.info(
                                "SimpleLdapSecurityContext: Password invalid for user: "
                                        + this.myPrincipal.UID);
                    } catch (Exception e) {
                        log.error(
                                "SimpleLdapSecurityContext: LDAP Error with user: "
                                        + this.myPrincipal.UID
                                        + "; ",
                                e);
                        throw new PortalSecurityException(
                                "SimpleLdapSecurityContext: LDAP Error"
                                        + e
                                        + " with user: "
                                        + this.myPrincipal.UID);
                    } finally {
                        ldapConn.releaseConnection(conn);
                    }
                } else {
                    log.error("LDAP Server Connection unavailable");
                }
            } catch (final NamingException ne) {
                log.error("Error getting connection to LDAP server.", ne);
            }
        } else {
            // If the principal and/or credential are missing, the context authentication
            // simply fails. It should not be construed that this is an error. It happens for guest
            // access.
            log.info("Principal or OpaqueCredentials not initialized prior to authenticate");
        }
        // Ok...we are now ready to authenticate all of our subcontexts.
        super.authenticate();
        return;
    }
579269
protected UserDetails authenticateUser(String username, String password, HttpRequest authRequest) throws AuthenticationException {
        UserDetails userDetails;
        IUserAuthentication ua;
        if (OAuthConfig.getUserAuthenticationClass() != null) {
            try {
                ua = OAuthConfig.getUserAuthenticationClass().newInstance();
                userDetails = ua.authenticate(username, password, authRequest);
            } catch (InstantiationException | IllegalAccessException e) {
                LOG.error("cannot instantiate user authentication class", e);
                throw new AuthenticationException(e.getMessage());
            }
        } else {
            // if no specific UserAuthentication used, always returns customerId - 12345
            userDetails = new UserDetails("12345", null);
        }
        return userDetails;
    }
564169
public static function CheckAuthentication(){
            $oThis = self::CreateInstanceIfNotExists();
            $bReturn = ($oThis->bStarted) ? (!empty($oThis->aAuth["id"]) && !empty($oThis->aAuth["username"]) && ((intval($oThis->aAuth["timeout"]) > time()) || (intval($oThis->aAuth["timeout"]) <= 0))) : false;
            return $bReturn;
        }
675895
protected function onAuthenticationFailure(AuthenticationRequiredException $exception = null)
    {
        if ($this->view instanceof JsonView) {
            $this->view->assign('value', ['success' => false]);
        } else {
            $this->addFlashMessage('The entered username or password was wrong', 'Wrong credentials', Message::SEVERITY_ERROR, [], ($exception === null ? 1347016771 : $exception->getCode()));
        }
    }
618406
public Connection getConnection(String username, String password)
            throws SQLException {
        throw new SQLException(Resources.getMessage("NOT_SUPPORTED"));
    }