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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. RestrictedFilter: form.RestrictedFilter,
  117. AllowDeactivateAll: form.AllowDeactivateAll,
  118. Enabled: true,
  119. },
  120. }
  121. }
  122. func parseSMTPConfig(form auth.AuthenticationForm) *models.SMTPConfig {
  123. return &models.SMTPConfig{
  124. Auth: form.SMTPAuth,
  125. Host: form.SMTPHost,
  126. Port: form.SMTPPort,
  127. AllowedDomains: form.AllowedDomains,
  128. TLS: form.TLS,
  129. SkipVerify: form.SkipVerify,
  130. }
  131. }
  132. func parseOAuth2Config(form auth.AuthenticationForm) *models.OAuth2Config {
  133. var customURLMapping *oauth2.CustomURLMapping
  134. if form.Oauth2UseCustomURL {
  135. customURLMapping = &oauth2.CustomURLMapping{
  136. TokenURL: form.Oauth2TokenURL,
  137. AuthURL: form.Oauth2AuthURL,
  138. ProfileURL: form.Oauth2ProfileURL,
  139. EmailURL: form.Oauth2EmailURL,
  140. }
  141. } else {
  142. customURLMapping = nil
  143. }
  144. return &models.OAuth2Config{
  145. Provider: form.Oauth2Provider,
  146. ClientID: form.Oauth2Key,
  147. ClientSecret: form.Oauth2Secret,
  148. OpenIDConnectAutoDiscoveryURL: form.OpenIDConnectAutoDiscoveryURL,
  149. CustomURLMapping: customURLMapping,
  150. }
  151. }
  152. func parseSSPIConfig(ctx *context.Context, form auth.AuthenticationForm) (*models.SSPIConfig, error) {
  153. if util.IsEmptyString(form.SSPISeparatorReplacement) {
  154. ctx.Data["Err_SSPISeparatorReplacement"] = true
  155. return nil, errors.New(ctx.Tr("form.SSPISeparatorReplacement") + ctx.Tr("form.require_error"))
  156. }
  157. if separatorAntiPattern.MatchString(form.SSPISeparatorReplacement) {
  158. ctx.Data["Err_SSPISeparatorReplacement"] = true
  159. return nil, errors.New(ctx.Tr("form.SSPISeparatorReplacement") + ctx.Tr("form.alpha_dash_dot_error"))
  160. }
  161. if form.SSPIDefaultLanguage != "" && !langCodePattern.MatchString(form.SSPIDefaultLanguage) {
  162. ctx.Data["Err_SSPIDefaultLanguage"] = true
  163. return nil, errors.New(ctx.Tr("form.lang_select_error"))
  164. }
  165. return &models.SSPIConfig{
  166. AutoCreateUsers: form.SSPIAutoCreateUsers,
  167. AutoActivateUsers: form.SSPIAutoActivateUsers,
  168. StripDomainNames: form.SSPIStripDomainNames,
  169. SeparatorReplacement: form.SSPISeparatorReplacement,
  170. DefaultLanguage: form.SSPIDefaultLanguage,
  171. }, nil
  172. }
  173. // NewAuthSourcePost response for adding an auth source
  174. func NewAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
  175. ctx.Data["Title"] = ctx.Tr("admin.auths.new")
  176. ctx.Data["PageIsAdmin"] = true
  177. ctx.Data["PageIsAdminAuthentications"] = true
  178. ctx.Data["CurrentTypeName"] = models.LoginNames[models.LoginType(form.Type)]
  179. ctx.Data["CurrentSecurityProtocol"] = models.SecurityProtocolNames[ldap.SecurityProtocol(form.SecurityProtocol)]
  180. ctx.Data["AuthSources"] = authSources
  181. ctx.Data["SecurityProtocols"] = securityProtocols
  182. ctx.Data["SMTPAuths"] = models.SMTPAuths
  183. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  184. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  185. ctx.Data["SSPIAutoCreateUsers"] = true
  186. ctx.Data["SSPIAutoActivateUsers"] = true
  187. ctx.Data["SSPIStripDomainNames"] = true
  188. ctx.Data["SSPISeparatorReplacement"] = "_"
  189. ctx.Data["SSPIDefaultLanguage"] = ""
  190. hasTLS := false
  191. var config core.Conversion
  192. switch models.LoginType(form.Type) {
  193. case models.LoginLDAP, models.LoginDLDAP:
  194. config = parseLDAPConfig(form)
  195. hasTLS = ldap.SecurityProtocol(form.SecurityProtocol) > ldap.SecurityProtocolUnencrypted
  196. case models.LoginSMTP:
  197. config = parseSMTPConfig(form)
  198. hasTLS = true
  199. case models.LoginPAM:
  200. config = &models.PAMConfig{
  201. ServiceName: form.PAMServiceName,
  202. }
  203. case models.LoginOAuth2:
  204. config = parseOAuth2Config(form)
  205. case models.LoginSSPI:
  206. var err error
  207. config, err = parseSSPIConfig(ctx, form)
  208. if err != nil {
  209. ctx.RenderWithErr(err.Error(), tplAuthNew, form)
  210. return
  211. }
  212. existing, err := models.LoginSourcesByType(models.LoginSSPI)
  213. if err != nil || len(existing) > 0 {
  214. ctx.Data["Err_Type"] = true
  215. ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_of_type_exist"), tplAuthNew, form)
  216. return
  217. }
  218. default:
  219. ctx.Error(400)
  220. return
  221. }
  222. ctx.Data["HasTLS"] = hasTLS
  223. if ctx.HasError() {
  224. ctx.HTML(200, tplAuthNew)
  225. return
  226. }
  227. if err := models.CreateLoginSource(&models.LoginSource{
  228. Type: models.LoginType(form.Type),
  229. Name: form.Name,
  230. IsActived: form.IsActive,
  231. IsSyncEnabled: form.IsSyncEnabled,
  232. Cfg: config,
  233. }); err != nil {
  234. if models.IsErrLoginSourceAlreadyExist(err) {
  235. ctx.Data["Err_Name"] = true
  236. ctx.RenderWithErr(ctx.Tr("admin.auths.login_source_exist", err.(models.ErrLoginSourceAlreadyExist).Name), tplAuthNew, form)
  237. } else {
  238. ctx.ServerError("CreateSource", err)
  239. }
  240. return
  241. }
  242. log.Trace("Authentication created by admin(%s): %s", ctx.User.Name, form.Name)
  243. ctx.Flash.Success(ctx.Tr("admin.auths.new_success", form.Name))
  244. ctx.Redirect(setting.AppSubURL + "/admin/auths")
  245. }
  246. // EditAuthSource render editing auth source page
  247. func EditAuthSource(ctx *context.Context) {
  248. ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
  249. ctx.Data["PageIsAdmin"] = true
  250. ctx.Data["PageIsAdminAuthentications"] = true
  251. ctx.Data["SecurityProtocols"] = securityProtocols
  252. ctx.Data["SMTPAuths"] = models.SMTPAuths
  253. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  254. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  255. source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
  256. if err != nil {
  257. ctx.ServerError("GetLoginSourceByID", err)
  258. return
  259. }
  260. ctx.Data["Source"] = source
  261. ctx.Data["HasTLS"] = source.HasTLS()
  262. if source.IsOAuth2() {
  263. ctx.Data["CurrentOAuth2Provider"] = models.OAuth2Providers[source.OAuth2().Provider]
  264. }
  265. ctx.HTML(200, tplAuthEdit)
  266. }
  267. // EditAuthSourcePost response for editing auth source
  268. func EditAuthSourcePost(ctx *context.Context, form auth.AuthenticationForm) {
  269. ctx.Data["Title"] = ctx.Tr("admin.auths.edit")
  270. ctx.Data["PageIsAdmin"] = true
  271. ctx.Data["PageIsAdminAuthentications"] = true
  272. ctx.Data["SMTPAuths"] = models.SMTPAuths
  273. ctx.Data["OAuth2Providers"] = models.OAuth2Providers
  274. ctx.Data["OAuth2DefaultCustomURLMappings"] = models.OAuth2DefaultCustomURLMappings
  275. source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
  276. if err != nil {
  277. ctx.ServerError("GetLoginSourceByID", err)
  278. return
  279. }
  280. ctx.Data["Source"] = source
  281. ctx.Data["HasTLS"] = source.HasTLS()
  282. if ctx.HasError() {
  283. ctx.HTML(200, tplAuthEdit)
  284. return
  285. }
  286. var config core.Conversion
  287. switch models.LoginType(form.Type) {
  288. case models.LoginLDAP, models.LoginDLDAP:
  289. config = parseLDAPConfig(form)
  290. case models.LoginSMTP:
  291. config = parseSMTPConfig(form)
  292. case models.LoginPAM:
  293. config = &models.PAMConfig{
  294. ServiceName: form.PAMServiceName,
  295. }
  296. case models.LoginOAuth2:
  297. config = parseOAuth2Config(form)
  298. case models.LoginSSPI:
  299. config, err = parseSSPIConfig(ctx, form)
  300. if err != nil {
  301. ctx.RenderWithErr(err.Error(), tplAuthEdit, form)
  302. return
  303. }
  304. default:
  305. ctx.Error(400)
  306. return
  307. }
  308. source.Name = form.Name
  309. source.IsActived = form.IsActive
  310. source.IsSyncEnabled = form.IsSyncEnabled
  311. source.Cfg = config
  312. if err := models.UpdateSource(source); err != nil {
  313. if models.IsErrOpenIDConnectInitialize(err) {
  314. ctx.Flash.Error(err.Error(), true)
  315. ctx.HTML(200, tplAuthEdit)
  316. } else {
  317. ctx.ServerError("UpdateSource", err)
  318. }
  319. return
  320. }
  321. log.Trace("Authentication changed by admin(%s): %d", ctx.User.Name, source.ID)
  322. ctx.Flash.Success(ctx.Tr("admin.auths.update_success"))
  323. ctx.Redirect(setting.AppSubURL + "/admin/auths/" + com.ToStr(form.ID))
  324. }
  325. // DeleteAuthSource response for deleting an auth source
  326. func DeleteAuthSource(ctx *context.Context) {
  327. source, err := models.GetLoginSourceByID(ctx.ParamsInt64(":authid"))
  328. if err != nil {
  329. ctx.ServerError("GetLoginSourceByID", err)
  330. return
  331. }
  332. if err = models.DeleteSource(source); err != nil {
  333. if models.IsErrLoginSourceInUse(err) {
  334. ctx.Flash.Error(ctx.Tr("admin.auths.still_in_used"))
  335. } else {
  336. ctx.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
  337. }
  338. ctx.JSON(200, map[string]interface{}{
  339. "redirect": setting.AppSubURL + "/admin/auths/" + ctx.Params(":authid"),
  340. })
  341. return
  342. }
  343. log.Trace("Authentication deleted by admin(%s): %d", ctx.User.Name, source.ID)
  344. ctx.Flash.Success(ctx.Tr("admin.auths.deletion_success"))
  345. ctx.JSON(200, map[string]interface{}{
  346. "redirect": setting.AppSubURL + "/admin/auths",
  347. })
  348. }