// LoginHandler can be used by clients to get a jwt token.
// Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
// Reply will be of the form {"token": "TOKEN"}.
175955
func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
	if mw.Authenticator == nil {
		mw.unauthorized(c, http.StatusInternalServerError, mw.HTTPStatusMessageFunc(ErrMissingAuthenticatorFunc, c))
		return
	}

	data, err := mw.Authenticator(c)

	if err != nil {
		mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
		return
	}

	// Create the token
	token := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
	claims := token.Claims.(jwt.MapClaims)

	if mw.PayloadFunc != nil {
		for key, value := range mw.PayloadFunc(data) {
			claims[key] = value
		}
	}

	expire := mw.TimeFunc().Add(mw.Timeout)
	claims["exp"] = expire.Unix()
	claims["orig_iat"] = mw.TimeFunc().Unix()
	tokenString, err := mw.signedString(token)

	if err != nil {
		mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrFailedTokenCreation, c))
		return
	}

	// set cookie
	if mw.SendCookie {
		maxage := int(expire.Unix() - time.Now().Unix())
		c.SetCookie(
			mw.CookieName,
			tokenString,
			maxage,
			"/",
			mw.CookieDomain,
			mw.SecureCookie,
			mw.CookieHTTPOnly,
		)
	}

	mw.LoginResponse(c, http.StatusOK, tokenString, expire)
}
666691
func WrapAuth(auth Authenticater, handle http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if auth.Authenticate(r) {
			handle(w, r)
		} else {
			w.WriteHeader(http.StatusUnauthorized)
		}
	}
}
239163
func (c *ContivClient) Login(username, password string) (*http.Response, []byte, error) {

	// login is only allowed over a secure channel
	if !c.isHTTPS() {
		return nil, nil, errors.New("login requires a https auth_proxy URL")
	}

	url := c.baseURL + LoginPath

	// create the POST payload for login
	lp := loginPayload{
		Username: username,
		Password: password,
	}

	payload, err := json.Marshal(lp)
	if err != nil {
		return nil, nil, err
	}

	// send the login POST request
	resp, err := c.httpClient.Post(url, "application/json", bytes.NewBuffer(payload))
	if err != nil {
		return nil, nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, nil, err
	}

	return resp, body, nil
}
319597
func JWTAuthentication(userName, password string) Authentication {
	return &userNameAuthentication{
		authType: AuthenticationTypeJWT,
		userName: userName,
		password: password,
	}
}
709193
func (c *Client) LoginUser(username, password string, user User) error {
	uri, _ := url.Parse("/1/login")
	params := url.Values{}
	params.Add("username", username)
	params.Add("password", password)
	uri.RawQuery = params.Encode()

	resp, err := c.doSimple("GET", uri.String())
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	c.trace("LoginUser", uri, string(body))
	// TODO(tmc): warn if not == .Zero() before populating?
	return json.Unmarshal(body, user)
}
771661
func (d *DNSProvider) login() (*response, error) {
	if d.config.AuthSid != "" {
		// already logged in
		return nil, nil
	}

	response, err := d.postRequest("login", url.Values{"api-key": {d.config.APIKey}})
	if err != nil {
		return response, err
	}

	if response == nil {
		return nil, fmt.Errorf("login returned nil response")
	}

	if response.AuthSid == "" {
		return response, fmt.Errorf("login did not return valid Auth-Sid")
	}

	d.config.AuthSid = response.AuthSid

	return response, nil
}
952589
func (c *Client) SignHandler() (string, error) {
	if err := c.condDiscovery(); err != nil {
		return "", err
	}
	if c.signHandler == "" {
		return "", ErrNoSigning
	}
	return c.signHandler, nil
}
1127476
func (a *Auth) Handler(h http.Handler) http.Handler {
	a.ensureDefaults()
	return &handler{Auth: a, handler: h}
}
679340
func (m *AuthMethod) callbackHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	// This code path is hit when user clicks "Deny" on consent page.
	q := r.URL.Query()
	errorMsg := q.Get("error")
	if errorMsg != "" {
		replyError(c, rw, errors.New("login error"), "OpenID login error: %s", errorMsg)
		return
	}

	// Validate inputs.
	code := q.Get("code")
	if code == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'code' parameter")
		return
	}
	stateTok := q.Get("state")
	if stateTok == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'state' parameter")
		return
	}
	state, err := validateStateToken(c, stateTok)
	if err != nil {
		replyError(c, rw, err, "Failed to validate 'state' token")
		return
	}

	// Revalidate "dest_url". It was already validate in loginHandler when
	// generating state token, but just in case.
	dest, err := normalizeURL(state["dest_url"])
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	// Callback URI is hardcoded in OAuth2 client config and must always point
	// to default version on GAE. Yet we want to support logging to non-default
	// versions that have different hostnames. Do some redirect dance here to pass
	// control to required version if necessary (so that it can set cookie on
	// non-default version domain). Same handler with same params, just with
	// different hostname. For most common case of signing in into default version
	// this code path is not triggered.
	if state["host_url"] != r.Host {
		// There's no Scheme in r.URL. Append one, otherwise url.String() returns
		// relative (broken) URL. And replace the hostname with desired one.
		url := *r.URL
		if m.Insecure {
			url.Scheme = "http"
		} else {
			url.Scheme = "https"
		}
		url.Host = state["host_url"]
		logging.Warningf(c, "Redirecting to callback URI on another host %q", url.Host)
		http.Redirect(rw, r, url.String(), http.StatusFound)
		return
	}

	// Use authorization code to grab user profile.
	cfg, err := fetchCachedSettings(c)
	if err != nil {
		replyError(c, rw, err, "Can't load OpenID settings - %s", err)
		return
	}
	uid, user, err := handleAuthorizationCode(c, cfg, code)
	if err != nil {
		replyError(c, rw, err, "Error when fetching user profile - %s", err)
		return
	}

	// Grab previous session from the cookie to close it once new one is created.
	prevSid, err := decodeSessionCookie(c, r)
	if err != nil {
		replyError(c, rw, err, "Error when decoding session cookie - %s", err)
		return
	}

	// Create session in the session store.
	expTime := clock.Now(c).Add(sessionCookieToken.Expiration)
	sid, err := m.SessionStore.OpenSession(c, uid, user, expTime)
	if err != nil {
		replyError(c, rw, err, "Error when creating the session - %s", err)
		return
	}
	(logging.Fields{"sid": sid}).Infof(c, "Opened a new session")

	// Kill previous session now that new one is successfully created.
	if prevSid != "" {
		(logging.Fields{"sid": prevSid}).Infof(c, "Closing the previous session")
		if err = m.SessionStore.CloseSession(c, prevSid); err != nil {
			replyError(c, rw, err, "Error when closing the session - %s", err)
			return
		}
	}

	// Set the cookies.
	cookie, err := makeSessionCookie(c, sid, !m.Insecure)
	if err != nil {
		replyError(c, rw, err, "Can't make session cookie - %s", err)
		return
	}
	http.SetCookie(rw, cookie)
	m.removeIncompatibleCookies(rw, r)

	// Redirect to the final destination page.
	logging.Infof(c, "Redirecting to %s", dest)
	http.Redirect(rw, r, dest, http.StatusFound)
}
326199
func NewAuthTokenHandler(tokenStorage session.Storage) func(http.Handler) http.Handler {
	return func(h http.Handler) http.Handler {
		return &authHandler{
			handler:    h,
			backend:    tokenStorage,
			contextKey: tokenKey,
			headerKey:  TokenHeader,
			mustAuth:   true,
		}
	}
}
33969
func (a *Authenticator) AddHandlers(mux *apiserverhttp.Mux) {
	h := &localLoginHandlers{
		authCtxt: a.authContext,
		finder:   a.statePool.SystemState(),
	}
	h.AddHandlers(mux)
}
1169604
func (b *BearerJWT) Token(username string) (string, error) {
	if b.Now == nil {
		b.Now = time.Now
	}
	return JWT(username, b.SharedSecret, b.Now)
}
376575
func LogHandler(h http.Handler, opts *LogOptions) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if _, ok := getStatusWriter(w); ok {
			// Self-awareness, logging handler already set up
			h.ServeHTTP(w, r)
			return
		}

		// Save the response start time
		st := time.Now()
		// Call the wrapped handler, with the augmented ResponseWriter to handle the status code
		stw := &statusResponseWriter{w, 0, ""}

		// Log immediately if requested, otherwise on exit
		if opts.Immediate {
			logRequest(stw, r, st, opts)
		} else {
			// Store original URL, may get modified by handlers (i.e. StripPrefix)
			stw.oriURL = r.URL.String()
			defer logRequest(stw, r, st, opts)
		}
		h.ServeHTTP(stw, r)
	}
}
1289304
func MainHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	// For now it only supports `GET`
	if r.Method != "GET" {
		return errors.ErrGenericNotFound.WithDetail(nil)
	}

	if _, err := w.Write([]byte("{}")); err != nil {
		return errors.ErrUnknown.WithDetail(err)
	}
	return nil
}
82842
func (h *authGlobalHandler) Handle(
	ctx types.Context,
	w http.ResponseWriter,
	req *http.Request,
	store types.Store) error {

	if h.config == nil {
		ctx.Debug("skipping global auth handler; empty auth config")
		return h.handler(ctx, w, req, store)
	}

	if len(h.config.Allow) == 0 && len(h.config.Deny) == 0 {
		ctx.Debug("skipping global auth handler; empty allow & deny lists")
		return h.handler(ctx, w, req, store)
	}

	tok, err := auth.ValidateAuthTokenWithReq(ctx, h.config, req)
	if err != nil {
		return err
	}

	if tok == nil {
		panic("token should never be nil here")
	}

	ctx.Debug("validated global security token")

	return h.handler(
		ctx.WithValue(context.AuthTokenKey, tok), w, req, store)
}
17686
func (c *Client) Login(ctx context.Context, user *url.Userinfo) error {
	req := internal.URL(c, internal.SessionPath).Request(http.MethodPost)

	if user != nil {
		if password, ok := user.Password(); ok {
			req.SetBasicAuth(user.Username(), password)
		}
	}

	return c.Do(ctx, req, nil)
}
81659
func handleAuthResponse(c packetConn) (bool, []string, error) {
	for {
		packet, err := c.readPacket()
		if err != nil {
			return false, nil, err
		}

		switch packet[0] {
		case msgUserAuthBanner:
			// TODO: add callback to present the banner to the user
		case msgUserAuthFailure:
			var msg userAuthFailureMsg
			if err := Unmarshal(packet, &msg); err != nil {
				return false, nil, err
			}
			return false, msg.Methods, nil
		case msgUserAuthSuccess:
			return true, nil, nil
		case msgDisconnect:
			return false, nil, io.EOF
		default:
			return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0])
		}
	}
}