// Captchaer is a middleware that maps a captcha.Captcha service into the Macaron handler chain.
// An single variadic captcha.Options struct can be optionally provided to configure.
// This should be register after cache.Cacher.
356570
func Captchaer(options ...Options) macaron.Handler {
	return func(ctx *macaron.Context, cache cache.Cache) {
		cpt := NewCaptcha(prepareOptions(options))
		cpt.store = cache

		if strings.HasPrefix(ctx.Req.URL.Path, cpt.URLPrefix) {
			var chars string
			id := path.Base(ctx.Req.URL.Path)
			if i := strings.Index(id, "."); i > -1 {
				id = id[:i]
			}
			key := cpt.key(id)

			// Reload captcha.
			if len(ctx.Query("reload")) > 0 {
				chars = cpt.genRandChars()
				if err := cpt.store.Put(key, chars, cpt.Expiration); err != nil {
					ctx.Status(500)
					ctx.Write([]byte("captcha reload error"))
					panic(fmt.Errorf("reload captcha: %v", err))
				}
			} else {
				if v, ok := cpt.store.Get(key).(string); ok {
					chars = v
				} else {
					ctx.Status(404)
					ctx.Write([]byte("captcha not found"))
					return
				}
			}

			if _, err := NewImage([]byte(chars), cpt.StdWidth, cpt.StdHeight, cpt.ColorPalette).WriteTo(ctx.Resp); err != nil {
				panic(fmt.Errorf("write captcha: %v", err))
			}
			return
		}

		ctx.Data["Captcha"] = cpt
		ctx.Map(cpt)
	}
}
359981
func (ctx *Context) AcceptCharset(preferred ...string) string {
	return negotiator.New(ctx.Req.Header).Charset(preferred...)
}
22360
func mapToUser(m map[string]interface{}) *User {
	user := User { }
	for k, v := range m {
		// ignore nil values
		if v == nil {
			continue
		}

		switch k {
		case "login"       : user.Login, _ = v.(string)
		case "type"        : user.Type, _ = v.(string)
		case "name"        : user.Name, _ = v.(string)
		case "email"       : user.Email, _ = v.(string)
		case "company"     : user.Company, _ = v.(string)
		case "location"    : user.Location, _ = v.(string)
		case "avatar_url"  : user.Avatar, _ = v.(string)
		case "gravatar_id" : user.GravatarId, _ = v.(string)
		case "html_url"    : user.Url, _ = v.(string)
		case "id"          :
			if id, ok := v.(float64); ok {
				user.ID = int64(id)
			}
		}
	}

	return &user
}
1127476
func (a *Auth) Handler(h http.Handler) http.Handler {
	a.ensureDefaults()
	return &handler{Auth: a, handler: h}
}
675168
func Matcher(p rpc.ReadPeeker) bool {
	b, err := p.Peek(1)
	return err == nil && b[0] == '{'
}
689165
func (a *cachedTokenAuthenticator) AuthenticateToken(ctx context.Context, token string) (*authenticator.Response, bool, error) {
	auds, _ := authenticator.AudiencesFrom(ctx)

	key := keyFunc(auds, token)
	if record, ok := a.cache.get(key); ok {
		return record.resp, record.ok, record.err
	}

	resp, ok, err := a.authenticator.AuthenticateToken(ctx, token)
	if !a.cacheErrs && err != nil {
		return resp, ok, err
	}

	switch {
	case ok && a.successTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.successTTL)
	case !ok && a.failureTTL > 0:
		a.cache.set(key, &cacheRecord{resp: resp, ok: ok, err: err}, a.failureTTL)
	}

	return resp, ok, err
}
874601
func (ref *Consumer) errorHandler(in <-chan error) {
	ref.Debug("errorHandler started ...")
	for {
		select {
		case err, more := <-in:
			if more {
				ref.Errorf("message error: %T, %v", err, err)
				ref.Config.RecvErrorChan <- err
			}
		case <-ref.closeChannel:
			ref.Debug("Canceling error handler")
			return
		}
	}
}
959682
func ErrorHandler(cb ErrHandler) Option {
	return func(o *Options) error {
		o.AsyncErrorCB = cb
		return nil
	}
}
965906
func (p *OAuth) Wrapper(e *echo.Echo, middlewares ...interface{}) {
	p.Config.GenerateProviders()

	g := e.Group(p.Config.Path, middlewares...)

	// set the mux path to handle the registered providers
	g.Get("/login/:provider", p.beginAuthHandler)

	authMiddleware := func(h echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(ctx echo.Context) error {
			user, err := p.completeAuthHandler(ctx)
			if err != nil {
				return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
			}
			ctx.Set(p.Config.ContextKey, user)
			return h.Handle(ctx)
		})
	}

	p.successHandlers = append([]interface{}{authMiddleware}, p.successHandlers...)
	lastIndex := len(p.successHandlers) - 1
	if lastIndex == 0 {
		g.Get("/callback/:provider", func(ctx echo.Context) error {
			return ctx.String(`Success Handler is not set`)
		}, p.successHandlers...)
	} else {
		g.Get("/callback/:provider", p.successHandlers[lastIndex], p.successHandlers[0:lastIndex]...)
	}
	// register the error handler
	if p.failHandler != nil {
		e.SetHTTPErrorHandler(p.failHandler)
	}
}
383718
func ErrorHandler(h utils.ErrorHandler) ConnLimitOption {
	return func(cl *ConnLimiter) error {
		cl.errHandler = h
		return nil
	}
}
65517
func (i *InputField) InputHandler() func(event *tcell.EventKey, setFocus func(p Primitive)) {
	return i.WrapInputHandler(func(event *tcell.EventKey, setFocus func(p Primitive)) {
		// Trigger changed events.
		currentText := i.text
		defer func() {
			if i.text != currentText && i.changed != nil {
				i.changed(i.text)
			}
		}()

		// Movement functions.
		home := func() { i.cursorPos = 0 }
		end := func() { i.cursorPos = len(i.text) }
		moveLeft := func() {
			iterateStringReverse(i.text[:i.cursorPos], func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
				i.cursorPos -= textWidth
				return true
			})
		}
		moveRight := func() {
			iterateString(i.text[i.cursorPos:], func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
				i.cursorPos += textWidth
				return true
			})
		}
		moveWordLeft := func() {
			i.cursorPos = len(regexp.MustCompile(`\S+\s*$`).ReplaceAllString(i.text[:i.cursorPos], ""))
		}
		moveWordRight := func() {
			i.cursorPos = len(i.text) - len(regexp.MustCompile(`^\s*\S+\s*`).ReplaceAllString(i.text[i.cursorPos:], ""))
		}

		// Add character function. Returns whether or not the rune character is
		// accepted.
		add := func(r rune) bool {
			newText := i.text[:i.cursorPos] + string(r) + i.text[i.cursorPos:]
			if i.accept != nil && !i.accept(newText, r) {
				return false
			}
			i.text = newText
			i.cursorPos += len(string(r))
			return true
		}

		// Process key event.
		switch key := event.Key(); key {
		case tcell.KeyRune: // Regular character.
			if event.Modifiers()&tcell.ModAlt > 0 {
				// We accept some Alt- key combinations.
				switch event.Rune() {
				case 'a': // Home.
					home()
				case 'e': // End.
					end()
				case 'b': // Move word left.
					moveWordLeft()
				case 'f': // Move word right.
					moveWordRight()
				default:
					if !add(event.Rune()) {
						return
					}
				}
			} else {
				// Other keys are simply accepted as regular characters.
				if !add(event.Rune()) {
					return
				}
			}
		case tcell.KeyCtrlU: // Delete all.
			i.text = ""
			i.cursorPos = 0
		case tcell.KeyCtrlK: // Delete until the end of the line.
			i.text = i.text[:i.cursorPos]
		case tcell.KeyCtrlW: // Delete last word.
			lastWord := regexp.MustCompile(`\S+\s*$`)
			newText := lastWord.ReplaceAllString(i.text[:i.cursorPos], "") + i.text[i.cursorPos:]
			i.cursorPos -= len(i.text) - len(newText)
			i.text = newText
		case tcell.KeyBackspace, tcell.KeyBackspace2: // Delete character before the cursor.
			iterateStringReverse(i.text[:i.cursorPos], func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
				i.text = i.text[:textPos] + i.text[textPos+textWidth:]
				i.cursorPos -= textWidth
				return true
			})
			if i.offset >= i.cursorPos {
				i.offset = 0
			}
		case tcell.KeyDelete: // Delete character after the cursor.
			iterateString(i.text[i.cursorPos:], func(main rune, comb []rune, textPos, textWidth, screenPos, screenWidth int) bool {
				i.text = i.text[:i.cursorPos] + i.text[i.cursorPos+textWidth:]
				return true
			})
		case tcell.KeyLeft:
			if event.Modifiers()&tcell.ModAlt > 0 {
				moveWordLeft()
			} else {
				moveLeft()
			}
		case tcell.KeyRight:
			if event.Modifiers()&tcell.ModAlt > 0 {
				moveWordRight()
			} else {
				moveRight()
			}
		case tcell.KeyHome, tcell.KeyCtrlA:
			home()
		case tcell.KeyEnd, tcell.KeyCtrlE:
			end()
		case tcell.KeyEnter, tcell.KeyTab, tcell.KeyBacktab, tcell.KeyEscape: // We're done.
			if i.done != nil {
				i.done(key)
			}
			if i.finished != nil {
				i.finished(key)
			}
		}
	})
}
584795
func renderErr(c *router.Context, err error) {
	status := grpcCodeToHTTP[grpc.Code(err)]
	if status == 0 {
		status = http.StatusInternalServerError
	}
	c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
	c.Writer.WriteHeader(status)
	templates.MustRender(c.Context, c.Writer, "pages/error.html", map[string]interface{}{
		"Message": err.Error(),
	})
}
505415
func FuncHandler(f func(io.Writer, *gomemcached.MCRequest) *gomemcached.MCResponse) RequestHandler {
	return funcHandler(f)
}
963379
func (i *InputField) SetMaskCharacter(mask rune) *InputField {
	i.maskCharacter = mask
	return i
}
982115
func (c *Captcha) CreateHTML() template.HTML {
	value, err := c.CreateCaptcha()
	if err != nil {
		panic(fmt.Errorf("fail to create captcha: %v", err))
	}
	return template.HTML(fmt.Sprintf(`<input type="hidden" name="%[1]s" value="%[2]s">
	<a class="captcha" href="javascript:" tabindex="-1">
		<img onclick="this.src=('%[3]s%[4]s%[2]s.png?reload='+(new Date()).getTime())" class="captcha-img" src="%[3]s%[4]s%[2]s.png">
	</a>`, c.FieldIdName, value, c.SubURL, c.URLPrefix))
}
535586
func (c *Captcha) randStr(size int, kind int) []byte {
	ikind, result := kind, make([]byte, size)
	isAll := kind > 2 || kind < 0
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < size; i++ {
		if isAll {
			ikind = rand.Intn(3)
		}
		scope, base := fontKinds[ikind][0], fontKinds[ikind][1]
		result[i] = uint8(base + rand.Intn(scope))
	}
	return result
}
292348
func (s LoginSession) NewCaptchaIden() (string, error) {
	req := &request{
		url: "https://www.reddit.com/api/new_captcha",
		values: &url.Values{
			"api_type": {"json"},
		},
		cookie:    s.cookie,
		useragent: s.useragent,
	}
	body, err := req.getResponse()
	if err != nil {
		return "", err
	}

	// Get the CAPTCHA iden from the JSON.
	type Response struct {
		JSON struct {
			Errors [][]string
			Data   struct {
				Iden string
			}
		}
	}

	r := new(Response)
	err = json.NewDecoder(body).Decode(r)
	if err != nil {
		return "", err
	}

	return r.JSON.Data.Iden, nil
}