You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

316 lines
8.5 KiB

Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mux
  5. import (
  6. "bytes"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. )
  14. // newRouteRegexp parses a route template and returns a routeRegexp,
  15. // used to match a host, a path or a query string.
  16. //
  17. // It will extract named variables, assemble a regexp to be matched, create
  18. // a "reverse" template to build URLs and compile regexps to validate variable
  19. // values used in URL building.
  20. //
  21. // Previously we accepted only Python-like identifiers for variable
  22. // names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
  23. // name and pattern can't be empty, and names can't contain a colon.
  24. func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) {
  25. // Check if it is well-formed.
  26. idxs, errBraces := braceIndices(tpl)
  27. if errBraces != nil {
  28. return nil, errBraces
  29. }
  30. // Backup the original.
  31. template := tpl
  32. // Now let's parse it.
  33. defaultPattern := "[^/]+"
  34. if matchQuery {
  35. defaultPattern = "[^?&]*"
  36. } else if matchHost {
  37. defaultPattern = "[^.]+"
  38. matchPrefix = false
  39. }
  40. // Only match strict slash if not matching
  41. if matchPrefix || matchHost || matchQuery {
  42. strictSlash = false
  43. }
  44. // Set a flag for strictSlash.
  45. endSlash := false
  46. if strictSlash && strings.HasSuffix(tpl, "/") {
  47. tpl = tpl[:len(tpl)-1]
  48. endSlash = true
  49. }
  50. varsN := make([]string, len(idxs)/2)
  51. varsR := make([]*regexp.Regexp, len(idxs)/2)
  52. pattern := bytes.NewBufferString("")
  53. pattern.WriteByte('^')
  54. reverse := bytes.NewBufferString("")
  55. var end int
  56. var err error
  57. for i := 0; i < len(idxs); i += 2 {
  58. // Set all values we are interested in.
  59. raw := tpl[end:idxs[i]]
  60. end = idxs[i+1]
  61. parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
  62. name := parts[0]
  63. patt := defaultPattern
  64. if len(parts) == 2 {
  65. patt = parts[1]
  66. }
  67. // Name or pattern can't be empty.
  68. if name == "" || patt == "" {
  69. return nil, fmt.Errorf("mux: missing name or pattern in %q",
  70. tpl[idxs[i]:end])
  71. }
  72. // Build the regexp pattern.
  73. fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt)
  74. // Build the reverse template.
  75. fmt.Fprintf(reverse, "%s%%s", raw)
  76. // Append variable name and compiled pattern.
  77. varsN[i/2] = name
  78. varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
  79. if err != nil {
  80. return nil, err
  81. }
  82. }
  83. // Add the remaining.
  84. raw := tpl[end:]
  85. pattern.WriteString(regexp.QuoteMeta(raw))
  86. if strictSlash {
  87. pattern.WriteString("[/]?")
  88. }
  89. if matchQuery {
  90. // Add the default pattern if the query value is empty
  91. if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
  92. pattern.WriteString(defaultPattern)
  93. }
  94. }
  95. if !matchPrefix {
  96. pattern.WriteByte('$')
  97. }
  98. reverse.WriteString(raw)
  99. if endSlash {
  100. reverse.WriteByte('/')
  101. }
  102. // Compile full regexp.
  103. reg, errCompile := regexp.Compile(pattern.String())
  104. if errCompile != nil {
  105. return nil, errCompile
  106. }
  107. // Done!
  108. return &routeRegexp{
  109. template: template,
  110. matchHost: matchHost,
  111. matchQuery: matchQuery,
  112. strictSlash: strictSlash,
  113. useEncodedPath: useEncodedPath,
  114. regexp: reg,
  115. reverse: reverse.String(),
  116. varsN: varsN,
  117. varsR: varsR,
  118. }, nil
  119. }
  120. // routeRegexp stores a regexp to match a host or path and information to
  121. // collect and validate route variables.
  122. type routeRegexp struct {
  123. // The unmodified template.
  124. template string
  125. // True for host match, false for path or query string match.
  126. matchHost bool
  127. // True for query string match, false for path and host match.
  128. matchQuery bool
  129. // The strictSlash value defined on the route, but disabled if PathPrefix was used.
  130. strictSlash bool
  131. // Determines whether to use encoded path from getPath function or unencoded
  132. // req.URL.Path for path matching
  133. useEncodedPath bool
  134. // Expanded regexp.
  135. regexp *regexp.Regexp
  136. // Reverse template.
  137. reverse string
  138. // Variable names.
  139. varsN []string
  140. // Variable regexps (validators).
  141. varsR []*regexp.Regexp
  142. }
  143. // Match matches the regexp against the URL host or path.
  144. func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
  145. if !r.matchHost {
  146. if r.matchQuery {
  147. return r.matchQueryString(req)
  148. }
  149. path := req.URL.Path
  150. if r.useEncodedPath {
  151. path = getPath(req)
  152. }
  153. return r.regexp.MatchString(path)
  154. }
  155. return r.regexp.MatchString(getHost(req))
  156. }
  157. // url builds a URL part using the given values.
  158. func (r *routeRegexp) url(values map[string]string) (string, error) {
  159. urlValues := make([]interface{}, len(r.varsN))
  160. for k, v := range r.varsN {
  161. value, ok := values[v]
  162. if !ok {
  163. return "", fmt.Errorf("mux: missing route variable %q", v)
  164. }
  165. urlValues[k] = value
  166. }
  167. rv := fmt.Sprintf(r.reverse, urlValues...)
  168. if !r.regexp.MatchString(rv) {
  169. // The URL is checked against the full regexp, instead of checking
  170. // individual variables. This is faster but to provide a good error
  171. // message, we check individual regexps if the URL doesn't match.
  172. for k, v := range r.varsN {
  173. if !r.varsR[k].MatchString(values[v]) {
  174. return "", fmt.Errorf(
  175. "mux: variable %q doesn't match, expected %q", values[v],
  176. r.varsR[k].String())
  177. }
  178. }
  179. }
  180. return rv, nil
  181. }
  182. // getURLQuery returns a single query parameter from a request URL.
  183. // For a URL with foo=bar&baz=ding, we return only the relevant key
  184. // value pair for the routeRegexp.
  185. func (r *routeRegexp) getURLQuery(req *http.Request) string {
  186. if !r.matchQuery {
  187. return ""
  188. }
  189. templateKey := strings.SplitN(r.template, "=", 2)[0]
  190. for key, vals := range req.URL.Query() {
  191. if key == templateKey && len(vals) > 0 {
  192. return key + "=" + vals[0]
  193. }
  194. }
  195. return ""
  196. }
  197. func (r *routeRegexp) matchQueryString(req *http.Request) bool {
  198. return r.regexp.MatchString(r.getURLQuery(req))
  199. }
  200. // braceIndices returns the first level curly brace indices from a string.
  201. // It returns an error in case of unbalanced braces.
  202. func braceIndices(s string) ([]int, error) {
  203. var level, idx int
  204. var idxs []int
  205. for i := 0; i < len(s); i++ {
  206. switch s[i] {
  207. case '{':
  208. if level++; level == 1 {
  209. idx = i
  210. }
  211. case '}':
  212. if level--; level == 0 {
  213. idxs = append(idxs, idx, i+1)
  214. } else if level < 0 {
  215. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  216. }
  217. }
  218. }
  219. if level != 0 {
  220. return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
  221. }
  222. return idxs, nil
  223. }
  224. // varGroupName builds a capturing group name for the indexed variable.
  225. func varGroupName(idx int) string {
  226. return "v" + strconv.Itoa(idx)
  227. }
  228. // ----------------------------------------------------------------------------
  229. // routeRegexpGroup
  230. // ----------------------------------------------------------------------------
  231. // routeRegexpGroup groups the route matchers that carry variables.
  232. type routeRegexpGroup struct {
  233. host *routeRegexp
  234. path *routeRegexp
  235. queries []*routeRegexp
  236. }
  237. // setMatch extracts the variables from the URL once a route matches.
  238. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
  239. // Store host variables.
  240. if v.host != nil {
  241. host := getHost(req)
  242. matches := v.host.regexp.FindStringSubmatchIndex(host)
  243. if len(matches) > 0 {
  244. extractVars(host, matches, v.host.varsN, m.Vars)
  245. }
  246. }
  247. path := req.URL.Path
  248. if r.useEncodedPath {
  249. path = getPath(req)
  250. }
  251. // Store path variables.
  252. if v.path != nil {
  253. matches := v.path.regexp.FindStringSubmatchIndex(path)
  254. if len(matches) > 0 {
  255. extractVars(path, matches, v.path.varsN, m.Vars)
  256. // Check if we should redirect.
  257. if v.path.strictSlash {
  258. p1 := strings.HasSuffix(path, "/")
  259. p2 := strings.HasSuffix(v.path.template, "/")
  260. if p1 != p2 {
  261. u, _ := url.Parse(req.URL.String())
  262. if p1 {
  263. u.Path = u.Path[:len(u.Path)-1]
  264. } else {
  265. u.Path += "/"
  266. }
  267. m.Handler = http.RedirectHandler(u.String(), 301)
  268. }
  269. }
  270. }
  271. }
  272. // Store query string variables.
  273. for _, q := range v.queries {
  274. queryURL := q.getURLQuery(req)
  275. matches := q.regexp.FindStringSubmatchIndex(queryURL)
  276. if len(matches) > 0 {
  277. extractVars(queryURL, matches, q.varsN, m.Vars)
  278. }
  279. }
  280. }
  281. // getHost tries its best to return the request host.
  282. func getHost(r *http.Request) string {
  283. if r.URL.IsAbs() {
  284. return r.URL.Host
  285. }
  286. host := r.Host
  287. // Slice off any port information.
  288. if i := strings.Index(host, ":"); i != -1 {
  289. host = host[:i]
  290. }
  291. return host
  292. }
  293. func extractVars(input string, matches []int, names []string, output map[string]string) {
  294. for i, name := range names {
  295. output[name] = input[matches[2*i+2]:matches[2*i+3]]
  296. }
  297. }