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.

auths.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. // Copyright 2014 The Gogs 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 admin
  5. import (
  6. "errors"
  7. "fmt"
  8. "regexp"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/auth/ldap"
  12. "code.gitea.io/gitea/modules/auth/oauth2"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. "github.com/unknwon/com"
  19. "xorm.io/core"
  20. )
  21. const (
  22. tplAuths base.TplName = "admin/auth/list"
  23. tplAuthNew base.TplName = "admin/auth/new"
  24. tplAuthEdit base.TplName = "admin/auth/edit"
  25. )
  26. var (
  27. separatorAntiPattern = regexp.MustCompile(`[^\w-\.]`)
  28. langCodePattern = regexp.MustCompile(`^[a-z]{2}-[A-Z]{2}$`)
  29. )
  30. // Authentications show authentication config page
  31. func Authentications(ctx *context.Context) {
  32. ctx.Data["Title"] = ctx.Tr("admin.authentication")
  33. ctx.Data["PageIsAdmin"] = true
  34. ctx.Data["PageIsAdminAuthentications"] = true
  35. var err error
  36. ctx.Data["Sources"], err = models.LoginSources()
  37. if err != nil {
  38. ctx.ServerError("LoginSources", err)
  39. return
  40. }
  41. ctx.Data["Total"] = models.CountLoginSources()
  42. ctx.HTML(200, tplAuths)
  43. }
  44. type dropdownItem struct {
  45. Name string
  46. Type interface{}
  47. }
  48. var (
  49. authSources = []dropdownItem{
  50. {models.LoginNames[models.LoginLDAP], models.LoginLDAP},
  51. {models.LoginNames[models.LoginDLDAP], models.LoginDLDAP},
  52. {models.LoginNames[models.LoginSMTP], models.LoginSMTP},
  53. {models.LoginNames[models.LoginPAM], models.LoginPAM},
  54. {models.LoginNames[models.LoginOAuth2], models.LoginOAuth2},
  55. {models.LoginNames[models.LoginSSPI], models.LoginSSPI},
  56. }
  57. securityProtocols = []dropdownItem{
  58. {models.SecurityProtocolNames[ldap.SecurityProtocolUnencrypted], ldap.SecurityProtocolUnencrypted},
  59. {models.SecurityProtocolNames[ldap.SecurityProtocolLDAPS], ldap.SecurityProtocolLDAPS},
  60. {models.SecurityProtocolNames[ldap.SecurityProtocolStartTLS], ldap.SecurityProtocolStartTLS},
  61. }
  62. )
  63. // NewAuthSource render adding a new auth source page
  64. func NewAuthSource(ctx *context.Context) {
  65. ctx.Data["Title"] = ctx.Tr("admin.auths.new")
  66. ctx.Data["PageIsAdmin"] = true
  67. ctx.Data["PageIsAdminAuthentications"] = true
  68. ctx.Data["type"] = models.LoginLDAP
  69. ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginLDAP]
  70. ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocolUnencrypted]
  71. ctx.Data["smtp_auth"] = "PLAIN"
  72. ctx.Data["is_active"] = true
  73. ctx.Data["is_sync_enabled"] = true
  74. ctx.Data["AuthSources"] = authSources
  75. ctx.Data["SecurityProtocols"] = securityProtocols
  76. ctx.Data["SMTPAuths"] = models.SMTPAuths
  77. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  78. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  79. ctx.Data["SSPIAutoCreateUsers"] = true
  80. ctx.Data["SSPIAutoActivateUsers"] = true
  81. ctx.Data["SSPIStripDomainNames"] = true
  82. ctx.Data["SSPISeparatorReplacement"] = "_"
  83. ctx.Data["SSPIDefaultLanguage"] = ""
  84. // only the first as default
  85. for key := range models.OAuth2Providers {
  86. ctx.Data["oauth2_provider"] = key
  87. break
  88. }
  89. ctx.HTML(200, tplAuthNew)
  90. }
  91. func parseLDAPConfig(form auth.AuthenticationForm) *models.LDAPConfig {
  92. var pageSize uint32
  93. if form.UsePagedSearch {
  94. pageSize = uint32(form.SearchPageSize)
  95. }
  96. return &models.LDAPConfig{
  97. Source: &ldap.Source{
  98. Name: form.Name,
  99. Host: form.Host,
  100. Port: form.Port,
  101. SecurityProtocol: ldap.SecurityProtocol(form.SecurityProtocol),
  102. SkipVerify: form.SkipVerify,
  103. BindDN: form.BindDN,
  104. UserDN: form.UserDN,
  105. BindPassword: form.BindPassword,
  106. UserBase: form.UserBase,
  107. AttributeUsername: form.AttributeUsername,
  108. AttributeName: form.AttributeName,
  109. AttributeSurname: form.AttributeSurname,
  110. AttributeMail: form.AttributeMail,
  111. AttributesInBind: form.AttributesInBind,
  112. AttributeSSHPublicKey: form.AttributeSSHPublicKey,
  113. SearchPageSize: pageSize,
  114. Filter: form.Filter,
  115. AdminFilter: form.AdminFilter,
  116. AllowDeactivateAll: form.AllowDeactivateAll,
  117. Enabled: true,
  118. },
  119. }
  120. }
  121. func parseSMTPConfig(form auth.AuthenticationForm) *models.SMTPConfig {
  122. return &models.SMTPConfig{
  123. Auth: form.SMTPAuth,
  124. Host: form.SMTPHost,
  125. Port: form.SMTPPort,
  126. AllowedDomains: form.AllowedDomains,
  127. TLS: form.TLS,
  128. SkipVerify: form.SkipVerify,
  129. }
  130. }
  131. func parseOAuth2Config(form auth.AuthenticationForm) *models.OAuth2Config {
  132. var customURLMapping *oauth2.CustomURLMapping
  133. if form.Oauth2UseCustomURL {
  134. customURLMapping = &oauth2.CustomURLMapping{
  135. TokenURL: form.Oauth2TokenURL,
  136. AuthURL: form.Oauth2AuthURL,
  137. ProfileURL: form.Oauth2ProfileURL,
  138. EmailURL: form.Oauth2EmailURL,
  139. }
  140. } else {
  141. customURLMapping = nil
  142. }
  143. return &models.OAuth2Config{
  144. Provider: form.Oauth2Provider,
  145. ClientID: form.Oauth2Key,
  146. ClientSecret: form.Oauth2Secret,
  147. OpenIDConnectAutoDiscoveryURL: form.OpenIDConnectAutoDiscoveryURL,
  148. CustomURLMapping: customURLMapping,
  149. }
  150. }
  151. func parseSSPIConfig(ctx *context.Context, form auth.AuthenticationForm) (*models.SSPIConfig, error) {
  152. if util.IsEmptyString(form.SSPISeparatorReplacement) {
  153. ctx.Data["Err_SSPISeparatorReplacement"] = true
  154. return nil, errors.New(ctx.Tr("form.SSPISeparatorReplacement") + ctx.Tr("form.require_error"))
  155. }
  156. if separatorAntiPattern.MatchString(form.SSPISeparatorReplacement) {
  157. ctx.Data["Err_SSPISeparatorReplacement"] = true
  158. return nil, errors.New(ctx.Tr("form.SSPISeparatorReplacement") + ctx.Tr("form.alpha_dash_dot_error"))
  159. }
  160. if form.SSPIDefaultLanguage != "" && !langCodePattern.MatchString(form.SSPIDefaultLanguage) {
  161. ctx.Data["Err_SSPIDefaultLanguage"] = true
  162. return nil, errors.New(ctx.Tr("form.lang_select_error"))
  163. }
  164. return &models.SSPIConfig{
  165. AutoCreateUsers: form.SSPIAutoCreateUsers,
  166. AutoActivateUsers: form.SSPIAutoActivateUsers,
  167. StripDomainNames: form.SSPIStripDomainNames,
  168. SeparatorReplacement: form.SSPISeparatorReplacement,
  169. DefaultLanguage: form.SSPIDefaultLanguage,
  170. }, nil
  171. }
  172. // NewAuthSourcePost response for adding an auth source
  173. func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
  174. ctx.Data["Title"] = ctx.Tr("admin.auths.new")
  175. ctx.Data["PageIsAdmin"] = true
  176. ctx.Data["PageIsAdminAuthentications"] = true
  177. ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(form.Type)]
  178. ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(form.SecurityProtocol)]
  179. ctx.Data["AuthSources"] = authSources
  180. ctx.Data["SecurityProtocols"] = securityProtocols
  181. ctx.Data["SMTPAuths"] = models.SMTPAuths
  182. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  183. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  184. ctx.Data["SSPIAutoCreateUsers"] = true
  185. ctx.Data["SSPIAutoActivateUsers"] = true
  186. ctx.Data["SSPIStripDomainNames"] = true
  187. ctx.Data["SSPISeparatorReplacement"] = "_"
  188. ctx.Data["SSPIDefaultLanguage"] = ""
  189. hasTLS := false
  190. var config core.Conversion
  191. switch models.LoginType(form.Type) {
  192. case models.LoginLDAP, models.LoginDLDAP:
  193. config = parseLDAPConfig(form)
  194. hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SecurityProtocolUnencrypted
  195. case models.LoginSMTP:
  196. config = parseSMTPConfig(form)
  197. hasTLS = true
  198. case models.LoginPAM:
  199. config = &models.PAMConfig{
  200. ServiceName: form.PAMServiceName,
  201. }
  202. case models.LoginOAuth2:
  203. config = parseOAuth2Config(form)
  204. case models.LoginSSPI:
  205. var err error
  206. config, err = parseSSPIConfig(ctx, form)
  207. if err != nil {
  208. ctx.RenderWithErr(err.Error(), tplAuthNew, form)
  209. return
  210. }
  211. existing, err := models.LoginSourcesByType(models.LoginSSPI)
  212. if err != nil || len(existing) > 0 {
  213. ctx.Data["Err_Type"] = true
  214. ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form)
  215. return
  216. }
  217. default:
  218. ctx.Error(400)
  219. return
  220. }
  221. ctx.Data["HasTLS"] = hasTLS
  222. if ctx.HasError() {
  223. ctx.HTML(200, tplAuthNew)
  224. return
  225. }
  226. if err := models.CreateLoginSource(&models.LoginSource{
  227. Type: models.LoginType(form.Type),
  228. Name: form.Name,
  229. IsActived: form.IsActive,
  230. IsSyncEnabled: form.IsSyncEnabled,
  231. Cfg: config,
  232. }); err != nil {
  233. if models.IsErrLoginSourceAlreadyExist(err) {
  234. ctx.Data["Err_Name"] = true
  235. ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), tplAuthNew, form)
  236. } else {
  237. ctx.ServerError("CreateSource", err)
  238. }
  239. return
  240. }
  241. log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, form.Name)
  242. ctx.Flash.Success(ctx.Tr("admin.auths.new_success", form.Name))
  243. ctx.Redirect(setting.AppSubURL + "/admin/auths")
  244. }
  245. // EditAuthSource render editing auth source page
  246. func EditAuthSource(ctx *context.Context) {
  247. ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
  248. ctx.Data["PageIsAdmin"] = true
  249. ctx.Data["PageIsAdminAuthentications"] = true
  250. ctx.Data["SecurityProtocols"] = securityProtocols
  251. ctx.Data["SMTPAuths"] = models.SMTPAuths
  252. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  253. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  254. source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
  255. if err != nil {
  256. ctx.ServerError("GetLoginSourceByID", err)
  257. return
  258. }
  259. ctx.Data["Source"] = source
  260. ctx.Data["HasTLS"] = source.HasTLS()
  261. if source.IsOAuth2() {
  262. ctx.Data["CurrentOAuth2Provider"] = models.OAuth2Providers[source.OAuth2().Provider]
  263. }
  264. ctx.HTML(200, tplAuthEdit)
  265. }
  266. // EditAuthSourcePost response for editing auth source
  267. func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
  268. ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
  269. ctx.Data["PageIsAdmin"] = true
  270. ctx.Data["PageIsAdminAuthentications"] = true
  271. ctx.Data["SMTPAuths"] = models.SMTPAuths
  272. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  273. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  274. source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
  275. if err != nil {
  276. ctx.ServerError("GetLoginSourceByID", err)
  277. return
  278. }
  279. ctx.Data["Source"] = source
  280. ctx.Data["HasTLS"] = source.HasTLS()
  281. if ctx.HasError() {
  282. ctx.HTML(200, tplAuthEdit)
  283. return
  284. }
  285. var config core.Conversion
  286. switch models.LoginType(form.Type) {
  287. case models.LoginLDAP, models.LoginDLDAP:
  288. config = parseLDAPConfig(form)
  289. case models.LoginSMTP:
  290. config = parseSMTPConfig(form)
  291. case models.LoginPAM:
  292. config = &models.PAMConfig{
  293. ServiceName: form.PAMServiceName,
  294. }
  295. case models.LoginOAuth2:
  296. config = parseOAuth2Config(form)
  297. case models.LoginSSPI:
  298. config, err = parseSSPIConfig(ctx, form)
  299. if err != nil {
  300. ctx.RenderWithErr(err.Error(), tplAuthEdit, form)
  301. return
  302. }
  303. default:
  304. ctx.Error(400)
  305. return
  306. }
  307. source.Name = form.Name
  308. source.IsActived = form.IsActive
  309. source.IsSyncEnabled = form.IsSyncEnabled
  310. source.Cfg = config
  311. if err := models.UpdateSource(source); err != nil {
  312. if models.IsErrOpenIDConnectInitialize(err) {
  313. ctx.Flash.Error(err.Error(), true)
  314. ctx.HTML(200, tplAuthEdit)
  315. } else {
  316. ctx.ServerError("UpdateSource", err)
  317. }
  318. return
  319. }
  320. log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID)
  321. ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
  322. ctx.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(form.ID))
  323. }
  324. // DeleteAuthSource response for deleting an auth source
  325. func DeleteAuthSource(ctx *context.Context) {
  326. source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
  327. if err != nil {
  328. ctx.ServerError("GetLoginSourceByID", err)
  329. return
  330. }
  331. if err = models.DeleteSource(source); err != nil {
  332. if models.IsErrLoginSourceInUse(err) {
  333. ctx.Flash.Error(ctx.Tr("admin.auths.still_in_used"))
  334. } else {
  335. ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
  336. }
  337. ctx.JSON(200, map[string]interface{}{
  338. "redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"),
  339. })
  340. return
  341. }
  342. log.Trace("Authentication deleted by admin(%s): %d", ctx.User.Name, source.ID)
  343. ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success"))
  344. ctx.JSON(200, map[string]interface{}{
  345. "redirect": setting.AppSubURL + "/admin/auths",
  346. })
  347. }