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

auth_openid.go 13 kB

Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. "fmt"
  7. "net/url"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/auth"
  10. "code.gitea.io/gitea/modules/auth/openid"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/generate"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/recaptcha"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/go-macaron/captcha"
  18. )
  19. const (
  20. tplSignInOpenID base.TplName = "user/auth/signin_openid"
  21. tplConnectOID base.TplName = "user/auth/signup_openid_connect"
  22. tplSignUpOID base.TplName = "user/auth/signup_openid_register"
  23. )
  24. // SignInOpenID render sign in page
  25. func SignInOpenID(ctx *context.Context) {
  26. ctx.Data["Title"] = ctx.Tr("sign_in")
  27. if ctx.Query("openid.return_to") != "" {
  28. signInOpenIDVerify(ctx)
  29. return
  30. }
  31. // Check auto-login.
  32. isSucceed, err := AutoSignIn(ctx)
  33. if err != nil {
  34. ctx.ServerError("AutoSignIn", err)
  35. return
  36. }
  37. redirectTo := ctx.Query("redirect_to")
  38. if len(redirectTo) > 0 {
  39. ctx.SetCookie("redirect_to", redirectTo, 0, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  40. } else {
  41. redirectTo = ctx.GetCookie("redirect_to")
  42. }
  43. if isSucceed {
  44. ctx.SetCookie("redirect_to", "", -1, setting.AppSubURL, "", setting.SessionConfig.Secure, true)
  45. ctx.RedirectToFirst(redirectTo)
  46. return
  47. }
  48. ctx.Data["PageIsSignIn"] = true
  49. ctx.Data["PageIsLoginOpenID"] = true
  50. ctx.HTML(200, tplSignInOpenID)
  51. }
  52. // Check if the given OpenID URI is allowed by blacklist/whitelist
  53. func allowedOpenIDURI(uri string) (err error) {
  54. // In case a Whitelist is present, URI must be in it
  55. // in order to be accepted
  56. if len(setting.Service.OpenIDWhitelist) != 0 {
  57. for _, pat := range setting.Service.OpenIDWhitelist {
  58. if pat.MatchString(uri) {
  59. return nil // pass
  60. }
  61. }
  62. // must match one of this or be refused
  63. return fmt.Errorf("URI not allowed by whitelist")
  64. }
  65. // A blacklist match expliclty forbids
  66. for _, pat := range setting.Service.OpenIDBlacklist {
  67. if pat.MatchString(uri) {
  68. return fmt.Errorf("URI forbidden by blacklist")
  69. }
  70. }
  71. return nil
  72. }
  73. // SignInOpenIDPost response for openid sign in request
  74. func SignInOpenIDPost(ctx *context.Context, form auth.SignInOpenIDForm) {
  75. ctx.Data["Title"] = ctx.Tr("sign_in")
  76. ctx.Data["PageIsSignIn"] = true
  77. ctx.Data["PageIsLoginOpenID"] = true
  78. if ctx.HasError() {
  79. ctx.HTML(200, tplSignInOpenID)
  80. return
  81. }
  82. id, err := openid.Normalize(form.Openid)
  83. if err != nil {
  84. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &form)
  85. return
  86. }
  87. form.Openid = id
  88. log.Trace("OpenID uri: " + id)
  89. err = allowedOpenIDURI(id)
  90. if err != nil {
  91. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &form)
  92. return
  93. }
  94. redirectTo := setting.AppURL + "user/login/openid"
  95. url, err := openid.RedirectURL(id, redirectTo, setting.AppURL)
  96. if err != nil {
  97. log.Error("Error in OpenID redirect URL: %s, %v", redirectTo, err.Error())
  98. ctx.RenderWithErr(fmt.Sprintf("Unable to find OpenID provider in %s", redirectTo), tplSignInOpenID, &form)
  99. return
  100. }
  101. // Request optional nickname and email info
  102. // NOTE: change to `openid.sreg.required` to require it
  103. url += "&openid.ns.sreg=http%3A%2F%2Fopenid.net%2Fextensions%2Fsreg%2F1.1"
  104. url += "&openid.sreg.optional=nickname%2Cemail"
  105. log.Trace("Form-passed openid-remember: %t", form.Remember)
  106. ctx.Session.Set("openid_signin_remember", form.Remember)
  107. ctx.Redirect(url)
  108. }
  109. // signInOpenIDVerify handles response from OpenID provider
  110. func signInOpenIDVerify(ctx *context.Context) {
  111. log.Trace("Incoming call to: " + ctx.Req.Request.URL.String())
  112. fullURL := setting.AppURL + ctx.Req.Request.URL.String()[1:]
  113. log.Trace("Full URL: " + fullURL)
  114. var id, err = openid.Verify(fullURL)
  115. if err != nil {
  116. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  117. Openid: id,
  118. })
  119. return
  120. }
  121. log.Trace("Verified ID: " + id)
  122. /* Now we should seek for the user and log him in, or prompt
  123. * to register if not found */
  124. u, _ := models.GetUserByOpenID(id)
  125. if err != nil {
  126. if !models.IsErrUserNotExist(err) {
  127. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  128. Openid: id,
  129. })
  130. return
  131. }
  132. }
  133. if u != nil {
  134. log.Trace("User exists, logging in")
  135. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  136. log.Trace("Session stored openid-remember: %t", remember)
  137. handleSignIn(ctx, u, remember)
  138. return
  139. }
  140. log.Trace("User with openid " + id + " does not exist, should connect or register")
  141. parsedURL, err := url.Parse(fullURL)
  142. if err != nil {
  143. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  144. Openid: id,
  145. })
  146. return
  147. }
  148. values, err := url.ParseQuery(parsedURL.RawQuery)
  149. if err != nil {
  150. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  151. Openid: id,
  152. })
  153. return
  154. }
  155. email := values.Get("openid.sreg.email")
  156. nickname := values.Get("openid.sreg.nickname")
  157. log.Trace("User has email=" + email + " and nickname=" + nickname)
  158. if email != "" {
  159. u, _ = models.GetUserByEmail(email)
  160. if err != nil {
  161. if !models.IsErrUserNotExist(err) {
  162. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  163. Openid: id,
  164. })
  165. return
  166. }
  167. }
  168. if u != nil {
  169. log.Trace("Local user " + u.LowerName + " has OpenID provided email " + email)
  170. }
  171. }
  172. if u == nil && nickname != "" {
  173. u, _ = models.GetUserByName(nickname)
  174. if err != nil {
  175. if !models.IsErrUserNotExist(err) {
  176. ctx.RenderWithErr(err.Error(), tplSignInOpenID, &auth.SignInOpenIDForm{
  177. Openid: id,
  178. })
  179. return
  180. }
  181. }
  182. if u != nil {
  183. log.Trace("Local user " + u.LowerName + " has OpenID provided nickname " + nickname)
  184. }
  185. }
  186. ctx.Session.Set("openid_verified_uri", id)
  187. ctx.Session.Set("openid_determined_email", email)
  188. if u != nil {
  189. nickname = u.LowerName
  190. }
  191. ctx.Session.Set("openid_determined_username", nickname)
  192. if u != nil || !setting.Service.EnableOpenIDSignUp {
  193. ctx.Redirect(setting.AppSubURL + "/user/openid/connect")
  194. } else {
  195. ctx.Redirect(setting.AppSubURL + "/user/openid/register")
  196. }
  197. }
  198. // ConnectOpenID shows a form to connect an OpenID URI to an existing account
  199. func ConnectOpenID(ctx *context.Context) {
  200. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  201. if oid == "" {
  202. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  203. return
  204. }
  205. ctx.Data["Title"] = "OpenID connect"
  206. ctx.Data["PageIsSignIn"] = true
  207. ctx.Data["PageIsOpenIDConnect"] = true
  208. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  209. ctx.Data["OpenID"] = oid
  210. userName, _ := ctx.Session.Get("openid_determined_username").(string)
  211. if userName != "" {
  212. ctx.Data["user_name"] = userName
  213. }
  214. ctx.HTML(200, tplConnectOID)
  215. }
  216. // ConnectOpenIDPost handles submission of a form to connect an OpenID URI to an existing account
  217. func ConnectOpenIDPost(ctx *context.Context, form auth.ConnectOpenIDForm) {
  218. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  219. if oid == "" {
  220. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  221. return
  222. }
  223. ctx.Data["Title"] = "OpenID connect"
  224. ctx.Data["PageIsSignIn"] = true
  225. ctx.Data["PageIsOpenIDConnect"] = true
  226. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  227. ctx.Data["OpenID"] = oid
  228. u, err := models.UserSignIn(form.UserName, form.Password)
  229. if err != nil {
  230. if models.IsErrUserNotExist(err) {
  231. ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplConnectOID, &form)
  232. } else {
  233. ctx.ServerError("ConnectOpenIDPost", err)
  234. }
  235. return
  236. }
  237. // add OpenID for the user
  238. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  239. if err = models.AddUserOpenID(userOID); err != nil {
  240. if models.IsErrOpenIDAlreadyUsed(err) {
  241. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplConnectOID, &form)
  242. return
  243. }
  244. ctx.ServerError("AddUserOpenID", err)
  245. return
  246. }
  247. ctx.Flash.Success(ctx.Tr("settings.add_openid_success"))
  248. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  249. log.Trace("Session stored openid-remember: %t", remember)
  250. handleSignIn(ctx, u, remember)
  251. }
  252. // RegisterOpenID shows a form to create a new user authenticated via an OpenID URI
  253. func RegisterOpenID(ctx *context.Context) {
  254. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  255. if oid == "" {
  256. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  257. return
  258. }
  259. ctx.Data["Title"] = "OpenID signup"
  260. ctx.Data["PageIsSignIn"] = true
  261. ctx.Data["PageIsOpenIDRegister"] = true
  262. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  263. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  264. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  265. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  266. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  267. ctx.Data["OpenID"] = oid
  268. userName, _ := ctx.Session.Get("openid_determined_username").(string)
  269. if userName != "" {
  270. ctx.Data["user_name"] = userName
  271. }
  272. email, _ := ctx.Session.Get("openid_determined_email").(string)
  273. if email != "" {
  274. ctx.Data["email"] = email
  275. }
  276. ctx.HTML(200, tplSignUpOID)
  277. }
  278. // RegisterOpenIDPost handles submission of a form to create a new user authenticated via an OpenID URI
  279. func RegisterOpenIDPost(ctx *context.Context, cpt *captcha.Captcha, form auth.SignUpOpenIDForm) {
  280. oid, _ := ctx.Session.Get("openid_verified_uri").(string)
  281. if oid == "" {
  282. ctx.Redirect(setting.AppSubURL + "/user/login/openid")
  283. return
  284. }
  285. ctx.Data["Title"] = "OpenID signup"
  286. ctx.Data["PageIsSignIn"] = true
  287. ctx.Data["PageIsOpenIDRegister"] = true
  288. ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp
  289. ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha
  290. ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL
  291. ctx.Data["CaptchaType"] = setting.Service.CaptchaType
  292. ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey
  293. ctx.Data["OpenID"] = oid
  294. if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ImageCaptcha && !cpt.VerifyReq(ctx.Req) {
  295. ctx.Data["Err_Captcha"] = true
  296. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  297. return
  298. }
  299. if setting.Service.EnableCaptcha && setting.Service.CaptchaType == setting.ReCaptcha {
  300. ctx.Req.ParseForm()
  301. valid, _ := recaptcha.Verify(form.GRecaptchaResponse)
  302. if !valid {
  303. ctx.Data["Err_Captcha"] = true
  304. ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form)
  305. return
  306. }
  307. }
  308. length := setting.MinPasswordLength
  309. if length < 256 {
  310. length = 256
  311. }
  312. password, err := generate.GetRandomString(length)
  313. if err != nil {
  314. ctx.RenderWithErr(err.Error(), tplSignUpOID, form)
  315. return
  316. }
  317. // TODO: abstract a finalizeSignUp function ?
  318. u := &models.User{
  319. Name: form.UserName,
  320. Email: form.Email,
  321. Passwd: password,
  322. IsActive: !setting.Service.RegisterEmailConfirm,
  323. }
  324. if err := models.CreateUser(u); err != nil {
  325. switch {
  326. case models.IsErrUserAlreadyExist(err):
  327. ctx.Data["Err_UserName"] = true
  328. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplSignUpOID, &form)
  329. case models.IsErrEmailAlreadyUsed(err):
  330. ctx.Data["Err_Email"] = true
  331. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignUpOID, &form)
  332. case models.IsErrNameReserved(err):
  333. ctx.Data["Err_UserName"] = true
  334. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplSignUpOID, &form)
  335. case models.IsErrNamePatternNotAllowed(err):
  336. ctx.Data["Err_UserName"] = true
  337. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSignUpOID, &form)
  338. default:
  339. ctx.ServerError("CreateUser", err)
  340. }
  341. return
  342. }
  343. log.Trace("Account created: %s", u.Name)
  344. // add OpenID for the user
  345. userOID := &models.UserOpenID{UID: u.ID, URI: oid}
  346. if err = models.AddUserOpenID(userOID); err != nil {
  347. if models.IsErrOpenIDAlreadyUsed(err) {
  348. ctx.RenderWithErr(ctx.Tr("form.openid_been_used", oid), tplSignUpOID, &form)
  349. return
  350. }
  351. ctx.ServerError("AddUserOpenID", err)
  352. return
  353. }
  354. // Auto-set admin for the only user.
  355. if models.CountUsers() == 1 {
  356. u.IsAdmin = true
  357. u.IsActive = true
  358. u.SetLastLogin()
  359. if err := models.UpdateUserCols(u, "is_admin", "is_active", "last_login_unix"); err != nil {
  360. ctx.ServerError("UpdateUser", err)
  361. return
  362. }
  363. }
  364. // Send confirmation email, no need for social account.
  365. if setting.Service.RegisterEmailConfirm && u.ID > 1 {
  366. models.SendActivateAccountMail(ctx.Context, u)
  367. ctx.Data["IsSendRegisterMail"] = true
  368. ctx.Data["Email"] = u.Email
  369. ctx.Data["ActiveCodeLives"] = base.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale.Language())
  370. ctx.HTML(200, TplActivate)
  371. if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
  372. log.Error("Set cache(MailResendLimit) fail: %v", err)
  373. }
  374. return
  375. }
  376. remember, _ := ctx.Session.Get("openid_signin_remember").(bool)
  377. log.Trace("Session stored openid-remember: %t", remember)
  378. handleSignIn(ctx, u, remember)
  379. }