Login via macaroons and generate and return new API keys.
556075
async def authenticate_with_macaroon(url, insecure=False):
    """"""
    executor = futures.ThreadPoolExecutor(max_workers=1)

    def get_token():
        client = httpbakery.Client()
        resp = client.request(
            'POST', '{}/account/?op=create_authorisation_token'.format(url),
            verify=not insecure)
        if resp.status_code == HTTPStatus.UNAUTHORIZED:
            # if the auteentication with Candid fails, an exception is raised
            # above so we don't get here
            raise MacaroonLoginNotSupported(
                'Macaroon authentication not supported')
        if resp.status_code != HTTPStatus.OK:
            raise LoginError('Login failed: {}'.format(resp.text))
        result = resp.json()
        return '{consumer_key}:{token_key}:{token_secret}'.format(**result)

    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(executor, get_token)
1257403
def _login(self, username, password, client_id, client_secret):
        """"""
        url = self.api_url + self.auth_token_url
        auth_string = '%s:%s' % (client_id, client_secret)
        authorization = base64.b64encode(auth_string.encode()).decode()
        headers = {
            'Authorization': "Basic " + authorization,
            'Content-Type': "application/x-www-form-urlencoded"
        }
        params = {
            'username': str(username),
            'password': str(password),
            # 'client_id': client_id,
            'grant_type': 'password',
            'response_type': 'token'
        }
        return self.session.post(url, params=params, headers=headers)
839450
def _login(self, username, password):
        """"""
        data = {
            'username': username,
            'password': password,
            'grant_type': 'password'
        }
        r = self.spark_api.oauth.token.POST(auth=('spark', 'spark'), data=data, timeout=self.timeout)
        self._check_error(r)
        return r.json()['access_token']
857526
private ApiKeyAuthenticationInfo createAuthenticationInfo(String authenticationId, ApiKey apiKey) {
        return new ApiKeyAuthenticationInfo(authenticationId, apiKey, getName());
    }
1142010
def from_credentials(credentials):
        
        return API(username=credentials.username, password=credentials.password,
                   database=credentials.database, session_id=credentials.session_id,
                   server=credentials.server)
78982
def login_required(obj):
    
    decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_authenticated())
    return wrap_object(obj, decorator)
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'))
972829
def login(options)
      out = nil
      post('/auth/login', options) do |resp|
        @access_token = resp.body['auth_token']
        out = Cryptoprocessing::User.new self, resp.data
        yield(resp) if block_given?
      end
      out
    end
943876
def _login(server, creds_file=None, api_key=None, silent=False):
    
    # fetch_api_key and check_version expect server to end in /
    if server[-1] != "/":
        server = server + "/"

    # creds file path setup
    if creds_file is None:
        creds_file = os.path.expanduser("~/.onecodex")

    # check if the creds file exists and is readable
    if not os.path.exists(creds_file):
        if silent:
            return None

        creds = {}
    elif not os.access(creds_file, os.R_OK):
        click.echo("Please check the permissions on {}".format(collapse_user(creds_file)), err=True)
        sys.exit(1)
    else:
        # it is, so let's read it!
        with open(creds_file, "r") as fp:
            try:
                creds = json.load(fp)
            except ValueError:
                click.echo(
                    "Your ~/.onecodex credentials file appears to be corrupted. "  # noqa
                    "Please delete it and re-authorize.",
                    err=True,
                )
                sys.exit(1)

        # check for updates if logged in more than one day ago
        last_update = creds.get("updated_at") or creds.get("saved_at")
        last_update = last_update if last_update else datetime.datetime.now().strftime(DATE_FORMAT)
        diff = datetime.datetime.now() - datetime.datetime.strptime(last_update, DATE_FORMAT)

        if diff.days >= 1:
            # if creds_file is old, check for updates
            upgrade_required, msg = check_version(__version__, server)
            creds["updated_at"] = datetime.datetime.now().strftime(DATE_FORMAT)

            try:
                json.dump(creds, open(creds_file, "w"))
            except Exception as e:
                if e.errno == errno.EACCES:
                    click.echo(
                        "Please check the permissions on {}".format(collapse_user(creds_file)),
                        err=True,
                    )
                    sys.exit(1)
                else:
                    raise

            if upgrade_required:
                click.echo("\nWARNING: {}\n".format(msg), err=True)

        # finally, give the user back what they want (whether silent or not)
        if silent:
            return creds.get("api_key", None)

        click.echo(
            "Credentials file already exists ({}). Logout first.".format(collapse_user(creds_file)),
            err=True,
        )
        return creds.get("email", None)

    # creds_file was not found and we're not silent, so prompt user to login
    email, api_key = login_uname_pwd(server, api_key=api_key)

    if api_key is None:
        click.echo(
            "We could not verify your credentials. Either you mistyped your email "
            "or password, or your account does not currently have API access. "
            "Please contact help@onecodex.com if you continue to experience problems."
        )
        sys.exit(1)

    creds.update(
        {
            "api_key": api_key,
            "saved_at": datetime.datetime.now().strftime(DATE_FORMAT),
            "updated_at": None,
            "email": email,
        }
    )

    try:
        json.dump(creds, open(creds_file, "w"))
    except Exception as e:
        if e.errno == errno.EACCES:
            click.echo("Please check the permissions on {}".format(creds_file), err=True)
            sys.exit(1)
        else:
            raise

    click.echo("Your ~/.onecodex credentials file was successfully created.", err=True)

    return email
640153
def login(self):
        """"""
        response = self.session.get(self.signin_url, verify=False)
        user_param, password_param = self._get_hashed_params(response.text)
        login_data = {
            user_param: self.config['username'],
            password_param: self.config['password'],
            'once': self._get_once(response.text),
            'next': '/'
        }
        headers = {'Referer': 'https://www.v2ex.com/signin'}
        self.session.post(self.signin_url, headers=headers, data=login_data)
229146
def new(cls,
            username,
            password=None,
            email=None,
            first_name="",
            last_name="",
            login_method=None,
            role="MEMBER"
            ):
        
        data = {
            "first_name": first_name,
            "last_name": last_name,
            "email": email
        }

        if not password:
            password = utils.generate_random_string()

        username = username.strip().lower()
        if "@" in username and not email:
            if not utils.is_email_valid(username):
                exceptions.AuthError(_("Invalid username"))
            data["email"] = username
        elif email:
            if not utils.is_email_valid(email):
                exceptions.AuthError(_("Invalid username"))

        if not utils.is_username_valid(username):
            exceptions.AuthError(_("Invalid username"))
        if not utils.is_password_valid(password):
            raise exceptions.AuthError(_("Password is invalid"))

        if cls.get_by_username(username):
            raise exceptions.AuthError(_("Username exists already"))
        _email = data.get("email")
        if _email:
            if cls.get_by_email(_email):
                raise exceptions.AuthError(_("Email address exists already"))

        role = AuthUserRole.get_by_name(role or "MEMBER")
        if not role:
            raise exceptions.AuthError(_("Invalid user role"))

        data.update({
            "username": username,
            "password_hash": cls.encrypt_password(password),
            "email_verified": False,
            "login_method": login_method,
            "role": role,
            "status": cls.STATUS_ACTIVE
        })
        user = cls.create(**data)
        user.reset_secret_key()
        return user
1328434
public function login($login, $api_key)
    {
        if (empty($login) || !is_string($login)) {
            throw new \InvalidArgumentException('Argument "login" cannot be empty and must be a string');
        }

        if (empty($login) || !is_string($api_key)) {
            throw new \InvalidArgumentException('Argument "api_key" cannot be empty and must be a string');
        }

        $this->auth = [
            'login'         => $login,
            'password_hash' => $api_key,
        ];
    }
446397
def _serialize_v1(self, macaroon):
        '''
        '''
        serialized = {
            'identifier': utils.convert_to_string(macaroon.identifier),
            'signature': macaroon.signature,
        }
        if macaroon.location:
            serialized['location'] = macaroon.location
        if macaroon.caveats:
            serialized['caveats'] = [
                _caveat_v1_to_dict(caveat) for caveat in macaroon.caveats
            ]
        return json.dumps(serialized)
406008
def authenticate(self, login, passcode):
        
        return login in self.store and self.store[login] == passcode
1136335
def _create_user(ctx):
    """"""

    username, passhash = _get_credentials(ctx.obj['username'],
                                          ctx.obj['password'],
                                          ctx.obj['db'])

    if ctx.obj['db'].objectmodels['user'].count({'name': username}) > 0:
        raise KeyError()

    new_user = ctx.obj['db'].objectmodels['user']({
        'uuid': str(uuid4()),
        'created': std_now()
    })

    new_user.name = username
    new_user.passhash = passhash

    return new_user
736987
def keys():
    """"""
    for admin in current_app.config['ADMIN_USERS']:
        try:
            db.get_db()  # init db on global app context
            keys = ApiKey.find_by_user(admin)
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
        else:
            for key in keys:
                click.echo('{:40} {}'.format(key.key, key.user))
889478
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except UPSError:
            _login(*args)
            return function(*args)
    return wrapped