{{.i18n.Tr "notification.notifications"}}
diff --git a/tools/fuzz.go b/tools/fuzz.go
index b48ae0add944..ca35ff4f0082 100644
--- a/tools/fuzz.go
+++ b/tools/fuzz.go
@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/markup/markdown"
+ "code.gitea.io/gitea/modules/setting"
)
// Contains fuzzing functions executed by
@@ -32,6 +33,7 @@ var (
)
func FuzzMarkdownRenderRaw(data []byte) int {
+ setting.AppURL = "http://localhost:3000/"
err := markdown.RenderRaw(&renderContext, bytes.NewReader(data), io.Discard)
if err != nil {
return 0
@@ -40,6 +42,7 @@ func FuzzMarkdownRenderRaw(data []byte) int {
}
func FuzzMarkupPostProcess(data []byte) int {
+ setting.AppURL = "http://localhost:3000/"
err := markup.PostProcess(&renderContext, bytes.NewReader(data), io.Discard)
if err != nil {
return 0
diff --git a/vendor/gitea.com/lunny/levelqueue/queue.go b/vendor/gitea.com/lunny/levelqueue/queue.go
index 0570cc572dc6..328769d2bd2a 100644
--- a/vendor/gitea.com/lunny/levelqueue/queue.go
+++ b/vendor/gitea.com/lunny/levelqueue/queue.go
@@ -21,8 +21,8 @@ const (
// Queue defines a queue struct
type Queue struct {
db *leveldb.DB
- highLock sync.Mutex
- lowLock sync.Mutex
+ lowLock sync.Mutex // If you are locking both high and low locks, lock the low lock before the high lock
+ highLock sync.Mutex // If you are locking both high and low locks, lock the low lock before the high lock
low int64
high int64
lowKey []byte
@@ -295,6 +295,11 @@ func (queue *Queue) LHandle(h func([]byte) error) error {
// Close closes the queue (and the underlying db is set to closeUnderlyingDB)
func (queue *Queue) Close() error {
+ queue.lowLock.Lock()
+ queue.highLock.Lock()
+ defer queue.lowLock.Unlock()
+ defer queue.highLock.Unlock()
+
if !queue.closeUnderlyingDB {
queue.db = nil
return nil
diff --git a/vendor/gitea.com/lunny/levelqueue/set.go b/vendor/gitea.com/lunny/levelqueue/set.go
index f5995cb8f1cf..7e0e65c554f5 100644
--- a/vendor/gitea.com/lunny/levelqueue/set.go
+++ b/vendor/gitea.com/lunny/levelqueue/set.go
@@ -107,6 +107,8 @@ func (set *Set) Remove(value []byte) (bool, error) {
// Close closes the set (and the underlying db if set to closeUnderlyingDB)
func (set *Set) Close() error {
+ set.lock.Lock()
+ defer set.lock.Unlock()
if !set.closeUnderlyingDB {
set.db = nil
return nil
diff --git a/vendor/gitea.com/lunny/levelqueue/uniquequeue.go b/vendor/gitea.com/lunny/levelqueue/uniquequeue.go
index a53abb2c4edf..8d66e008de4d 100644
--- a/vendor/gitea.com/lunny/levelqueue/uniquequeue.go
+++ b/vendor/gitea.com/lunny/levelqueue/uniquequeue.go
@@ -181,6 +181,8 @@ func (queue *UniqueQueue) Len() int64 {
func (queue *UniqueQueue) Close() error {
_ = queue.q.Close()
_ = queue.set.Close()
+ queue.set.lock.Lock()
+ defer queue.set.lock.Unlock()
if !queue.closeUnderlyingDB {
queue.db = nil
return nil
diff --git a/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml
deleted file mode 100644
index 1027f56cd94d..000000000000
--- a/vendor/github.com/dgrijalva/jwt-go/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-language: go
-
-script:
- - go vet ./...
- - go test -v ./...
-
-go:
- - 1.3
- - 1.4
- - 1.5
- - 1.6
- - 1.7
- - tip
diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
deleted file mode 100644
index 7fc1f793cbc4..000000000000
--- a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md
+++ /dev/null
@@ -1,97 +0,0 @@
-## Migration Guide from v2 -> v3
-
-Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code.
-
-### `Token.Claims` is now an interface type
-
-The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`.
-
-`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property.
-
-The old example for parsing a token looked like this..
-
-```go
- if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil {
- fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
- }
-```
-
-is now directly mapped to...
-
-```go
- if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil {
- claims := token.Claims.(jwt.MapClaims)
- fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
- }
-```
-
-`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type.
-
-```go
- type MyCustomClaims struct {
- User string
- *StandardClaims
- }
-
- if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil {
- claims := token.Claims.(*MyCustomClaims)
- fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt)
- }
-```
-
-### `ParseFromRequest` has been moved
-
-To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`.
-
-`Extractors` do the work of picking the token string out of a request. The interface is simple and composable.
-
-This simple parsing example:
-
-```go
- if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil {
- fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"])
- }
-```
-
-is directly mapped to:
-
-```go
- if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil {
- claims := token.Claims.(jwt.MapClaims)
- fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"])
- }
-```
-
-There are several concrete `Extractor` types provided for your convenience:
-
-* `HeaderExtractor` will search a list of headers until one contains content.
-* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content.
-* `MultiExtractor` will try a list of `Extractors` in order until one returns content.
-* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token.
-* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument
-* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header
-
-
-### RSA signing methods no longer accept `[]byte` keys
-
-Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse.
-
-To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types.
-
-```go
- func keyLookupFunc(*Token) (interface{}, error) {
- // Don't forget to validate the alg is what you expect:
- if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
- return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
- }
-
- // Look up key
- key, err := lookupPublicKey(token.Header["kid"])
- if err != nil {
- return nil, err
- }
-
- // Unpack key from PEM encoded PKCS8
- return jwt.ParseRSAPublicKeyFromPEM(key)
- }
-```
diff --git a/vendor/github.com/dgrijalva/jwt-go/.gitignore b/vendor/github.com/golang-jwt/jwt/.gitignore
similarity index 68%
rename from vendor/github.com/dgrijalva/jwt-go/.gitignore
rename to vendor/github.com/golang-jwt/jwt/.gitignore
index 80bed650ec03..09573e0169c2 100644
--- a/vendor/github.com/dgrijalva/jwt-go/.gitignore
+++ b/vendor/github.com/golang-jwt/jwt/.gitignore
@@ -1,4 +1,4 @@
.DS_Store
bin
-
+.idea/
diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/golang-jwt/jwt/LICENSE
similarity index 96%
rename from vendor/github.com/dgrijalva/jwt-go/LICENSE
rename to vendor/github.com/golang-jwt/jwt/LICENSE
index df83a9c2f019..35dbc252041e 100644
--- a/vendor/github.com/dgrijalva/jwt-go/LICENSE
+++ b/vendor/github.com/golang-jwt/jwt/LICENSE
@@ -1,4 +1,5 @@
Copyright (c) 2012 Dave Grijalva
+Copyright (c) 2021 golang-jwt maintainers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
diff --git a/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md
new file mode 100644
index 000000000000..c4efbd2a8c5d
--- /dev/null
+++ b/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md
@@ -0,0 +1,22 @@
+## Migration Guide (v3.2.1)
+
+Starting from [v3.2.1](https://github.com/golang-jwt/jwt/releases/tag/v3.2.1]), the import path has changed from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt`. Future releases will be using the `github.com/golang-jwt/jwt` import path and continue the existing versioning scheme of `v3.x.x+incompatible`. Backwards-compatible patches and fixes will be done on the `v3` release branch, where as new build-breaking features will be developed in a `v4` release, possibly including a SIV-style import path.
+
+### go.mod replacement
+
+In a first step, the easiest way is to use `go mod edit` to issue a replacement.
+
+```
+go mod edit -replace github.com/dgrijalva/jwt-go=github.com/golang-jwt/jwt@v3.2.1+incompatible
+go mod tidy
+```
+
+This will still keep the old import path in your code but replace it with the new package and also introduce a new indirect dependency to `github.com/golang-jwt/jwt`. Try to compile your project; it should still work.
+
+### Cleanup
+
+If your code still consistently builds, you can replace all occurences of `github.com/dgrijalva/jwt-go` with `github.com/golang-jwt/jwt`, either manually or by using tools such as `sed`. Finally, the `replace` directive in the `go.mod` file can be removed.
+
+## Older releases (before v3.2.0)
+
+The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md.
\ No newline at end of file
diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/golang-jwt/jwt/README.md
similarity index 55%
rename from vendor/github.com/dgrijalva/jwt-go/README.md
rename to vendor/github.com/golang-jwt/jwt/README.md
index d358d881b8dd..9b653e46b013 100644
--- a/vendor/github.com/dgrijalva/jwt-go/README.md
+++ b/vendor/github.com/golang-jwt/jwt/README.md
@@ -1,25 +1,34 @@
# jwt-go
-[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go)
-[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go)
+[![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml)
+[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt)
-A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html)
+A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519).
-**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3.
+**IMPORT PATH CHANGE:** Starting from [v3.2.1](https://github.com/golang-jwt/jwt/releases/tag/v3.2.1), the import path has changed from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt`. After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic.
-**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail.
+Future releases will be using the `github.com/golang-jwt/jwt` import path and continue the existing versioning scheme of `v3.x.x+incompatible`. Backwards-compatible patches and fixes will be done on the `v3` release branch, where as new build-breaking features will be developed in a `v4` release, possibly including a SIV-style import path.
-**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.
+**SECURITY NOTICE:** Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue [dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more detail.
+
+**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.
+
+### Supported Go versions
+
+Our support of Go versions is aligned with Go's [version release policy](https://golang.org/doc/devel/release#policy).
+So we will support a major version of Go until there are two newer major releases.
+We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities
+which will not be fixed.
## What the heck is a JWT?
JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens.
-In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way.
+In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) encoded. The last part is the signature, encoded the same way.
The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.
-The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own.
+The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about reserved keys and the proper way to add your own.
## What's in the box?
@@ -27,31 +36,31 @@ This library supports the parsing and verification as well as the generation and
## Examples
-See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage:
+See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt) for examples of usage:
-* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac)
-* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac)
-* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples)
+* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-Parse-Hmac)
+* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-New-Hmac)
+* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt#pkg-examples)
## Extensions
This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`.
-Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go
+Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go
## Compliance
-This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences:
+This library was last reviewed to comply with [RTF 7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few notable differences:
-* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key.
+* In order to protect against accidental use of [Unsecured JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key.
## Project Status & Versioning
This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason).
-This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases).
+This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `main`. Periodically, versions will be tagged from `main`. You can find all the releases on [the project releases page](https://github.com/golang-jwt/jwt/releases).
-While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning.
+While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/golang-jwt/jwt.v3`. It will do the right thing WRT semantic versioning.
**BREAKING CHANGES:***
* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code.
@@ -79,9 +88,9 @@ Asymmetric signing methods, such as RSA, use different keys for signing and veri
Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones:
-* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation
-* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation
-* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation
+* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation
+* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation
+* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation
### JWT and OAuth
@@ -93,8 +102,12 @@ Without going too far down the rabbit hole, here's a description of the interact
* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
+### Troubleshooting
+
+This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types.
+
## More
-Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
+Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt).
The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.
diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md
similarity index 85%
rename from vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
rename to vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md
index 6370298313a6..637f2ba616a8 100644
--- a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
+++ b/vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md
@@ -1,5 +1,18 @@
## `jwt-go` Version History
+#### 3.2.2
+
+* Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)).
+* Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)).
+* Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)).
+* Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)).
+
+#### 3.2.1
+
+* **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code
+ * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt`
+* Fixed type confusing issue between `string` and `[]string` in `VerifyAudience` ([#12](https://github.com/golang-jwt/jwt/pull/12)). This fixes CVE-2020-26160
+
#### 3.2.0
* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation
@@ -115,4 +128,4 @@ It is likely the only integration change required here will be to change `func(t
* First versioned release
* API stabilized
* Supports creating, signing, parsing, and validating JWT tokens
-* Supports RS256 and HS256 signing methods
\ No newline at end of file
+* Supports RS256 and HS256 signing methods
diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/golang-jwt/jwt/claims.go
similarity index 83%
rename from vendor/github.com/dgrijalva/jwt-go/claims.go
rename to vendor/github.com/golang-jwt/jwt/claims.go
index f0228f02e033..f1dba3cb916f 100644
--- a/vendor/github.com/dgrijalva/jwt-go/claims.go
+++ b/vendor/github.com/golang-jwt/jwt/claims.go
@@ -35,18 +35,18 @@ func (c StandardClaims) Valid() error {
// The claims below are optional, by default, so if they are set to the
// default value in Go, let's not fail the verification for them.
- if c.VerifyExpiresAt(now, false) == false {
+ if !c.VerifyExpiresAt(now, false) {
delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
vErr.Inner = fmt.Errorf("token is expired by %v", delta)
vErr.Errors |= ValidationErrorExpired
}
- if c.VerifyIssuedAt(now, false) == false {
+ if !c.VerifyIssuedAt(now, false) {
vErr.Inner = fmt.Errorf("Token used before issued")
vErr.Errors |= ValidationErrorIssuedAt
}
- if c.VerifyNotBefore(now, false) == false {
+ if !c.VerifyNotBefore(now, false) {
vErr.Inner = fmt.Errorf("token is not valid yet")
vErr.Errors |= ValidationErrorNotValidYet
}
@@ -61,7 +61,7 @@ func (c StandardClaims) Valid() error {
// Compares the aud claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool {
- return verifyAud(c.Audience, cmp, req)
+ return verifyAud([]string{c.Audience}, cmp, req)
}
// Compares the exp claim against cmp.
@@ -90,15 +90,27 @@ func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
// ----- helpers
-func verifyAud(aud string, cmp string, required bool) bool {
- if aud == "" {
+func verifyAud(aud []string, cmp string, required bool) bool {
+ if len(aud) == 0 {
return !required
}
- if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 {
- return true
- } else {
- return false
+ // use a var here to keep constant time compare when looping over a number of claims
+ result := false
+
+ var stringClaims string
+ for _, a := range aud {
+ if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 {
+ result = true
+ }
+ stringClaims = stringClaims + a
}
+
+ // case where "" is sent in one or many aud claims
+ if len(stringClaims) == 0 {
+ return !required
+ }
+
+ return result
}
func verifyExp(exp int64, now int64, required bool) bool {
diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/golang-jwt/jwt/doc.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/doc.go
rename to vendor/github.com/golang-jwt/jwt/doc.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/golang-jwt/jwt/ecdsa.go
similarity index 84%
rename from vendor/github.com/dgrijalva/jwt-go/ecdsa.go
rename to vendor/github.com/golang-jwt/jwt/ecdsa.go
index f977381240e3..15e23435df6b 100644
--- a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go
+++ b/vendor/github.com/golang-jwt/jwt/ecdsa.go
@@ -88,11 +88,11 @@ func (m *SigningMethodECDSA) Verify(signingString, signature string, key interfa
hasher.Write([]byte(signingString))
// Verify the signature
- if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true {
+ if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus {
return nil
- } else {
- return ErrECDSAVerification
}
+
+ return ErrECDSAVerification
}
// Implements the Sign method from SigningMethod
@@ -128,18 +128,12 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string
keyBytes += 1
}
- // We serialize the outpus (r and s) into big-endian byte arrays and pad
- // them with zeros on the left to make sure the sizes work out. Both arrays
- // must be keyBytes long, and the output must be 2*keyBytes long.
- rBytes := r.Bytes()
- rBytesPadded := make([]byte, keyBytes)
- copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
-
- sBytes := s.Bytes()
- sBytesPadded := make([]byte, keyBytes)
- copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
-
- out := append(rBytesPadded, sBytesPadded...)
+ // We serialize the outputs (r and s) into big-endian byte arrays
+ // padded with zeros on the left to make sure the sizes work out.
+ // Output must be 2*keyBytes long.
+ out := make([]byte, 2*keyBytes)
+ r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output.
+ s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output.
return EncodeSegment(out), nil
} else {
diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go
similarity index 93%
rename from vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
rename to vendor/github.com/golang-jwt/jwt/ecdsa_utils.go
index d19624b7264f..db9f4be7d8ea 100644
--- a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go
+++ b/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go
@@ -25,7 +25,9 @@ func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
// Parse the key
var parsedKey interface{}
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
- return nil, err
+ if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
+ return nil, err
+ }
}
var pkey *ecdsa.PrivateKey
diff --git a/vendor/github.com/golang-jwt/jwt/ed25519.go b/vendor/github.com/golang-jwt/jwt/ed25519.go
new file mode 100644
index 000000000000..a2f8ddbe9bb3
--- /dev/null
+++ b/vendor/github.com/golang-jwt/jwt/ed25519.go
@@ -0,0 +1,81 @@
+package jwt
+
+import (
+ "errors"
+
+ "crypto/ed25519"
+)
+
+var (
+ ErrEd25519Verification = errors.New("ed25519: verification error")
+)
+
+// Implements the EdDSA family
+// Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification
+type SigningMethodEd25519 struct{}
+
+// Specific instance for EdDSA
+var (
+ SigningMethodEdDSA *SigningMethodEd25519
+)
+
+func init() {
+ SigningMethodEdDSA = &SigningMethodEd25519{}
+ RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod {
+ return SigningMethodEdDSA
+ })
+}
+
+func (m *SigningMethodEd25519) Alg() string {
+ return "EdDSA"
+}
+
+// Implements the Verify method from SigningMethod
+// For this verify method, key must be an ed25519.PublicKey
+func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error {
+ var err error
+ var ed25519Key ed25519.PublicKey
+ var ok bool
+
+ if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
+ return ErrInvalidKeyType
+ }
+
+ if len(ed25519Key) != ed25519.PublicKeySize {
+ return ErrInvalidKey
+ }
+
+ // Decode the signature
+ var sig []byte
+ if sig, err = DecodeSegment(signature); err != nil {
+ return err
+ }
+
+ // Verify the signature
+ if !ed25519.Verify(ed25519Key, []byte(signingString), sig) {
+ return ErrEd25519Verification
+ }
+
+ return nil
+}
+
+// Implements the Sign method from SigningMethod
+// For this signing method, key must be an ed25519.PrivateKey
+func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) {
+ var ed25519Key ed25519.PrivateKey
+ var ok bool
+
+ if ed25519Key, ok = key.(ed25519.PrivateKey); !ok {
+ return "", ErrInvalidKeyType
+ }
+
+ // ed25519.Sign panics if private key not equal to ed25519.PrivateKeySize
+ // this allows to avoid recover usage
+ if len(ed25519Key) != ed25519.PrivateKeySize {
+ return "", ErrInvalidKey
+ }
+
+ // Sign the string and return the encoded result
+ sig := ed25519.Sign(ed25519Key, []byte(signingString))
+ return EncodeSegment(sig), nil
+}
diff --git a/vendor/github.com/golang-jwt/jwt/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/ed25519_utils.go
new file mode 100644
index 000000000000..c6357275efc0
--- /dev/null
+++ b/vendor/github.com/golang-jwt/jwt/ed25519_utils.go
@@ -0,0 +1,64 @@
+package jwt
+
+import (
+ "crypto"
+ "crypto/ed25519"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+)
+
+var (
+ ErrNotEdPrivateKey = errors.New("Key is not a valid Ed25519 private key")
+ ErrNotEdPublicKey = errors.New("Key is not a valid Ed25519 public key")
+)
+
+// Parse PEM-encoded Edwards curve private key
+func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ // Parse the key
+ var parsedKey interface{}
+ if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
+ return nil, err
+ }
+
+ var pkey ed25519.PrivateKey
+ var ok bool
+ if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok {
+ return nil, ErrNotEdPrivateKey
+ }
+
+ return pkey, nil
+}
+
+// Parse PEM-encoded Edwards curve public key
+func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) {
+ var err error
+
+ // Parse PEM block
+ var block *pem.Block
+ if block, _ = pem.Decode(key); block == nil {
+ return nil, ErrKeyMustBePEMEncoded
+ }
+
+ // Parse the key
+ var parsedKey interface{}
+ if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
+ return nil, err
+ }
+
+ var pkey ed25519.PublicKey
+ var ok bool
+ if pkey, ok = parsedKey.(ed25519.PublicKey); !ok {
+ return nil, ErrNotEdPublicKey
+ }
+
+ return pkey, nil
+}
diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/golang-jwt/jwt/errors.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/errors.go
rename to vendor/github.com/golang-jwt/jwt/errors.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/golang-jwt/jwt/hmac.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/hmac.go
rename to vendor/github.com/golang-jwt/jwt/hmac.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/golang-jwt/jwt/map_claims.go
similarity index 69%
rename from vendor/github.com/dgrijalva/jwt-go/map_claims.go
rename to vendor/github.com/golang-jwt/jwt/map_claims.go
index 291213c460d4..72c79f92e55a 100644
--- a/vendor/github.com/dgrijalva/jwt-go/map_claims.go
+++ b/vendor/github.com/golang-jwt/jwt/map_claims.go
@@ -10,37 +10,59 @@ import (
// This is the default claims type if you don't supply one
type MapClaims map[string]interface{}
-// Compares the aud claim against cmp.
+// VerifyAudience Compares the aud claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (m MapClaims) VerifyAudience(cmp string, req bool) bool {
- aud, _ := m["aud"].(string)
+ var aud []string
+ switch v := m["aud"].(type) {
+ case string:
+ aud = append(aud, v)
+ case []string:
+ aud = v
+ case []interface{}:
+ for _, a := range v {
+ vs, ok := a.(string)
+ if !ok {
+ return false
+ }
+ aud = append(aud, vs)
+ }
+ }
return verifyAud(aud, cmp, req)
}
// Compares the exp claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool {
- switch exp := m["exp"].(type) {
+ exp, ok := m["exp"]
+ if !ok {
+ return !req
+ }
+ switch expType := exp.(type) {
case float64:
- return verifyExp(int64(exp), cmp, req)
+ return verifyExp(int64(expType), cmp, req)
case json.Number:
- v, _ := exp.Int64()
+ v, _ := expType.Int64()
return verifyExp(v, cmp, req)
}
- return req == false
+ return false
}
// Compares the iat claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool {
- switch iat := m["iat"].(type) {
+ iat, ok := m["iat"]
+ if !ok {
+ return !req
+ }
+ switch iatType := iat.(type) {
case float64:
- return verifyIat(int64(iat), cmp, req)
+ return verifyIat(int64(iatType), cmp, req)
case json.Number:
- v, _ := iat.Int64()
+ v, _ := iatType.Int64()
return verifyIat(v, cmp, req)
}
- return req == false
+ return false
}
// Compares the iss claim against cmp.
@@ -53,14 +75,18 @@ func (m MapClaims) VerifyIssuer(cmp string, req bool) bool {
// Compares the nbf claim against cmp.
// If required is false, this method will return true if the value matches or is unset
func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool {
- switch nbf := m["nbf"].(type) {
+ nbf, ok := m["nbf"]
+ if !ok {
+ return !req
+ }
+ switch nbfType := nbf.(type) {
case float64:
- return verifyNbf(int64(nbf), cmp, req)
+ return verifyNbf(int64(nbfType), cmp, req)
case json.Number:
- v, _ := nbf.Int64()
+ v, _ := nbfType.Int64()
return verifyNbf(v, cmp, req)
}
- return req == false
+ return false
}
// Validates time based claims "exp, iat, nbf".
@@ -71,17 +97,17 @@ func (m MapClaims) Valid() error {
vErr := new(ValidationError)
now := TimeFunc().Unix()
- if m.VerifyExpiresAt(now, false) == false {
+ if !m.VerifyExpiresAt(now, false) {
vErr.Inner = errors.New("Token is expired")
vErr.Errors |= ValidationErrorExpired
}
- if m.VerifyIssuedAt(now, false) == false {
+ if !m.VerifyIssuedAt(now, false) {
vErr.Inner = errors.New("Token used before issued")
vErr.Errors |= ValidationErrorIssuedAt
}
- if m.VerifyNotBefore(now, false) == false {
+ if !m.VerifyNotBefore(now, false) {
vErr.Inner = errors.New("Token is not valid yet")
vErr.Errors |= ValidationErrorNotValidYet
}
diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/golang-jwt/jwt/none.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/none.go
rename to vendor/github.com/golang-jwt/jwt/none.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/golang-jwt/jwt/parser.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/parser.go
rename to vendor/github.com/golang-jwt/jwt/parser.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/golang-jwt/jwt/rsa.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/rsa.go
rename to vendor/github.com/golang-jwt/jwt/rsa.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/rsa_pss.go
similarity index 71%
rename from vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
rename to vendor/github.com/golang-jwt/jwt/rsa_pss.go
index 10ee9db8a4ed..c01470864803 100644
--- a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go
+++ b/vendor/github.com/golang-jwt/jwt/rsa_pss.go
@@ -12,9 +12,14 @@ import (
type SigningMethodRSAPSS struct {
*SigningMethodRSA
Options *rsa.PSSOptions
+ // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS.
+ // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow
+ // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously.
+ // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details.
+ VerifyOptions *rsa.PSSOptions
}
-// Specific instances for RS/PS and company
+// Specific instances for RS/PS and company.
var (
SigningMethodPS256 *SigningMethodRSAPSS
SigningMethodPS384 *SigningMethodRSAPSS
@@ -24,13 +29,15 @@ var (
func init() {
// PS256
SigningMethodPS256 = &SigningMethodRSAPSS{
- &SigningMethodRSA{
+ SigningMethodRSA: &SigningMethodRSA{
Name: "PS256",
Hash: crypto.SHA256,
},
- &rsa.PSSOptions{
+ Options: &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthEqualsHash,
+ },
+ VerifyOptions: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
- Hash: crypto.SHA256,
},
}
RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod {
@@ -39,13 +46,15 @@ func init() {
// PS384
SigningMethodPS384 = &SigningMethodRSAPSS{
- &SigningMethodRSA{
+ SigningMethodRSA: &SigningMethodRSA{
Name: "PS384",
Hash: crypto.SHA384,
},
- &rsa.PSSOptions{
+ Options: &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthEqualsHash,
+ },
+ VerifyOptions: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
- Hash: crypto.SHA384,
},
}
RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod {
@@ -54,13 +63,15 @@ func init() {
// PS512
SigningMethodPS512 = &SigningMethodRSAPSS{
- &SigningMethodRSA{
+ SigningMethodRSA: &SigningMethodRSA{
Name: "PS512",
Hash: crypto.SHA512,
},
- &rsa.PSSOptions{
+ Options: &rsa.PSSOptions{
+ SaltLength: rsa.PSSSaltLengthEqualsHash,
+ },
+ VerifyOptions: &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
- Hash: crypto.SHA512,
},
}
RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod {
@@ -94,7 +105,12 @@ func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interf
hasher := m.Hash.New()
hasher.Write([]byte(signingString))
- return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
+ opts := m.Options
+ if m.VerifyOptions != nil {
+ opts = m.VerifyOptions
+ }
+
+ return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts)
}
// Implements the Sign method from SigningMethod
diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/rsa_utils.go
similarity index 95%
rename from vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
rename to vendor/github.com/golang-jwt/jwt/rsa_utils.go
index a5ababf956c4..14c78c292a94 100644
--- a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go
+++ b/vendor/github.com/golang-jwt/jwt/rsa_utils.go
@@ -8,7 +8,7 @@ import (
)
var (
- ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
+ ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be a PEM encoded PKCS1 or PKCS8 key")
ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
)
diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/golang-jwt/jwt/signing_method.go
similarity index 100%
rename from vendor/github.com/dgrijalva/jwt-go/signing_method.go
rename to vendor/github.com/golang-jwt/jwt/signing_method.go
diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/golang-jwt/jwt/token.go
similarity index 93%
rename from vendor/github.com/dgrijalva/jwt-go/token.go
rename to vendor/github.com/golang-jwt/jwt/token.go
index d637e0867c65..6b30ced1200c 100644
--- a/vendor/github.com/dgrijalva/jwt-go/token.go
+++ b/vendor/github.com/golang-jwt/jwt/token.go
@@ -65,7 +65,7 @@ func (t *Token) SignedString(key interface{}) (string, error) {
func (t *Token) SigningString() (string, error) {
var err error
parts := make([]string, 2)
- for i, _ := range parts {
+ for i := range parts {
var jsonValue []byte
if i == 0 {
if jsonValue, err = json.Marshal(t.Header); err != nil {
@@ -95,14 +95,10 @@ func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token
// Encode JWT specific base64url encoding with padding stripped
func EncodeSegment(seg []byte) string {
- return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
+ return base64.RawURLEncoding.EncodeToString(seg)
}
// Decode JWT specific base64url encoding with padding stripped
func DecodeSegment(seg string) ([]byte, error) {
- if l := len(seg) % 4; l > 0 {
- seg += strings.Repeat("=", 4-l)
- }
-
- return base64.URLEncoding.DecodeString(seg)
+ return base64.RawURLEncoding.DecodeString(seg)
}
diff --git a/vendor/github.com/markbates/goth/go.mod b/vendor/github.com/markbates/goth/go.mod
index b29abbdefef1..4a4405185a93 100644
--- a/vendor/github.com/markbates/goth/go.mod
+++ b/vendor/github.com/markbates/goth/go.mod
@@ -5,7 +5,7 @@ go 1.15
require (
cloud.google.com/go v0.67.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
- github.com/dgrijalva/jwt-go v3.2.0+incompatible
+ github.com/golang-jwt/jwt v3.2.1+incompatible
github.com/gorilla/mux v1.6.2
github.com/gorilla/pat v0.0.0-20180118222023-199c85a7f6d1
github.com/gorilla/sessions v1.1.1
@@ -14,7 +14,6 @@ require (
github.com/markbates/going v1.0.0
github.com/mrjones/oauth v0.0.0-20180629183705-f4e24b6d100c
github.com/pkg/errors v0.9.1 // indirect
- github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.4.0
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 // indirect
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43
diff --git a/vendor/github.com/markbates/goth/go.sum b/vendor/github.com/markbates/goth/go.sum
index 96c92c6cfba4..38523c052b23 100644
--- a/vendor/github.com/markbates/goth/go.sum
+++ b/vendor/github.com/markbates/goth/go.sum
@@ -1,6 +1,4 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
-cloud.google.com/go v0.30.0 h1:xKvyLgk56d0nksWq49J0UyGEeUIicTl4+UBiX1NPX9g=
-cloud.google.com/go v0.30.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
@@ -14,8 +12,8 @@ cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bP
cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk=
cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs=
cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc=
-cloud.google.com/go v0.63.0/go.mod h1:GmezbQc7T2snqkEXWfZ0sy0VfkB/ivI2DdtJL2DEmlg=
cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY=
+cloud.google.com/go v0.67.0 h1:YIkzmqUfVGiGPpT98L8sVvUIkDno6UlrDxw4NR6z5ak=
cloud.google.com/go v0.67.0/go.mod h1:YNan/mUhNZFrYUor0vqrsQ0Ffl7Xtm/ACOy/vsTS858=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE=
@@ -43,12 +41,9 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
-github.com/damonkeys/goth v1.64.2 h1:I2cB72NAa1tJBI1TcLYn7H6hBeHpwm5y8Ew+VeSZXPg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
-github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
@@ -56,6 +51,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
+github.com/golang-jwt/jwt v3.2.1+incompatible h1:73Z+4BJcrTC+KczS6WvTPvRGOp1WmfEP4Q1lOd9Z/+c=
+github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
@@ -67,7 +64,6 @@ github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt
github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
-github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
@@ -133,8 +129,6 @@ github.com/lestrrat-go/jwx v0.9.0 h1:Fnd0EWzTm0kFrBPzE/PEPp9nzllES5buMkksPMjEKpM
github.com/lestrrat-go/jwx v0.9.0/go.mod h1:iEoxlYfZjvoGpuWwxUz+eR5e6KTJGsaRcy/YNA/UnBk=
github.com/markbates/going v1.0.0 h1:DQw0ZP7NbNlFGcKbcE/IVSOAFzScxRtLpd0rLMzLhq0=
github.com/markbates/going v1.0.0/go.mod h1:I6mnB4BPnEeqo85ynXIx1ZFLLbtiLHNXVgWeFO9OGOA=
-github.com/markbates/goth v1.65.0 h1:IbXpMneUhqbxgJ8JP1Ghl8ghlAaVX66jWDAapU1KxqU=
-github.com/markbates/goth v1.65.0/go.mod h1:65frybxoeSCfORin51KOKqAKbIh7wREIDvdCkdWj//4=
github.com/mrjones/oauth v0.0.0-20180629183705-f4e24b6d100c h1:3wkDRdxK92dF+c1ke2dtj7ZzemFWBHB9plnJOtlwdFA=
github.com/mrjones/oauth v0.0.0-20180629183705-f4e24b6d100c/go.mod h1:skjdDftzkFALcuGzYSklqYd8gvat6F1gZJ4YPVbkZpM=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@@ -143,10 +137,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
-github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
-github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -192,7 +184,6 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB
golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
-golang.org/x/net v0.0.0-20180724234803-3673e40ba225 h1:kNX+jCowfMYzvlSvJu5pQWEmyWFrBXJ3PBy10xKMXK8=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -218,13 +209,10 @@ golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/
golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
-golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200927032502-5d4f70055728/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 h1:YfxMZzv3PjGonQYNUaeU2+DhAdqOxerQ30JFB6WgAXo=
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
-golang.org/x/oauth2 v0.0.0-20180620175406-ef147856a6dd h1:QQhib242ErYDSMitlBm8V7wYCm/1a25hV8qMadIKLPA=
-golang.org/x/oauth2 v0.0.0-20180620175406-ef147856a6dd/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -232,7 +220,6 @@ golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4Iltr
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43 h1:ld7aEMNHoBnnDAX15v1T6z31v8HwR2A9FYOuAhWqkwc=
golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
-golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -314,7 +301,6 @@ golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roY
golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
-golang.org/x/tools v0.0.0-20200806022845-90696ccdc692/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE=
golang.org/x/tools v0.0.0-20200929161345-d7fc70abf50f/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
@@ -375,7 +361,6 @@ google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEY
google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA=
google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
-google.golang.org/genproto v0.0.0-20200806141610-86f49bd18e98/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20200929141702-51c3e5b607fe/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
diff --git a/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go b/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go
index b486f97783e1..5ae2a84821c9 100644
--- a/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go
+++ b/vendor/github.com/markbates/goth/providers/openidConnect/openidConnect.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io/ioutil"
"net/http"
+ "net/url"
"strings"
"time"
@@ -82,6 +83,22 @@ type OpenIDConfig struct {
Issuer string `json:"issuer"`
}
+type RefreshTokenResponse struct {
+ AccessToken string `json:"access_token"`
+
+ // The OpenID spec defines the ID token as an optional response field in the
+ // refresh token flow. As a result, a new ID token may not be returned in a successful
+ // response.
+ // See more: https://openid.net/specs/openid-connect-core-1_0.html#RefreshingAccessToken
+ IdToken string `json:"id_token, omitempty"`
+
+ // The OAuth spec defines the refresh token as an optional response field in the
+ // refresh token flow. As a result, a new refresh token may not be returned in a successful
+ // response.
+ //See more: https://www.oauth.com/oauth2-servers/making-authenticated-requests/refreshing-an-access-token/
+ RefreshToken string `json:"refresh_token,omitempty"`
+}
+
// New creates a new OpenID Connect provider, and sets up important connection details.
// You should always call `openidConnect.New` to get a new Provider. Never try to create
// one manually.
@@ -202,6 +219,49 @@ func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
return newToken, err
}
+// The ID token is a fundamental part of the OpenID connect refresh token flow but is not part of the OAuth flow.
+// The existing RefreshToken function leverages the OAuth library's refresh token mechanism, ignoring the refreshed
+// ID token. As a result, a new function needs to be exposed (rather than changing the existing function, for backwards
+// compatibility purposes) that also returns the id_token in the OpenID refresh token flow API response
+// Learn more about ID tokens: https://openid.net/specs/openid-connect-core-1_0.html#IDToken
+func (p *Provider) RefreshTokenWithIDToken(refreshToken string) (*RefreshTokenResponse, error) {
+ urlValues := url.Values{
+ "grant_type": {"refresh_token"},
+ "refresh_token": {refreshToken},
+ "client_id": {p.ClientKey},
+ "client_secret": {p.Secret},
+ }
+ req, err := http.NewRequest("POST", p.OpenIDConfig.TokenEndpoint, strings.NewReader(urlValues.Encode()))
+ if err != nil {
+ return nil, err
+ }
+
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := p.Client().Do(req)
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("Non-200 response from RefreshToken: %d, WWW-Authenticate=%s", resp.StatusCode, resp.Header.Get("WWW-Authenticate"))
+ }
+
+ body, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+ return nil, err
+ }
+ resp.Body.Close()
+
+ refreshTokenResponse := &RefreshTokenResponse{}
+
+ err = json.Unmarshal(body, refreshTokenResponse)
+ if err != nil {
+ return nil, err
+ }
+
+ return refreshTokenResponse, nil
+}
+
// validate according to standard, returns expiry
// http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
func (p *Provider) validateClaims(claims map[string]interface{}) (time.Time, error) {
diff --git a/vendor/modules.txt b/vendor/modules.txt
index 41b6e2199fef..9b2a96ad5386 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -25,7 +25,7 @@ gitea.com/go-chi/session/couchbase
gitea.com/go-chi/session/memcache
gitea.com/go-chi/session/mysql
gitea.com/go-chi/session/postgres
-# gitea.com/lunny/levelqueue v0.3.0
+# gitea.com/lunny/levelqueue v0.4.1
## explicit
gitea.com/lunny/levelqueue
# github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c
@@ -225,9 +225,6 @@ github.com/denisenkom/go-mssqldb
github.com/denisenkom/go-mssqldb/internal/cp
github.com/denisenkom/go-mssqldb/internal/decimal
github.com/denisenkom/go-mssqldb/internal/querytext
-# github.com/dgrijalva/jwt-go v3.2.0+incompatible
-## explicit
-github.com/dgrijalva/jwt-go
# github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f
github.com/dgryski/go-rendezvous
# github.com/djherbis/buffer v1.2.0
@@ -431,6 +428,9 @@ github.com/gogs/cron
# github.com/gogs/go-gogs-client v0.0.0-20210131175652-1d7215cd8d85
## explicit
github.com/gogs/go-gogs-client
+# github.com/golang-jwt/jwt v3.2.2+incompatible
+## explicit
+github.com/golang-jwt/jwt
# github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe
github.com/golang-sql/civil
# github.com/golang/protobuf v1.5.2
@@ -570,7 +570,7 @@ github.com/mailru/easyjson
github.com/mailru/easyjson/buffer
github.com/mailru/easyjson/jlexer
github.com/mailru/easyjson/jwriter
-# github.com/markbates/goth v1.67.1
+# github.com/markbates/goth v1.68.0
## explicit
github.com/markbates/goth
github.com/markbates/goth/gothic
@@ -1053,3 +1053,4 @@ xorm.io/xorm/names
xorm.io/xorm/schemas
xorm.io/xorm/tags
# github.com/hashicorp/go-version => github.com/6543/go-version v1.3.1
+# github.com/golang-jwt/jwt v3.2.1+incompatible => github.com/golang-jwt/jwt v3.2.2+incompatible
diff --git a/web_src/fomantic/build/semantic.css b/web_src/fomantic/build/semantic.css
index ee136e13ff7c..27ff073a567f 100644
--- a/web_src/fomantic/build/semantic.css
+++ b/web_src/fomantic/build/semantic.css
@@ -30873,7 +30873,7 @@ ol.ui.suffixed.list li:before,
List
---------------*/
-/* Menu divider shouldn't apply */
+/* Menu divider shouldnt apply */
.ui.menu .list .item:before {
background: none !important;
@@ -31802,7 +31802,7 @@ Floated Menu / Item
opacity: 1;
}
-/* Icon Glyph */
+/* Icon Gylph */
.ui.icon.menu i.icon:before {
opacity: 1;
diff --git a/web_src/fomantic/build/semantic.js b/web_src/fomantic/build/semantic.js
index c68d266b0cd5..6514e99e3382 100644
--- a/web_src/fomantic/build/semantic.js
+++ b/web_src/fomantic/build/semantic.js
@@ -142,7 +142,7 @@ $.api = $.fn.api = function(parameters) {
response = JSON.parse(response);
}
catch(e) {
- // isn't json string
+ // isnt json string
}
}
return response;
@@ -2220,7 +2220,7 @@ $.fn.dimmer = function(parameters) {
event: {
click: function(event) {
- module.verbose('Determining if event occurred on dimmer', event);
+ module.verbose('Determining if event occured on dimmer', event);
if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) {
module.hide();
event.stopImmediatePropagation();
@@ -2827,6 +2827,13 @@ $.fn.dimmer.settings = {
*
*/
+/*
+ * Copyright 2019 The Gitea Authors
+ * Released under the MIT license
+ * http://opensource.org/licenses/MIT
+ * This version has been modified by Gitea to improve accessibility.
+ */
+
;(function ($, window, document, undefined) {
'use strict';
@@ -2860,6 +2867,7 @@ $.fn.dropdown = function(parameters) {
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
+ lastAriaID = 1,
returnedValue
;
@@ -2952,6 +2960,8 @@ $.fn.dropdown = function(parameters) {
module.observeChanges();
module.instantiate();
+
+ module.aria.setup();
}
},
@@ -3152,6 +3162,86 @@ $.fn.dropdown = function(parameters) {
}
},
+ aria: {
+ setup: function() {
+ var role = module.aria.guessRole();
+ if( role !== 'menu' ) {
+ return;
+ }
+ $module.attr('aria-busy', 'true');
+ $module.attr('role', 'menu');
+ $module.attr('aria-haspopup', 'menu');
+ $module.attr('aria-expanded', 'false');
+ $menu.find('.divider').attr('role', 'separator');
+ $item.attr('role', 'menuitem');
+ $item.each(function (index, item) {
+ if( !item.id ) {
+ item.id = module.aria.nextID('menuitem');
+ }
+ });
+ $text = $module
+ .find('> .text')
+ .eq(0)
+ ;
+ if( $module.data('content') ) {
+ $text.attr('aria-hidden');
+ $module.attr('aria-label', $module.data('content'));
+ }
+ else {
+ $text.attr('id', module.aria.nextID('menutext'));
+ $module.attr('aria-labelledby', $text.attr('id'));
+ }
+ $module.attr('aria-busy', 'false');
+ },
+ nextID: function(prefix) {
+ var nextID;
+ do {
+ nextID = prefix + '_' + lastAriaID++;
+ } while( document.getElementById(nextID) );
+ return nextID;
+ },
+ setExpanded: function(expanded) {
+ if( $module.attr('aria-haspopup') ) {
+ $module.attr('aria-expanded', expanded);
+ }
+ },
+ refreshDescendant: function() {
+ if( $module.attr('aria-haspopup') !== 'menu' ) {
+ return;
+ }
+ var
+ $currentlySelected = $item.not(selector.unselectable).filter('.' + className.selected).eq(0),
+ $activeItem = $menu.children('.' + className.active).eq(0),
+ $selectedItem = ($currentlySelected.length > 0)
+ ? $currentlySelected
+ : $activeItem
+ ;
+ if( $selectedItem ) {
+ $module.attr('aria-activedescendant', $selectedItem.attr('id'));
+ }
+ else {
+ module.aria.removeDescendant();
+ }
+ },
+ removeDescendant: function() {
+ if( $module.attr('aria-haspopup') == 'menu' ) {
+ $module.removeAttr('aria-activedescendant');
+ }
+ },
+ guessRole: function() {
+ var
+ isIcon = $module.hasClass('icon'),
+ hasSearch = module.has.search(),
+ hasInput = ($input.length > 0),
+ isMultiple = module.is.multiple()
+ ;
+ if ( !isIcon && !hasSearch && !hasInput && !isMultiple ) {
+ return 'menu';
+ }
+ return 'unknown';
+ }
+ },
+
setup: {
api: function() {
var
@@ -3198,6 +3288,7 @@ $.fn.dropdown = function(parameters) {
if(settings.allowTab) {
module.set.tabbable();
}
+ $item.attr('tabindex', '-1');
},
select: function() {
var
@@ -3344,6 +3435,8 @@ $.fn.dropdown = function(parameters) {
return true;
}
if(settings.onShow.call(element) !== false) {
+ module.aria.setExpanded(true);
+ module.aria.refreshDescendant();
module.animate.show(function() {
if( module.can.click() ) {
module.bind.intent();
@@ -3366,9 +3459,11 @@ $.fn.dropdown = function(parameters) {
if( module.is.active() && !module.is.animatingOutward() ) {
module.debug('Hiding dropdown');
if(settings.onHide.call(element) !== false) {
+ module.aria.setExpanded(false);
+ module.aria.removeDescendant();
module.animate.hide(function() {
module.remove.visible();
- // hiding search focus
+ // hidding search focus
if ( module.is.focusedOnSearch() && preventBlur !== true ) {
$search.blur();
}
@@ -4319,7 +4414,7 @@ $.fn.dropdown = function(parameters) {
// allow selection with menu closed
if(isAdditionWithoutMenu) {
module.verbose('Selecting item from keyboard shortcut', $selectedItem);
- module.event.item.click.call($selectedItem, event);
+ $selectedItem[0].click();
if(module.is.searchSelection()) {
module.remove.searchTerm();
}
@@ -4339,7 +4434,7 @@ $.fn.dropdown = function(parameters) {
}
else if(selectedIsSelectable) {
module.verbose('Selecting item from keyboard shortcut', $selectedItem);
- module.event.item.click.call($selectedItem, event);
+ $selectedItem[0].click();
if(module.is.searchSelection()) {
module.remove.searchTerm();
if(module.is.multiple()) {
@@ -4367,6 +4462,7 @@ $.fn.dropdown = function(parameters) {
.closest(selector.item)
.addClass(className.selected)
;
+ module.aria.refreshDescendant();
event.preventDefault();
}
}
@@ -4383,6 +4479,7 @@ $.fn.dropdown = function(parameters) {
.find(selector.item).eq(0)
.addClass(className.selected)
;
+ module.aria.refreshDescendant();
event.preventDefault();
}
}
@@ -4407,6 +4504,7 @@ $.fn.dropdown = function(parameters) {
$nextItem
.addClass(className.selected)
;
+ module.aria.refreshDescendant();
module.set.scrollPosition($nextItem);
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextItem);
@@ -4434,6 +4532,7 @@ $.fn.dropdown = function(parameters) {
$nextItem
.addClass(className.selected)
;
+ module.aria.refreshDescendant();
module.set.scrollPosition($nextItem);
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextItem);
@@ -5403,6 +5502,7 @@ $.fn.dropdown = function(parameters) {
module.set.scrollPosition($nextValue);
$selectedItem.removeClass(className.selected);
$nextValue.addClass(className.selected);
+ module.aria.refreshDescendant();
if(settings.selectOnKeydown && module.is.single()) {
module.set.selectedItem($nextValue);
}
@@ -11937,7 +12037,7 @@ $.fn.progress = function(parameters) {
*
* @param min A minimum value within multiple values
* @param total A total amount of multiple values
- * @returns {number} A precision. Could be 1, 10, 100, ... 1e+10.
+ * @returns {number} A precison. Could be 1, 10, 100, ... 1e+10.
*/
derivePrecision: function(min, total) {
var precisionPower = 0
@@ -12837,7 +12937,7 @@ $.fn.progress.settings = {
nonNumeric : 'Progress value is non numeric',
tooHigh : 'Value specified is above 100%',
tooLow : 'Value specified is below 0%',
- sumExceedsTotal : 'Sum of multiple values exceed total',
+ sumExceedsTotal : 'Sum of multple values exceed total',
},
regExp: {
@@ -18076,7 +18176,7 @@ $.fn.transition.settings = {
// possible errors
error: {
- noAnimation : 'Element is no longer attached to DOM. Unable to animate. Use silent setting to suppress this warning in production.',
+ noAnimation : 'Element is no longer attached to DOM. Unable to animate. Use silent setting to surpress this warning in production.',
repeated : 'That animation is already occurring, cancelling repeated animation',
method : 'The method you called is not defined',
support : 'This browser does not support CSS animations'
diff --git a/web_src/js/features/notification.js b/web_src/js/features/notification.js
index 4fa2d3c29af3..d964ffa3052d 100644
--- a/web_src/js/features/notification.js
+++ b/web_src/js/features/notification.js
@@ -1,5 +1,7 @@
const {AppSubUrl, csrf, NotificationSettings} = window.config;
+let notificationSequenceNumber = 0;
+
export function initNotificationsTable() {
$('#notification_table .button').on('click', async function () {
const data = await updateNotification(
@@ -10,8 +12,10 @@ export function initNotificationsTable() {
$(this).data('notification-id'),
);
- $('#notification_div').replaceWith(data);
- initNotificationsTable();
+ if ($(data).data('sequence-number') === notificationSequenceNumber) {
+ $('#notification_div').replaceWith(data);
+ initNotificationsTable();
+ }
await updateNotificationCount();
return false;
@@ -139,10 +143,13 @@ async function updateNotificationTable() {
url: `${AppSubUrl}/notifications?${notificationDiv.data('params')}`,
data: {
'div-only': true,
+ 'sequence-number': ++notificationSequenceNumber,
}
});
- notificationDiv.replaceWith(data);
- initNotificationsTable();
+ if ($(data).data('sequence-number') === notificationSequenceNumber) {
+ notificationDiv.replaceWith(data);
+ initNotificationsTable();
+ }
}
}
@@ -182,6 +189,7 @@ async function updateNotification(url, status, page, q, notificationID) {
page,
q,
noredirect: true,
+ 'sequence-number': ++notificationSequenceNumber,
},
});
}
diff --git a/web_src/js/index.js b/web_src/js/index.js
index d10852ebf533..c440da442c61 100644
--- a/web_src/js/index.js
+++ b/web_src/js/index.js
@@ -1984,7 +1984,9 @@ function initAdmin() {
$('#password').attr('required', 'required');
}
} else {
- $('#user_name').attr('disabled', 'disabled');
+ if ($('.admin.edit.user').length > 0) {
+ $('#user_name').attr('disabled', 'disabled');
+ }
$('#login_name').attr('required', 'required');
$('.non-local').show();
$('.local').hide();
diff --git a/web_src/js/markup/tasklist.js b/web_src/js/markup/tasklist.js
index 24b29ddb7afc..ea1a1f824a13 100644
--- a/web_src/js/markup/tasklist.js
+++ b/web_src/js/markup/tasklist.js
@@ -46,9 +46,10 @@ export function initMarkupTasklist() {
const {updateUrl, context} = editContentZone.dataset;
await $.post(updateUrl, {
+ ignore_attachments: true,
_csrf: window.config.csrf,
content: newContent,
- context,
+ context
});
rawContent.textContent = newContent;
diff --git a/web_src/js/vendor/dropdown.js b/web_src/js/vendor/dropdown.js
new file mode 100644
index 000000000000..3d4cfec27a14
--- /dev/null
+++ b/web_src/js/vendor/dropdown.js
@@ -0,0 +1,4338 @@
+/*!
+ * # Fomantic-UI - Dropdown
+ * http://github.com/fomantic/Fomantic-UI/
+ *
+ *
+ * Released under the MIT license
+ * http://opensource.org/licenses/MIT
+ *
+ */
+
+/*
+ * Copyright 2019 The Gitea Authors
+ * Released under the MIT license
+ * http://opensource.org/licenses/MIT
+ * This version has been modified by Gitea to improve accessibility.
+ */
+
+;(function ($, window, document, undefined) {
+
+'use strict';
+
+$.isFunction = $.isFunction || function(obj) {
+ return typeof obj === "function" && typeof obj.nodeType !== "number";
+};
+
+window = (typeof window != 'undefined' && window.Math == Math)
+ ? window
+ : (typeof self != 'undefined' && self.Math == Math)
+ ? self
+ : Function('return this')()
+;
+
+$.fn.dropdown = function(parameters) {
+ var
+ $allModules = $(this),
+ $document = $(document),
+
+ moduleSelector = $allModules.selector || '',
+
+ hasTouch = ('ontouchstart' in document.documentElement),
+ clickEvent = hasTouch
+ ? 'touchstart'
+ : 'click',
+
+ time = new Date().getTime(),
+ performance = [],
+
+ query = arguments[0],
+ methodInvoked = (typeof query == 'string'),
+ queryArguments = [].slice.call(arguments, 1),
+ lastAriaID = 1,
+ returnedValue
+ ;
+
+ $allModules
+ .each(function(elementIndex) {
+ var
+ settings = ( $.isPlainObject(parameters) )
+ ? $.extend(true, {}, $.fn.dropdown.settings, parameters)
+ : $.extend({}, $.fn.dropdown.settings),
+
+ className = settings.className,
+ message = settings.message,
+ fields = settings.fields,
+ keys = settings.keys,
+ metadata = settings.metadata,
+ namespace = settings.namespace,
+ regExp = settings.regExp,
+ selector = settings.selector,
+ error = settings.error,
+ templates = settings.templates,
+
+ eventNamespace = '.' + namespace,
+ moduleNamespace = 'module-' + namespace,
+
+ $module = $(this),
+ $context = $(settings.context),
+ $text = $module.find(selector.text),
+ $search = $module.find(selector.search),
+ $sizer = $module.find(selector.sizer),
+ $input = $module.find(selector.input),
+ $icon = $module.find(selector.icon),
+ $clear = $module.find(selector.clearIcon),
+
+ $combo = ($module.prev().find(selector.text).length > 0)
+ ? $module.prev().find(selector.text)
+ : $module.prev(),
+
+ $menu = $module.children(selector.menu),
+ $item = $menu.find(selector.item),
+ $divider = settings.hideDividers ? $item.parent().children(selector.divider) : $(),
+
+ activated = false,
+ itemActivated = false,
+ internalChange = false,
+ iconClicked = false,
+ element = this,
+ instance = $module.data(moduleNamespace),
+
+ selectActionActive,
+ initialLoad,
+ pageLostFocus,
+ willRefocus,
+ elementNamespace,
+ id,
+ selectObserver,
+ menuObserver,
+ classObserver,
+ module
+ ;
+
+ module = {
+
+ initialize: function() {
+ module.debug('Initializing dropdown', settings);
+
+ if( module.is.alreadySetup() ) {
+ module.setup.reference();
+ }
+ else {
+ if (settings.ignoreDiacritics && !String.prototype.normalize) {
+ settings.ignoreDiacritics = false;
+ module.error(error.noNormalize, element);
+ }
+
+ module.setup.layout();
+
+ if(settings.values) {
+ module.set.initialLoad();
+ module.change.values(settings.values);
+ module.remove.initialLoad();
+ }
+
+ module.refreshData();
+
+ module.save.defaults();
+ module.restore.selected();
+
+ module.create.id();
+ module.bind.events();
+
+ module.observeChanges();
+ module.instantiate();
+
+ module.aria.setup();
+ }
+
+ },
+
+ instantiate: function() {
+ module.verbose('Storing instance of dropdown', module);
+ instance = module;
+ $module
+ .data(moduleNamespace, module)
+ ;
+ },
+
+ destroy: function() {
+ module.verbose('Destroying previous dropdown', $module);
+ module.remove.tabbable();
+ module.remove.active();
+ $menu.transition('stop all');
+ $menu.removeClass(className.visible).addClass(className.hidden);
+ $module
+ .off(eventNamespace)
+ .removeData(moduleNamespace)
+ ;
+ $menu
+ .off(eventNamespace)
+ ;
+ $document
+ .off(elementNamespace)
+ ;
+ module.disconnect.menuObserver();
+ module.disconnect.selectObserver();
+ module.disconnect.classObserver();
+ },
+
+ observeChanges: function() {
+ if('MutationObserver' in window) {
+ selectObserver = new MutationObserver(module.event.select.mutation);
+ menuObserver = new MutationObserver(module.event.menu.mutation);
+ classObserver = new MutationObserver(module.event.class.mutation);
+ module.debug('Setting up mutation observer', selectObserver, menuObserver, classObserver);
+ module.observe.select();
+ module.observe.menu();
+ module.observe.class();
+ }
+ },
+
+ disconnect: {
+ menuObserver: function() {
+ if(menuObserver) {
+ menuObserver.disconnect();
+ }
+ },
+ selectObserver: function() {
+ if(selectObserver) {
+ selectObserver.disconnect();
+ }
+ },
+ classObserver: function() {
+ if(classObserver) {
+ classObserver.disconnect();
+ }
+ }
+ },
+ observe: {
+ select: function() {
+ if(module.has.input() && selectObserver) {
+ selectObserver.observe($module[0], {
+ childList : true,
+ subtree : true
+ });
+ }
+ },
+ menu: function() {
+ if(module.has.menu() && menuObserver) {
+ menuObserver.observe($menu[0], {
+ childList : true,
+ subtree : true
+ });
+ }
+ },
+ class: function() {
+ if(module.has.search() && classObserver) {
+ classObserver.observe($module[0], {
+ attributes : true
+ });
+ }
+ }
+ },
+
+ create: {
+ id: function() {
+ id = (Math.random().toString(16) + '000000000').substr(2, 8);
+ elementNamespace = '.' + id;
+ module.verbose('Creating unique id for element', id);
+ },
+ userChoice: function(values) {
+ var
+ $userChoices,
+ $userChoice,
+ isUserValue,
+ html
+ ;
+ values = values || module.get.userValues();
+ if(!values) {
+ return false;
+ }
+ values = Array.isArray(values)
+ ? values
+ : [values]
+ ;
+ $.each(values, function(index, value) {
+ if(module.get.item(value) === false) {
+ html = settings.templates.addition( module.add.variables(message.addResult, value) );
+ $userChoice = $('')
+ .html(html)
+ .attr('data-' + metadata.value, value)
+ .attr('data-' + metadata.text, value)
+ .addClass(className.addition)
+ .addClass(className.item)
+ ;
+ if(settings.hideAdditions) {
+ $userChoice.addClass(className.hidden);
+ }
+ $userChoices = ($userChoices === undefined)
+ ? $userChoice
+ : $userChoices.add($userChoice)
+ ;
+ module.verbose('Creating user choices for value', value, $userChoice);
+ }
+ });
+ return $userChoices;
+ },
+ userLabels: function(value) {
+ var
+ userValues = module.get.userValues()
+ ;
+ if(userValues) {
+ module.debug('Adding user labels', userValues);
+ $.each(userValues, function(index, value) {
+ module.verbose('Adding custom user value');
+ module.add.label(value, value);
+ });
+ }
+ },
+ menu: function() {
+ $menu = $('')
+ .addClass(className.menu)
+ .appendTo($module)
+ ;
+ },
+ sizer: function() {
+ $sizer = $('')
+ .addClass(className.sizer)
+ .insertAfter($search)
+ ;
+ }
+ },
+
+ search: function(query) {
+ query = (query !== undefined)
+ ? query
+ : module.get.query()
+ ;
+ module.verbose('Searching for query', query);
+ if(module.has.minCharacters(query)) {
+ module.filter(query);
+ }
+ else {
+ module.hide(null,true);
+ }
+ },
+
+ select: {
+ firstUnfiltered: function() {
+ module.verbose('Selecting first non-filtered element');
+ module.remove.selectedItem();
+ $item
+ .not(selector.unselectable)
+ .not(selector.addition + selector.hidden)
+ .eq(0)
+ .addClass(className.selected)
+ ;
+ },
+ nextAvailable: function($selected) {
+ $selected = $selected.eq(0);
+ var
+ $nextAvailable = $selected.nextAll(selector.item).not(selector.unselectable).eq(0),
+ $prevAvailable = $selected.prevAll(selector.item).not(selector.unselectable).eq(0),
+ hasNext = ($nextAvailable.length > 0)
+ ;
+ if(hasNext) {
+ module.verbose('Moving selection to', $nextAvailable);
+ $nextAvailable.addClass(className.selected);
+ }
+ else {
+ module.verbose('Moving selection to', $prevAvailable);
+ $prevAvailable.addClass(className.selected);
+ }
+ }
+ },
+
+ aria: {
+ setup: function() {
+ var role = module.aria.guessRole();
+ if( role !== 'menu' ) {
+ return;
+ }
+ $module.attr('aria-busy', 'true');
+ $module.attr('role', 'menu');
+ $module.attr('aria-haspopup', 'menu');
+ $module.attr('aria-expanded', 'false');
+ $menu.find('.divider').attr('role', 'separator');
+ $item.attr('role', 'menuitem');
+ $item.each(function (index, item) {
+ if( !item.id ) {
+ item.id = module.aria.nextID('menuitem');
+ }
+ });
+ $text = $module
+ .find('> .text')
+ .eq(0)
+ ;
+ if( $module.data('content') ) {
+ $text.attr('aria-hidden');
+ $module.attr('aria-label', $module.data('content'));
+ }
+ else {
+ $text.attr('id', module.aria.nextID('menutext'));
+ $module.attr('aria-labelledby', $text.attr('id'));
+ }
+ $module.attr('aria-busy', 'false');
+ },
+ nextID: function(prefix) {
+ var nextID;
+ do {
+ nextID = prefix + '_' + lastAriaID++;
+ } while( document.getElementById(nextID) );
+ return nextID;
+ },
+ setExpanded: function(expanded) {
+ if( $module.attr('aria-haspopup') ) {
+ $module.attr('aria-expanded', expanded);
+ }
+ },
+ refreshDescendant: function() {
+ if( $module.attr('aria-haspopup') !== 'menu' ) {
+ return;
+ }
+ var
+ $currentlySelected = $item.not(selector.unselectable).filter('.' + className.selected).eq(0),
+ $activeItem = $menu.children('.' + className.active).eq(0),
+ $selectedItem = ($currentlySelected.length > 0)
+ ? $currentlySelected
+ : $activeItem
+ ;
+ if( $selectedItem ) {
+ $module.attr('aria-activedescendant', $selectedItem.attr('id'));
+ }
+ else {
+ module.aria.removeDescendant();
+ }
+ },
+ removeDescendant: function() {
+ if( $module.attr('aria-haspopup') == 'menu' ) {
+ $module.removeAttr('aria-activedescendant');
+ }
+ },
+ guessRole: function() {
+ var
+ isIcon = $module.hasClass('icon'),
+ hasSearch = module.has.search(),
+ hasInput = ($input.length > 0),
+ isMultiple = module.is.multiple()
+ ;
+ if ( !isIcon && !hasSearch && !hasInput && !isMultiple ) {
+ return 'menu';
+ }
+ return 'unknown';
+ }
+ },
+
+ setup: {
+ api: function() {
+ var
+ apiSettings = {
+ debug : settings.debug,
+ urlData : {
+ value : module.get.value(),
+ query : module.get.query()
+ },
+ on : false
+ }
+ ;
+ module.verbose('First request, initializing API');
+ $module
+ .api(apiSettings)
+ ;
+ },
+ layout: function() {
+ if( $module.is('select') ) {
+ module.setup.select();
+ module.setup.returnedObject();
+ }
+ if( !module.has.menu() ) {
+ module.create.menu();
+ }
+ if ( module.is.selection() && module.is.clearable() && !module.has.clearItem() ) {
+ module.verbose('Adding clear icon');
+ $clear = $('')
+ .addClass('remove icon')
+ .insertBefore($text)
+ ;
+ }
+ if( module.is.search() && !module.has.search() ) {
+ module.verbose('Adding search input');
+ $search = $('')
+ .addClass(className.search)
+ .prop('autocomplete', 'off')
+ .insertBefore($text)
+ ;
+ }
+ if( module.is.multiple() && module.is.searchSelection() && !module.has.sizer()) {
+ module.create.sizer();
+ }
+ if(settings.allowTab) {
+ module.set.tabbable();
+ }
+ $item.attr('tabindex', '-1');
+ },
+ select: function() {
+ var
+ selectValues = module.get.selectValues()
+ ;
+ module.debug('Dropdown initialized on a select', selectValues);
+ if( $module.is('select') ) {
+ $input = $module;
+ }
+ // see if select is placed correctly already
+ if($input.parent(selector.dropdown).length > 0) {
+ module.debug('UI dropdown already exists. Creating dropdown menu only');
+ $module = $input.closest(selector.dropdown);
+ if( !module.has.menu() ) {
+ module.create.menu();
+ }
+ $menu = $module.children(selector.menu);
+ module.setup.menu(selectValues);
+ }
+ else {
+ module.debug('Creating entire dropdown from select');
+ $module = $('')
+ .attr('class', $input.attr('class') )
+ .addClass(className.selection)
+ .addClass(className.dropdown)
+ .html( templates.dropdown(selectValues, fields, settings.preserveHTML, settings.className) )
+ .insertBefore($input)
+ ;
+ if($input.hasClass(className.multiple) && $input.prop('multiple') === false) {
+ module.error(error.missingMultiple);
+ $input.prop('multiple', true);
+ }
+ if($input.is('[multiple]')) {
+ module.set.multiple();
+ }
+ if ($input.prop('disabled')) {
+ module.debug('Disabling dropdown');
+ $module.addClass(className.disabled);
+ }
+ $input
+ .removeAttr('required')
+ .removeAttr('class')
+ .detach()
+ .prependTo($module)
+ ;
+ }
+ module.refresh();
+ },
+ menu: function(values) {
+ $menu.html( templates.menu(values, fields,settings.preserveHTML,settings.className));
+ $item = $menu.find(selector.item);
+ $divider = settings.hideDividers ? $item.parent().children(selector.divider) : $();
+ },
+ reference: function() {
+ module.debug('Dropdown behavior was called on select, replacing with closest dropdown');
+ // replace module reference
+ $module = $module.parent(selector.dropdown);
+ instance = $module.data(moduleNamespace);
+ element = $module.get(0);
+ module.refresh();
+ module.setup.returnedObject();
+ },
+ returnedObject: function() {
+ var
+ $firstModules = $allModules.slice(0, elementIndex),
+ $lastModules = $allModules.slice(elementIndex + 1)
+ ;
+ // adjust all modules to use correct reference
+ $allModules = $firstModules.add($module).add($lastModules);
+ }
+ },
+
+ refresh: function() {
+ module.refreshSelectors();
+ module.refreshData();
+ },
+
+ refreshItems: function() {
+ $item = $menu.find(selector.item);
+ $divider = settings.hideDividers ? $item.parent().children(selector.divider) : $();
+ },
+
+ refreshSelectors: function() {
+ module.verbose('Refreshing selector cache');
+ $text = $module.find(selector.text);
+ $search = $module.find(selector.search);
+ $input = $module.find(selector.input);
+ $icon = $module.find(selector.icon);
+ $combo = ($module.prev().find(selector.text).length > 0)
+ ? $module.prev().find(selector.text)
+ : $module.prev()
+ ;
+ $menu = $module.children(selector.menu);
+ $item = $menu.find(selector.item);
+ $divider = settings.hideDividers ? $item.parent().children(selector.divider) : $();
+ },
+
+ refreshData: function() {
+ module.verbose('Refreshing cached metadata');
+ $item
+ .removeData(metadata.text)
+ .removeData(metadata.value)
+ ;
+ },
+
+ clearData: function() {
+ module.verbose('Clearing metadata');
+ $item
+ .removeData(metadata.text)
+ .removeData(metadata.value)
+ ;
+ $module
+ .removeData(metadata.defaultText)
+ .removeData(metadata.defaultValue)
+ .removeData(metadata.placeholderText)
+ ;
+ },
+
+ toggle: function() {
+ module.verbose('Toggling menu visibility');
+ if( !module.is.active() ) {
+ module.show();
+ }
+ else {
+ module.hide();
+ }
+ },
+
+ show: function(callback, preventFocus) {
+ callback = $.isFunction(callback)
+ ? callback
+ : function(){}
+ ;
+ if(!module.can.show() && module.is.remote()) {
+ module.debug('No API results retrieved, searching before show');
+ module.queryRemote(module.get.query(), module.show);
+ }
+ if( module.can.show() && !module.is.active() ) {
+ module.debug('Showing dropdown');
+ if(module.has.message() && !(module.has.maxSelections() || module.has.allResultsFiltered()) ) {
+ module.remove.message();
+ }
+ if(module.is.allFiltered()) {
+ return true;
+ }
+ if(settings.onShow.call(element) !== false) {
+ module.aria.setExpanded(true);
+ module.aria.refreshDescendant();
+ module.animate.show(function() {
+ if( module.can.click() ) {
+ module.bind.intent();
+ }
+ if(module.has.search() && !preventFocus) {
+ module.focusSearch();
+ }
+ module.set.visible();
+ callback.call(element);
+ });
+ }
+ }
+ },
+
+ hide: function(callback, preventBlur) {
+ callback = $.isFunction(callback)
+ ? callback
+ : function(){}
+ ;
+ if( module.is.active() && !module.is.animatingOutward() ) {
+ module.debug('Hiding dropdown');
+ if(settings.onHide.call(element) !== false) {
+ module.aria.setExpanded(false);
+ module.aria.removeDescendant();
+ module.animate.hide(function() {
+ module.remove.visible();
+ // hidding search focus
+ if ( module.is.focusedOnSearch() && preventBlur !== true ) {
+ $search.blur();
+ }
+ callback.call(element);
+ });
+ }
+ } else if( module.can.click() ) {
+ module.unbind.intent();
+ }
+ iconClicked = false;
+ },
+
+ hideOthers: function() {
+ module.verbose('Finding other dropdowns to hide');
+ $allModules
+ .not($module)
+ .has(selector.menu + '.' + className.visible)
+ .dropdown('hide')
+ ;
+ },
+
+ hideMenu: function() {
+ module.verbose('Hiding menu instantaneously');
+ module.remove.active();
+ module.remove.visible();
+ $menu.transition('hide');
+ },
+
+ hideSubMenus: function() {
+ var
+ $subMenus = $menu.children(selector.item).find(selector.menu)
+ ;
+ module.verbose('Hiding sub menus', $subMenus);
+ $subMenus.transition('hide');
+ },
+
+ bind: {
+ events: function() {
+ module.bind.keyboardEvents();
+ module.bind.inputEvents();
+ module.bind.mouseEvents();
+ },
+ keyboardEvents: function() {
+ module.verbose('Binding keyboard events');
+ $module
+ .on('keydown' + eventNamespace, module.event.keydown)
+ ;
+ if( module.has.search() ) {
+ $module
+ .on(module.get.inputEvent() + eventNamespace, selector.search, module.event.input)
+ ;
+ }
+ if( module.is.multiple() ) {
+ $document
+ .on('keydown' + elementNamespace, module.event.document.keydown)
+ ;
+ }
+ },
+ inputEvents: function() {
+ module.verbose('Binding input change events');
+ $module
+ .on('change' + eventNamespace, selector.input, module.event.change)
+ ;
+ },
+ mouseEvents: function() {
+ module.verbose('Binding mouse events');
+ if(module.is.multiple()) {
+ $module
+ .on(clickEvent + eventNamespace, selector.label, module.event.label.click)
+ .on(clickEvent + eventNamespace, selector.remove, module.event.remove.click)
+ ;
+ }
+ if( module.is.searchSelection() ) {
+ $module
+ .on('mousedown' + eventNamespace, module.event.mousedown)
+ .on('mouseup' + eventNamespace, module.event.mouseup)
+ .on('mousedown' + eventNamespace, selector.menu, module.event.menu.mousedown)
+ .on('mouseup' + eventNamespace, selector.menu, module.event.menu.mouseup)
+ .on(clickEvent + eventNamespace, selector.icon, module.event.icon.click)
+ .on(clickEvent + eventNamespace, selector.clearIcon, module.event.clearIcon.click)
+ .on('focus' + eventNamespace, selector.search, module.event.search.focus)
+ .on(clickEvent + eventNamespace, selector.search, module.event.search.focus)
+ .on('blur' + eventNamespace, selector.search, module.event.search.blur)
+ .on(clickEvent + eventNamespace, selector.text, module.event.text.focus)
+ ;
+ if(module.is.multiple()) {
+ $module
+ .on(clickEvent + eventNamespace, module.event.click)
+ ;
+ }
+ }
+ else {
+ if(settings.on == 'click') {
+ $module
+ .on(clickEvent + eventNamespace, selector.icon, module.event.icon.click)
+ .on(clickEvent + eventNamespace, module.event.test.toggle)
+ ;
+ }
+ else if(settings.on == 'hover') {
+ $module
+ .on('mouseenter' + eventNamespace, module.delay.show)
+ .on('mouseleave' + eventNamespace, module.delay.hide)
+ ;
+ }
+ else {
+ $module
+ .on(settings.on + eventNamespace, module.toggle)
+ ;
+ }
+ $module
+ .on('mousedown' + eventNamespace, module.event.mousedown)
+ .on('mouseup' + eventNamespace, module.event.mouseup)
+ .on('focus' + eventNamespace, module.event.focus)
+ .on(clickEvent + eventNamespace, selector.clearIcon, module.event.clearIcon.click)
+ ;
+ if(module.has.menuSearch() ) {
+ $module
+ .on('blur' + eventNamespace, selector.search, module.event.search.blur)
+ ;
+ }
+ else {
+ $module
+ .on('blur' + eventNamespace, module.event.blur)
+ ;
+ }
+ }
+ $menu
+ .on((hasTouch ? 'touchstart' : 'mouseenter') + eventNamespace, selector.item, module.event.item.mouseenter)
+ .on('mouseleave' + eventNamespace, selector.item, module.event.item.mouseleave)
+ .on('click' + eventNamespace, selector.item, module.event.item.click)
+ ;
+ },
+ intent: function() {
+ module.verbose('Binding hide intent event to document');
+ if(hasTouch) {
+ $document
+ .on('touchstart' + elementNamespace, module.event.test.touch)
+ .on('touchmove' + elementNamespace, module.event.test.touch)
+ ;
+ }
+ $document
+ .on(clickEvent + elementNamespace, module.event.test.hide)
+ ;
+ }
+ },
+
+ unbind: {
+ intent: function() {
+ module.verbose('Removing hide intent event from document');
+ if(hasTouch) {
+ $document
+ .off('touchstart' + elementNamespace)
+ .off('touchmove' + elementNamespace)
+ ;
+ }
+ $document
+ .off(clickEvent + elementNamespace)
+ ;
+ }
+ },
+
+ filter: function(query) {
+ var
+ searchTerm = (query !== undefined)
+ ? query
+ : module.get.query(),
+ afterFiltered = function() {
+ if(module.is.multiple()) {
+ module.filterActive();
+ }
+ if(query || (!query && module.get.activeItem().length == 0)) {
+ module.select.firstUnfiltered();
+ }
+ if( module.has.allResultsFiltered() ) {
+ if( settings.onNoResults.call(element, searchTerm) ) {
+ if(settings.allowAdditions) {
+ if(settings.hideAdditions) {
+ module.verbose('User addition with no menu, setting empty style');
+ module.set.empty();
+ module.hideMenu();
+ }
+ }
+ else {
+ module.verbose('All items filtered, showing message', searchTerm);
+ module.add.message(message.noResults);
+ }
+ }
+ else {
+ module.verbose('All items filtered, hiding dropdown', searchTerm);
+ module.hideMenu();
+ }
+ }
+ else {
+ module.remove.empty();
+ module.remove.message();
+ }
+ if(settings.allowAdditions) {
+ module.add.userSuggestion(module.escape.htmlEntities(query));
+ }
+ if(module.is.searchSelection() && module.can.show() && module.is.focusedOnSearch() ) {
+ module.show();
+ }
+ }
+ ;
+ if(settings.useLabels && module.has.maxSelections()) {
+ return;
+ }
+ if(settings.apiSettings) {
+ if( module.can.useAPI() ) {
+ module.queryRemote(searchTerm, function() {
+ if(settings.filterRemoteData) {
+ module.filterItems(searchTerm);
+ }
+ var preSelected = $input.val();
+ if(!Array.isArray(preSelected)) {
+ preSelected = preSelected && preSelected!=="" ? preSelected.split(settings.delimiter) : [];
+ }
+ $.each(preSelected,function(index,value){
+ $item.filter('[data-value="'+value+'"]')
+ .addClass(className.filtered)
+ ;
+ });
+ afterFiltered();
+ });
+ }
+ else {
+ module.error(error.noAPI);
+ }
+ }
+ else {
+ module.filterItems(searchTerm);
+ afterFiltered();
+ }
+ },
+
+ queryRemote: function(query, callback) {
+ var
+ apiSettings = {
+ errorDuration : false,
+ cache : 'local',
+ throttle : settings.throttle,
+ urlData : {
+ query: query
+ },
+ onError: function() {
+ module.add.message(message.serverError);
+ callback();
+ },
+ onFailure: function() {
+ module.add.message(message.serverError);
+ callback();
+ },
+ onSuccess : function(response) {
+ var
+ values = response[fields.remoteValues]
+ ;
+ if (!Array.isArray(values)){
+ values = [];
+ }
+ module.remove.message();
+ var menuConfig = {};
+ menuConfig[fields.values] = values;
+ module.setup.menu(menuConfig);
+
+ if(values.length===0 && !settings.allowAdditions) {
+ module.add.message(message.noResults);
+ }
+ callback();
+ }
+ }
+ ;
+ if( !$module.api('get request') ) {
+ module.setup.api();
+ }
+ apiSettings = $.extend(true, {}, apiSettings, settings.apiSettings);
+ $module
+ .api('setting', apiSettings)
+ .api('query')
+ ;
+ },
+
+ filterItems: function(query) {
+ var
+ searchTerm = module.remove.diacritics(query !== undefined
+ ? query
+ : module.get.query()
+ ),
+ results = null,
+ escapedTerm = module.escape.string(searchTerm),
+ regExpFlags = (settings.ignoreSearchCase ? 'i' : '') + 'gm',
+ beginsWithRegExp = new RegExp('^' + escapedTerm, regExpFlags)
+ ;
+ // avoid loop if we're matching nothing
+ if( module.has.query() ) {
+ results = [];
+
+ module.verbose('Searching for matching values', searchTerm);
+ $item
+ .each(function(){
+ var
+ $choice = $(this),
+ text,
+ value
+ ;
+ if($choice.hasClass(className.unfilterable)) {
+ results.push(this);
+ return true;
+ }
+ if(settings.match === 'both' || settings.match === 'text') {
+ text = module.remove.diacritics(String(module.get.choiceText($choice, false)));
+ if(text.search(beginsWithRegExp) !== -1) {
+ results.push(this);
+ return true;
+ }
+ else if (settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, text)) {
+ results.push(this);
+ return true;
+ }
+ else if (settings.fullTextSearch === true && module.fuzzySearch(searchTerm, text)) {
+ results.push(this);
+ return true;
+ }
+ }
+ if(settings.match === 'both' || settings.match === 'value') {
+ value = module.remove.diacritics(String(module.get.choiceValue($choice, text)));
+ if(value.search(beginsWithRegExp) !== -1) {
+ results.push(this);
+ return true;
+ }
+ else if (settings.fullTextSearch === 'exact' && module.exactSearch(searchTerm, value)) {
+ results.push(this);
+ return true;
+ }
+ else if (settings.fullTextSearch === true && module.fuzzySearch(searchTerm, value)) {
+ results.push(this);
+ return true;
+ }
+ }
+ })
+ ;
+ }
+ module.debug('Showing only matched items', searchTerm);
+ module.remove.filteredItem();
+ if(results) {
+ $item
+ .not(results)
+ .addClass(className.filtered)
+ ;
+ }
+
+ if(!module.has.query()) {
+ $divider
+ .removeClass(className.hidden);
+ } else if(settings.hideDividers === true) {
+ $divider
+ .addClass(className.hidden);
+ } else if(settings.hideDividers === 'empty') {
+ $divider
+ .removeClass(className.hidden)
+ .filter(function() {
+ // First find the last divider in this divider group
+ // Dividers which are direct siblings are considered a group
+ var lastDivider = $(this).nextUntil(selector.item);
+
+ return (lastDivider.length ? lastDivider : $(this))
+ // Count all non-filtered items until the next divider (or end of the dropdown)
+ .nextUntil(selector.divider)
+ .filter(selector.item + ":not(." + className.filtered + ")")
+ // Hide divider if no items are found
+ .length === 0;
+ })
+ .addClass(className.hidden);
+ }
+ },
+
+ fuzzySearch: function(query, term) {
+ var
+ termLength = term.length,
+ queryLength = query.length
+ ;
+ query = (settings.ignoreSearchCase ? query.toLowerCase() : query);
+ term = (settings.ignoreSearchCase ? term.toLowerCase() : term);
+ if(queryLength > termLength) {
+ return false;
+ }
+ if(queryLength === termLength) {
+ return (query === term);
+ }
+ search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
+ var
+ queryCharacter = query.charCodeAt(characterIndex)
+ ;
+ while(nextCharacterIndex < termLength) {
+ if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
+ continue search;
+ }
+ }
+ return false;
+ }
+ return true;
+ },
+ exactSearch: function (query, term) {
+ query = (settings.ignoreSearchCase ? query.toLowerCase() : query);
+ term = (settings.ignoreSearchCase ? term.toLowerCase() : term);
+ return term.indexOf(query) > -1;
+
+ },
+ filterActive: function() {
+ if(settings.useLabels) {
+ $item.filter('.' + className.active)
+ .addClass(className.filtered)
+ ;
+ }
+ },
+
+ focusSearch: function(skipHandler) {
+ if( module.has.search() && !module.is.focusedOnSearch() ) {
+ if(skipHandler) {
+ $module.off('focus' + eventNamespace, selector.search);
+ $search.focus();
+ $module.on('focus' + eventNamespace, selector.search, module.event.search.focus);
+ }
+ else {
+ $search.focus();
+ }
+ }
+ },
+
+ blurSearch: function() {
+ if( module.has.search() ) {
+ $search.blur();
+ }
+ },
+
+ forceSelection: function() {
+ var
+ $currentlySelected = $item.not(className.filtered).filter('.' + className.selected).eq(0),
+ $activeItem = $item.not(className.filtered).filter('.' + className.active).eq(0),
+ $selectedItem = ($currentlySelected.length > 0)
+ ? $currentlySelected
+ : $activeItem,
+ hasSelected = ($selectedItem.length > 0)
+ ;
+ if(settings.allowAdditions || (hasSelected && !module.is.multiple())) {
+ module.debug('Forcing partial selection to selected item', $selectedItem);
+ module.event.item.click.call($selectedItem, {}, true);
+ }
+ else {
+ module.remove.searchTerm();
+ }
+ },
+
+ change: {
+ values: function(values) {
+ if(!settings.allowAdditions) {
+ module.clear();
+ }
+ module.debug('Creating dropdown with specified values', values);
+ var menuConfig = {};
+ menuConfig[fields.values] = values;
+ module.setup.menu(menuConfig);
+ $.each(values, function(index, item) {
+ if(item.selected == true) {
+ module.debug('Setting initial selection to', item[fields.value]);
+ module.set.selected(item[fields.value]);
+ if(!module.is.multiple()) {
+ return false;
+ }
+ }
+ });
+
+ if(module.has.selectInput()) {
+ module.disconnect.selectObserver();
+ $input.html('');
+ $input.append('');
+ $.each(values, function(index, item) {
+ var
+ value = settings.templates.deQuote(item[fields.value]),
+ name = settings.templates.escape(
+ item[fields.name] || '',
+ settings.preserveHTML
+ )
+ ;
+ $input.append('');
+ });
+ module.observe.select();
+ }
+ }
+ },
+
+ event: {
+ change: function() {
+ if(!internalChange) {
+ module.debug('Input changed, updating selection');
+ module.set.selected();
+ }
+ },
+ focus: function() {
+ if(settings.showOnFocus && !activated && module.is.hidden() && !pageLostFocus) {
+ module.show();
+ }
+ },
+ blur: function(event) {
+ pageLostFocus = (document.activeElement === this);
+ if(!activated && !pageLostFocus) {
+ module.remove.activeLabel();
+ module.hide();
+ }
+ },
+ mousedown: function() {
+ if(module.is.searchSelection()) {
+ // prevent menu hiding on immediate re-focus
+ willRefocus = true;
+ }
+ else {
+ // prevents focus callback from occurring on mousedown
+ activated = true;
+ }
+ },
+ mouseup: function() {
+ if(module.is.searchSelection()) {
+ // prevent menu hiding on immediate re-focus
+ willRefocus = false;
+ }
+ else {
+ activated = false;
+ }
+ },
+ click: function(event) {
+ var
+ $target = $(event.target)
+ ;
+ // focus search
+ if($target.is($module)) {
+ if(!module.is.focusedOnSearch()) {
+ module.focusSearch();
+ }
+ else {
+ module.show();
+ }
+ }
+ },
+ search: {
+ focus: function(event) {
+ activated = true;
+ if(module.is.multiple()) {
+ module.remove.activeLabel();
+ }
+ if(settings.showOnFocus || (event.type !== 'focus' && event.type !== 'focusin')) {
+ module.search();
+ }
+ },
+ blur: function(event) {
+ pageLostFocus = (document.activeElement === this);
+ if(module.is.searchSelection() && !willRefocus) {
+ if(!itemActivated && !pageLostFocus) {
+ if(settings.forceSelection) {
+ module.forceSelection();
+ } else if(!settings.allowAdditions){
+ module.remove.searchTerm();
+ }
+ module.hide();
+ }
+ }
+ willRefocus = false;
+ }
+ },
+ clearIcon: {
+ click: function(event) {
+ module.clear();
+ if(module.is.searchSelection()) {
+ module.remove.searchTerm();
+ }
+ module.hide();
+ event.stopPropagation();
+ }
+ },
+ icon: {
+ click: function(event) {
+ iconClicked=true;
+ if(module.has.search()) {
+ if(!module.is.active()) {
+ if(settings.showOnFocus){
+ module.focusSearch();
+ } else {
+ module.toggle();
+ }
+ } else {
+ module.blurSearch();
+ }
+ } else {
+ module.toggle();
+ }
+ }
+ },
+ text: {
+ focus: function(event) {
+ activated = true;
+ module.focusSearch();
+ }
+ },
+ input: function(event) {
+ if(module.is.multiple() || module.is.searchSelection()) {
+ module.set.filtered();
+ }
+ clearTimeout(module.timer);
+ module.timer = setTimeout(module.search, settings.delay.search);
+ },
+ label: {
+ click: function(event) {
+ var
+ $label = $(this),
+ $labels = $module.find(selector.label),
+ $activeLabels = $labels.filter('.' + className.active),
+ $nextActive = $label.nextAll('.' + className.active),
+ $prevActive = $label.prevAll('.' + className.active),
+ $range = ($nextActive.length > 0)
+ ? $label.nextUntil($nextActive).add($activeLabels).add($label)
+ : $label.prevUntil($prevActive).add($activeLabels).add($label)
+ ;
+ if(event.shiftKey) {
+ $activeLabels.removeClass(className.active);
+ $range.addClass(className.active);
+ }
+ else if(event.ctrlKey) {
+ $label.toggleClass(className.active);
+ }
+ else {
+ $activeLabels.removeClass(className.active);
+ $label.addClass(className.active);
+ }
+ settings.onLabelSelect.apply(this, $labels.filter('.' + className.active));
+ }
+ },
+ remove: {
+ click: function() {
+ var
+ $label = $(this).parent()
+ ;
+ if( $label.hasClass(className.active) ) {
+ // remove all selected labels
+ module.remove.activeLabels();
+ }
+ else {
+ // remove this label only
+ module.remove.activeLabels( $label );
+ }
+ }
+ },
+ test: {
+ toggle: function(event) {
+ var
+ toggleBehavior = (module.is.multiple())
+ ? module.show
+ : module.toggle
+ ;
+ if(module.is.bubbledLabelClick(event) || module.is.bubbledIconClick(event)) {
+ return;
+ }
+ if( module.determine.eventOnElement(event, toggleBehavior) ) {
+ event.preventDefault();
+ }
+ },
+ touch: function(event) {
+ module.determine.eventOnElement(event, function() {
+ if(event.type == 'touchstart') {
+ module.timer = setTimeout(function() {
+ module.hide();
+ }, settings.delay.touch);
+ }
+ else if(event.type == 'touchmove') {
+ clearTimeout(module.timer);
+ }
+ });
+ event.stopPropagation();
+ },
+ hide: function(event) {
+ if(module.determine.eventInModule(event, module.hide)){
+ if(element.id && $(event.target).attr('for') === element.id){
+ event.preventDefault();
+ }
+ }
+ }
+ },
+ class: {
+ mutation: function(mutations) {
+ mutations.forEach(function(mutation) {
+ if(mutation.attributeName === "class") {
+ module.check.disabled();
+ }
+ });
+ }
+ },
+ select: {
+ mutation: function(mutations) {
+ module.debug('