Logs a user in by parsing a POST request containing user credentials and
    issuing a JWT token.

    .. example::
       $ curl http://localhost:5000/login -X POST \
         -d '{"username":"Walter","password":"calmerthanyouare"}'
779292
def login():
    
    req = flask.request.get_json(force=True)
    username = req.pop('username', None)
    password = req.pop('password', None)

    user = guard.authenticate(username, password)
    ret = {'access_token': guard.encode_jwt_token(
        user,
        firstname=user.firstname,
        nickname=user.nickname,
        surname=user.surname,
    )}

    return (flask.jsonify(ret), 200)
836623
function parseAuth(auth) {
	if (auth && typeof auth === 'string') {
		var authObject = {
			username: auth.split(':')[0],
			password: auth.split(':')[1]
		};
		return authObject;
	} else {
		return auth;
	}
}
384170
def auth(username, password):
    '''
    
    '''

    url = rest_auth_setup()

    data = {'username': username, 'password': password}

    # Post to the API endpoint. If 200 is returned then the result will be the ACLs
    # for this user
    result = salt.utils.http.query(url, method='POST', data=data, status=True,
                                   decode=True)
    if result['status'] == 200:
        log.debug('eauth REST call returned 200: %s', result)
        if result['dict'] is not None:
            return result['dict']
        return True
    else:
        log.debug('eauth REST call failed: %s', result)
        return False
145423
function post_login(urlStr, username, password, token, next) {

    assert(_.isFunction(next));

    var p = url.parse(urlStr);


    var http_protocol;
    if (p.protocol === "https:") {
        http_protocol = https;
    } else {
        http_protocol = http;
    }

    var options = {
        host: p.hostname,
        path: url.resolve(p.pathname, "login"),
        method: "POST",
        user_agent: "Mozilla/5.0"

    };

    var req = http_protocol.request(options, function (res) {
        // console.log('STATUS: ' + res.statusCode);
        // console.log('HEADERS: ' + JSON.stringify(res.headers,null," "));

        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            //xx data += chunk
        });
        res.on('end', function () {


            var selected_elements = res.headers["set-cookie"].filter(function (str) {
                //  1234567890123456
                return str.substr(0, 16) === "_redmine_session";
            });

            assert(selected_elements.length === 1);
            var _cookie_session = selected_elements[0] + "; domain=" + p.hostname;
            next(null, _cookie_session);
        });
    });

    req.on('error', function (err) {
        console.log('problem with request: '.red + err.message);
        next(err);
    });

    // write data to request body
    req.write("username=" + username + "&password=" + password + "&authenticity_token=" + token + "\n");
    req.end();

}
1040914
def login(self):
        
        auth_data = dict()
        auth_data['apikey'] = self.api_key
        auth_data['username'] = self.username
        auth_data['userkey'] = self.account_identifier

        auth_resp = requests_util.run_request('post', self.API_BASE_URL + '/login', data=json.dumps(auth_data),
                                              headers=self.__get_header())

        if auth_resp.status_code == 200:
            auth_resp_data = self.parse_raw_response(auth_resp)
            self.__token = auth_resp_data['token']
            self.__auth_time = datetime.now()
            self.is_authenticated = True
        else:
            raise AuthenticationFailedException('Authentication failed!')
286258
function Login(callback)
	{
		Log("Making OAuth Request...");
		// start OAuth request (use our internal GET function as this is different!)
		_URLGET(
			// URL
			urls.login_base + "/2.0/oauth/authorize",
			// query string
			GetOAuthData({
				response_type: "code",
				service_entity: "urn:service-entity:psn",
				returnAuthCode: true,
				state: "1156936032"
			}),
			// headers
			{
				'User-Agent': ParseStaches(useragent)
			},
			function(err, body, response)
			{
				if (err)
				{
					// return login error
					if (callback) callback(err);
					return;
				}
				else
				{
					// get the login path
					var login_referrer = response.req.path;

					Log("Logging in...");

					// now actually login using the previous URL as the referrer
					request(
						{
							url: urls.login_base + "/login.do",
							method: "POST",
				            headers:
				            {
				            	'User-Agent': ParseStaches(useragent),
				            	'X-Requested-With': headers["X-Requested-With"],
				                'Origin': 'https://auth.api.sonyentertainmentnetwork.com',
				                'Referer': login_referrer,
				            },
				            form:
				            {
				                'params': new Buffer(login_params).toString('base64'),
				                'j_username': login_details.email,
				                'j_password': login_details.password
				            }
			        	},
				        function (err, response, body)
				        {
				        	if (err)
				        	{
				        		// login failed
				        		Log("Failed to make login request");
				        		if (callback) callback(err);
				        		return;
				        	}
				        	else
				        	{
					        	Log("Following login...");
					        	
					            request.get(response.headers.location, function (err, response, body)
					            {
					                if (!err)
					                {
					                	// parse URL
					                	var result = url.parse(response.req.path, true);
					                	if (result.query.authentication_error)
					                	{
					                		// try to extract login error from website
					                		var error_message = /errorDivMessage\"\>\s*(.*)\<br \/\>/.exec(body);
					                		if (error_message && error_message[1])
					                		{
					                			Log("Login failed! Error from Sony: " + error_message[1]);
					                			if (callback) callback(error_message[1]);
					                		}
					                		else
					                		{
												Log("Login failed!");
								        		if (callback) callback("Login failed!");
								        	}

							        		return;
					                	}
					                	else
					                	{
					                		// no auth error!
					                		var auth_result = url.parse(result.query.targetUrl, true);
					                		if (auth_result.query.authCode)
					                		{
					                			Log("Got auth code: " + auth_result.query.authCode);
					                			auth_obj.auth_code = auth_result.query.authCode;
					                			if (callback) callback(false);
					                			return;
					                		}
					                		else
					                		{
					                			Log("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
								        		if (callback) callback("Auth error " + auth_result.query.error_code + ": " + auth_result.query.error_description);
								        		return;
					                		}
					                	}
					                }
					                else
					                {
					                    Log("Auth code fetch error: " + err);
					                    if (callback) callback(err);
					                    return;
					                }
					            });
					        }
				        }
				    );
				}
			}
		);
	}
655172
def login(self, user_id, password):
        

        self._session = requests.session()
        self._session.verify = self._verify_certs
        self._session.auth = (user_id, password)

        try:
            self._update_capabilities()

            url_components = parse.urlparse(self.url)
            if self._dav_endpoint_version == 1:
                self._davpath = url_components.path + 'remote.php/dav/files/' + parse.quote(user_id)
                self._webdav_url = self.url + 'remote.php/dav/files/' + parse.quote(user_id)
            else:
                self._davpath = url_components.path + 'remote.php/webdav'
                self._webdav_url = self.url + 'remote.php/webdav'

        except HTTPResponseError as e:
            self._session.close()
            self._session = None
            raise e
1367709
def auth_token(self, apikey=None, secret=None, email=None, password=None):
        
        if (apikey and secret) or (self._apikey and self._secret):
            body = {
                "key_id": apikey or self._apikey,
                "secret": secret or self._secret
            }
        elif (email and password) or (self._email and self._password):
            body = {
                "user" : email or self._email,
                "password" : password or self._password
            }
        else:
            raise Value("No authentication provided.")
        response = self._post(url.auth, body=body)

        self._check_response(response, 200)
        return self._create_response(response).get("jwt")
720433
function _loginCallback (privateDirectoryUrl, publicUrl, jwksClient, cookieName, cookieDomain) {
  return asyncWrap(async (req, res, next) => {
    // Get a JWT in a id_token query parameter = coming from a link in an email
    const linkToken = req.query.id_token
    if (linkToken) {
      const cookies = new Cookies(req, res)
      try {
        debug(`Verify JWT token from the query parameter`)
        await _verifyToken(jwksClient, linkToken)
        debug('JWT token from query parameter is ok, exchange it for a long term session token')
        const exchangedToken = await _exchangeToken(privateDirectoryUrl, linkToken)
        const payload = await _verifyToken(jwksClient, exchangedToken)
        debug('Exchanged token is ok, store it', payload)
        _setCookieToken(cookies, cookieName, cookieDomain, exchangedToken, payload)
      } catch (err) {
        // Token expired or bad in another way..
        // TODO: a way to display warning to user ? throw error ?
        debug('JWT token from query parameter is broken', err)
      }
      const reloadUrl = new URL(publicUrl + req.originalUrl)
      reloadUrl.searchParams.delete('id_token')
      debug('Reload current page without id_token query parameter', reloadUrl.toString())
      return res.redirect(reloadUrl.toString())
    }
    next()
  })
}
324102
def login(self, username, password):
        '''
        '''
        response = self.request(
            ACCESS_TOKEN,
            {
                'x_auth_mode': 'client_auth',
                'x_auth_username': username,
                'x_auth_password': password
            },
            returns_json=False
        )
        token = dict(parse_qsl(response['data'].decode()))
        self.token = oauth.Token(
            token['oauth_token'], token['oauth_token_secret'])
        self.oauth_client = oauth.Client(self.consumer, self.token)
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()
563376
def login(self, identity, credentials):
        '''
        '''
        result = self.dispatcher.session.post(self._url('v0/auth/login'),
                                              json={
                                                  'email': identity,
                                                  'password': credentials
                                              })
        status = result.status_code
        if status == 400:
            raise APIException('invalid parameters, login process has changed')
        elif status == 401:
            # do our best to get something out to the user
            msg = result.text
            try:
                msg = json.loads(result.text)['message']
            finally:
                raise InvalidIdentity(msg)
        elif status != 200:
            raise APIException('%s: %s' % (status, result.text))
        jwt = result.text
        payload = jwt.split('.')[1]
        rem = len(payload) % 4
        if rem > 0:
            payload += '=' * (4 - rem)
        payload = base64.urlsafe_b64decode(payload.encode('utf-8'))
        return json.loads(payload.decode('utf-8'))
1114522
async def login(self, client_name, request, redirect_uri=None, **params):
        
        client = self.client(client_name, logger=self.app.logger)

        redirect_uri = redirect_uri or self.cfg.redirect_uri or '%s://%s%s' % (
            request.scheme, request.host, request.path)
        session = await self.app.ps.session(request)

        if isinstance(client, OAuth1Client):
            oauth_verifier = request.query.get('oauth_verifier')
            if not oauth_verifier:

                # Get request credentials
                token, secret = await client.get_request_token(
                    oauth_callback=redirect_uri)

                # Save the credentials in current user session
                session['oauth_token'] = token
                session['oauth_token_secret'] = secret

                url = client.get_authorize_url()
                raise muffin.HTTPFound(url)

            # Check request_token
            oauth_token = request.query.get('oauth_token')
            if session['oauth_token'] != oauth_token:
                raise muffin.HTTPForbidden(reason='Invalid token.')

            client.oauth_token = oauth_token
            client.oauth_token_secret = session.get('oauth_token_secret')

            # Get access tokens
            return client, await client.get_access_token(oauth_verifier)

        if isinstance(client, OAuth2Client):
            code = request.query.get('code')
            if not code:

                # Authorize an user
                state = sha1(str(random()).encode('ascii')).hexdigest()
                session['oauth_secret'] = state
                url = client.get_authorize_url(
                    redirect_uri=redirect_uri, state=state, **params)
                raise muffin.HTTPFound(url)

            # Check state
            state = request.query.get('state')
            oauth_secret = session.pop('oauth_secret', '')
            if oauth_secret != state:
                raise muffin.HTTPForbidden(reason='Invalid token "%s".' % oauth_secret)

            # Get access token
            return client, await client.get_access_token(code, redirect_uri=redirect_uri)

        return client
869380
def auth(self, user=None, password=None, jsonp=None):
        
        if not user:
            user = self.user
        if not password:
            password = self.password
        parameters = {
                      'username' : self.user,
                      'password' : self.password
                     }
        if jsonp is not None:
            parameters['jsonp'] = jsonp
        status, headers = self._query(self.authurl, parameters)
        # return the callback call if we want jsonp
        if jsonp is not None:
            return status
        return (int(status), self.auth_status_codes[int(status)])
300137
async def fetch_token(self):
        """"""
        url = '{}/login'.format(API_URL)
        payload = 'email={}&password={}'.format(self._email, self._password)

        reg = await self.api_post(url, None, payload)
        if reg is None:
            _LOGGER.error('Unable to authenticate and fetch eight token.')
        else:
            self._userid = reg['session']['userId']
            self._token = reg['session']['token']
            self._expdate = reg['session']['expirationDate']
            _LOGGER.debug('UserID: %s, Token: %s', self._userid, self.token)
175299
def login(self, username, password):
        
        response = self.session.post(
            os.path.join(self.identity_url, 'certlogin'),
            cert=self.cert_file,
            data=urllib.urlencode({
                'username': username,
                'password': password,
            }),
            headers={
                'X-Application': self.app_key,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            timeout=self.timeout,
        )
        utils.check_status_code(response, [httplib.OK])
        data = response.json()
        if data.get('loginStatus') != 'SUCCESS':
            raise exceptions.LoginError(response, data)
        self.session_token = data['sessionToken']
868288
def authenticate_credentials(self, token: bytes, request=None):
        
        user = AuthToken.get_user_for_token(token)

        if user is None:
            raise AuthenticationFailed(_('Invalid auth token.'))

        if not user.is_active:
            raise AuthenticationFailed(_('User inactive or deleted.'))

        return user, token