// OptJWTAuth sets the username and password used to access the database
// using JWT authentication.
160231
func OptJWTAuth(username, password string) Option {
	return func(db *Database) {
		db.auth = &jwtAuth{username: username, password: password}
	}
}
388673
func (c *Itsyouonline) CreateJWTToken(scopes, auds []string) (string, error) {
	// build request
	url := strings.TrimSuffix(c.BaseURI, "/api")
	req, err := http.NewRequest("GET", url+"/v1/oauth/jwt", nil)
	if err != nil {
		return "", err
	}

	// set auth header
	if c.AuthHeader == "" {
		return "", fmt.Errorf("you need to create an oauth token in order to create JWT token")
	}

	req.Header.Set("Authorization", c.AuthHeader)

	// query params
	q := req.URL.Query()
	if len(scopes) > 0 {
		q.Add("scope", strings.Join(scopes, ","))
	}
	if len(auds) > 0 {
		q.Add("aud", strings.Join(auds, ","))
	}
	req.URL.RawQuery = q.Encode()

	// do the request
	rsp, err := c.client.Do(req)
	if err != nil {
		return "", err
	}
	defer rsp.Body.Close()

	if rsp.StatusCode != 200 {
		return "", fmt.Errorf("invalid response's status code :%v", rsp.StatusCode)
	}

	b, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		return "", err
	}
	return string(b), nil
}
116409
func newJWTAuthentication(userName, password string) httpAuthentication {
	return &jwtAuthentication{
		userName: userName,
		password: password,
	}
}
64242
func (mw *JWTMiddleware) LoginHandler(writer rest.ResponseWriter, request *rest.Request) {
	loginVals := login{}
	err := request.DecodeJsonPayload(&loginVals)

	if err != nil {
		mw.unauthorized(writer)
		return
	}

	if !mw.Authenticator(loginVals.Username, loginVals.Password) {
		mw.unauthorized(writer)
		return
	}

	token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))

	if mw.PayloadFunc != nil {
		for key, value := range mw.PayloadFunc(loginVals.Username) {
			token.Claims[key] = value
		}
	}

	token.Claims["id"] = loginVals.Username
	token.Claims["exp"] = time.Now().Add(mw.Timeout).Unix()
	if mw.MaxRefresh != 0 {
		token.Claims["orig_iat"] = time.Now().Unix()
	}
	tokenString, err := token.SignedString(mw.Key)

	if err != nil {
		mw.unauthorized(writer)
		return
	}

	writer.WriteJson(resultToken{Token: tokenString})
}
613942
func (client *Socket) ClientAuthPlain(username, password string) error {
	err := client.SetPlainUsername(username)
	if err == nil {
		err = client.SetPlainPassword(password)
	}
	return err
}
559134
func (app *App) JWTPass() string {
	pass := os.Getenv(jwtPass)
	if pass == "" {
		return "pass"
	}
	return pass
}
1188550
func (c *httpConnection) SetAuthentication(auth driver.Authentication) (driver.Connection, error) {
	var httpAuth httpAuthentication
	switch auth.Type() {
	case driver.AuthenticationTypeBasic:
		userName := auth.Get("username")
		password := auth.Get("password")
		httpAuth = newBasicAuthentication(userName, password)
	case driver.AuthenticationTypeJWT:
		userName := auth.Get("username")
		password := auth.Get("password")
		httpAuth = newJWTAuthentication(userName, password)
	case driver.AuthenticationTypeRaw:
		value := auth.Get("value")
		httpAuth = newRawAuthentication(value)
	default:
		return nil, driver.WithStack(fmt.Errorf("Unsupported authentication type %d", int(auth.Type())))
	}

	result, err := newAuthenticatedConnection(c, httpAuth)
	if err != nil {
		return nil, driver.WithStack(err)
	}
	return result, nil
}
897382
func (a *jwtAuthentication) Prepare(ctx context.Context, conn driver.Connection) error {
	// Prepare request
	r, err := conn.NewRequest("POST", "/_open/auth")
	if err != nil {
		return driver.WithStack(err)
	}
	r.SetBody(jwtOpenRequest{
		UserName: a.userName,
		Password: a.password,
	})

	// Perform request
	resp, err := conn.Do(ctx, r)
	if err != nil {
		return driver.WithStack(err)
	}
	if err := resp.CheckStatus(200); err != nil {
		return driver.WithStack(err)
	}

	// Parse response
	var data jwtOpenResponse
	if err := resp.ParseBody("", &data); err != nil {
		return driver.WithStack(err)
	}

	// Store token
	a.token = data.Token

	// Ok
	return nil
}
1145925
func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
	return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
		encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
		return r.SetHeaderParam("Authorization", "Basic "+encoded)
	})
}
23136
func JWT(username, sharedSecret string, now Now) (string, error) {
	token := &jwt.Token{
		Header: map[string]interface{}{
			"typ": "JWT",
			"alg": jwt.SigningMethodHS512.Alg(),
		},
		Claims: jwt.MapClaims{
			"username": username,
			"exp":      now().Add(time.Minute).Unix(),
		},
		Method: jwt.SigningMethodHS512,
	}
	return token.SignedString([]byte(sharedSecret))
}
1019434
func SignJWT(jwt ClientJWT, pk jose.JsonWebKey) (string, error) {
	signer, err := jose.NewSigner(jose.RS512, &pk)
	if err != nil {
		return "", errors.Annotate(err, "Couldn't create JWT Signer")
	}
	json, err := json.Marshal(jwt)
	if err != nil {
		return "", errors.Annotate(err, "Couldn't marshal the JWT")
	}
	jws, err := signer.Sign(json)
	if err != nil {
		return "", errors.Annotate(err, "Couldn't sign the JWT")
	}
	return jws.CompactSerialize()
}
1089419
func DefaultAuthorization(src *chronograf.Source) Authorizer {
	// Optionally, add the shared secret JWT token creation
	if src.Username != "" && src.SharedSecret != "" {
		return &BearerJWT{
			Username:     src.Username,
			SharedSecret: src.SharedSecret,
		}
	} else if src.Username != "" && src.Password != "" {
		return &BasicAuth{
			Username: src.Username,
			Password: src.Password,
		}
	}
	return &NoAuthorization{}
}
910760
func JWt(opts ...*SignOpts) fibre.MiddlewareFunc {
	return func(h fibre.HandlerFunc) fibre.HandlerFunc {
		return func(c *fibre.Context) error {

			var config *SignOpts

			switch len(opts) {
			case 0:
				return h(c)
			default:
				config = opts[0]
			}

			// This is a socket
			if c.IsSocket() {
				return h(c)
			}

			// No config has been set
			if len(config.Key) == 0 {
				return h(c)
			}

			head := c.Request().Header().Get(fibre.HeaderAuthorization)

			if head != "" && head[:6] == "Bearer" {

				token, err := jwt.Parse(head[7:], func(token *jwt.Token) (interface{}, error) {

					if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
						return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
					}

					return config.Key, nil

				})

				if err == nil && token.Valid {
					if config.Fnc != nil {
						if err := config.Fnc(c, token.Header, token.Claims.(jwt.MapClaims)); err != nil {
							return fibre.NewHTTPError(401)
						}
					}
					return h(c)
				}

			}

			return fibre.NewHTTPError(401)

		}
	}
}
472871
func BasicAuthEncode(username, password string) string {
	return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
573021
func initJWTAuthHandler() func(ctx *neptulon.ReqCtx) error {
	return func(ctx *neptulon.ReqCtx) error {
		// todo: this could rather send the remaining queue size for the client so client can disconnect if there is nothing else to do
		ctx.Res = client.ACK
		return ctx.Next()
	}
}
1097515
func decodeJWT(a ast.Value) (*JSONWebToken, error) {
	// Parse the JSON Web Token
	astEncode, err := builtins.StringOperand(a, 1)
	if err != nil {
		return nil, err
	}

	encoding := string(astEncode)
	if !strings.Contains(encoding, ".") {
		return nil, errors.New("encoded JWT had no period separators")
	}

	parts := strings.Split(encoding, ".")
	if len(parts) != 3 {
		return nil, fmt.Errorf("encoded JWT must have 3 sections, found %d", len(parts))
	}

	return &JSONWebToken{header: parts[0], payload: parts[1], signature: parts[2]}, nil
}
1022797
func (us UsersService) GetToken(username, password string, client Client) (string, error) {
	req := network.Request{
		Method:        "POST",
		Path:          "/oauth/token",
		Authorization: network.NewBasicAuthorization(client.ID, ""),
		Body: network.NewFormRequestBody(url.Values{
			"username":      []string{username},
			"password":      []string{password},
			"grant_type":    []string{"password"},
			"response_type": []string{"token"},
		}),
		AcceptableStatusCodes: []int{http.StatusOK},
	}

	resp, err := newNetworkClient(us.config).MakeRequest(req)
	if err != nil {
		return "", translateError(err)
	}

	var responseBody struct {
		AccessToken string `json:"access_token"`
	}
	err = json.Unmarshal(resp.Body, &responseBody)
	if err != nil {
		return "", MalformedResponseError{err}
	}

	return responseBody.AccessToken, nil
}