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.

login_source.go 19KB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
10 years ago
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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
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
10 years ago
10 years ago
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
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
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
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
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
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
10 years ago
10 years ago
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
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
10 years ago
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
10 years ago
10 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
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
7 years ago
7 years ago
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
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
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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 models
  5. import (
  6. "crypto/tls"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net/smtp"
  11. "net/textproto"
  12. "strings"
  13. "time"
  14. "github.com/Unknwon/com"
  15. "github.com/go-macaron/binding"
  16. "github.com/go-xorm/core"
  17. "github.com/go-xorm/xorm"
  18. "code.gitea.io/gitea/modules/auth/ldap"
  19. "code.gitea.io/gitea/modules/auth/oauth2"
  20. "code.gitea.io/gitea/modules/auth/pam"
  21. "code.gitea.io/gitea/modules/log"
  22. )
  23. // LoginType represents an login type.
  24. type LoginType int
  25. // Note: new type must append to the end of list to maintain compatibility.
  26. const (
  27. LoginNoType LoginType = iota
  28. LoginPlain // 1
  29. LoginLDAP // 2
  30. LoginSMTP // 3
  31. LoginPAM // 4
  32. LoginDLDAP // 5
  33. LoginOAuth2 // 6
  34. )
  35. // LoginNames contains the name of LoginType values.
  36. var LoginNames = map[LoginType]string{
  37. LoginLDAP: "LDAP (via BindDN)",
  38. LoginDLDAP: "LDAP (simple auth)", // Via direct bind
  39. LoginSMTP: "SMTP",
  40. LoginPAM: "PAM",
  41. LoginOAuth2: "OAuth2",
  42. }
  43. // SecurityProtocolNames contains the name of SecurityProtocol values.
  44. var SecurityProtocolNames = map[ldap.SecurityProtocol]string{
  45. ldap.SecurityProtocolUnencrypted: "Unencrypted",
  46. ldap.SecurityProtocolLDAPS: "LDAPS",
  47. ldap.SecurityProtocolStartTLS: "StartTLS",
  48. }
  49. // Ensure structs implemented interface.
  50. var (
  51. _ core.Conversion = &LDAPConfig{}
  52. _ core.Conversion = &SMTPConfig{}
  53. _ core.Conversion = &PAMConfig{}
  54. _ core.Conversion = &OAuth2Config{}
  55. )
  56. // LDAPConfig holds configuration for LDAP login source.
  57. type LDAPConfig struct {
  58. *ldap.Source
  59. }
  60. // FromDB fills up a LDAPConfig from serialized format.
  61. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  62. return json.Unmarshal(bs, &cfg)
  63. }
  64. // ToDB exports a LDAPConfig to a serialized format.
  65. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  66. return json.Marshal(cfg)
  67. }
  68. // SecurityProtocolName returns the name of configured security
  69. // protocol.
  70. func (cfg *LDAPConfig) SecurityProtocolName() string {
  71. return SecurityProtocolNames[cfg.SecurityProtocol]
  72. }
  73. // SMTPConfig holds configuration for the SMTP login source.
  74. type SMTPConfig struct {
  75. Auth string
  76. Host string
  77. Port int
  78. AllowedDomains string `xorm:"TEXT"`
  79. TLS bool
  80. SkipVerify bool
  81. }
  82. // FromDB fills up an SMTPConfig from serialized format.
  83. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  84. return json.Unmarshal(bs, cfg)
  85. }
  86. // ToDB exports an SMTPConfig to a serialized format.
  87. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  88. return json.Marshal(cfg)
  89. }
  90. // PAMConfig holds configuration for the PAM login source.
  91. type PAMConfig struct {
  92. ServiceName string // pam service (e.g. system-auth)
  93. }
  94. // FromDB fills up a PAMConfig from serialized format.
  95. func (cfg *PAMConfig) FromDB(bs []byte) error {
  96. return json.Unmarshal(bs, &cfg)
  97. }
  98. // ToDB exports a PAMConfig to a serialized format.
  99. func (cfg *PAMConfig) ToDB() ([]byte, error) {
  100. return json.Marshal(cfg)
  101. }
  102. // OAuth2Config holds configuration for the OAuth2 login source.
  103. type OAuth2Config struct {
  104. Provider string
  105. ClientID string
  106. ClientSecret string
  107. OpenIDConnectAutoDiscoveryURL string
  108. CustomURLMapping *oauth2.CustomURLMapping
  109. }
  110. // FromDB fills up an OAuth2Config from serialized format.
  111. func (cfg *OAuth2Config) FromDB(bs []byte) error {
  112. return json.Unmarshal(bs, cfg)
  113. }
  114. // ToDB exports an SMTPConfig to a serialized format.
  115. func (cfg *OAuth2Config) ToDB() ([]byte, error) {
  116. return json.Marshal(cfg)
  117. }
  118. // LoginSource represents an external way for authorizing users.
  119. type LoginSource struct {
  120. ID int64 `xorm:"pk autoincr"`
  121. Type LoginType
  122. Name string `xorm:"UNIQUE"`
  123. IsActived bool `xorm:"INDEX NOT NULL DEFAULT false"`
  124. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  125. Cfg core.Conversion `xorm:"TEXT"`
  126. Created time.Time `xorm:"-"`
  127. CreatedUnix int64 `xorm:"INDEX"`
  128. Updated time.Time `xorm:"-"`
  129. UpdatedUnix int64 `xorm:"INDEX"`
  130. }
  131. // BeforeInsert is invoked from XORM before inserting an object of this type.
  132. func (source *LoginSource) BeforeInsert() {
  133. source.CreatedUnix = time.Now().Unix()
  134. source.UpdatedUnix = source.CreatedUnix
  135. }
  136. // BeforeUpdate is invoked from XORM before updating this object.
  137. func (source *LoginSource) BeforeUpdate() {
  138. source.UpdatedUnix = time.Now().Unix()
  139. }
  140. // Cell2Int64 converts a xorm.Cell type to int64,
  141. // and handles possible irregular cases.
  142. func Cell2Int64(val xorm.Cell) int64 {
  143. switch (*val).(type) {
  144. case []uint8:
  145. log.Trace("Cell2Int64 ([]uint8): %v", *val)
  146. return com.StrTo(string((*val).([]uint8))).MustInt64()
  147. }
  148. return (*val).(int64)
  149. }
  150. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  151. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  152. switch colName {
  153. case "type":
  154. switch LoginType(Cell2Int64(val)) {
  155. case LoginLDAP, LoginDLDAP:
  156. source.Cfg = new(LDAPConfig)
  157. case LoginSMTP:
  158. source.Cfg = new(SMTPConfig)
  159. case LoginPAM:
  160. source.Cfg = new(PAMConfig)
  161. case LoginOAuth2:
  162. source.Cfg = new(OAuth2Config)
  163. default:
  164. panic("unrecognized login source type: " + com.ToStr(*val))
  165. }
  166. }
  167. }
  168. // AfterSet is invoked from XORM after setting the value of a field of this object.
  169. func (source *LoginSource) AfterSet(colName string, _ xorm.Cell) {
  170. switch colName {
  171. case "created_unix":
  172. source.Created = time.Unix(source.CreatedUnix, 0).Local()
  173. case "updated_unix":
  174. source.Updated = time.Unix(source.UpdatedUnix, 0).Local()
  175. }
  176. }
  177. // TypeName return name of this login source type.
  178. func (source *LoginSource) TypeName() string {
  179. return LoginNames[source.Type]
  180. }
  181. // IsLDAP returns true of this source is of the LDAP type.
  182. func (source *LoginSource) IsLDAP() bool {
  183. return source.Type == LoginLDAP
  184. }
  185. // IsDLDAP returns true of this source is of the DLDAP type.
  186. func (source *LoginSource) IsDLDAP() bool {
  187. return source.Type == LoginDLDAP
  188. }
  189. // IsSMTP returns true of this source is of the SMTP type.
  190. func (source *LoginSource) IsSMTP() bool {
  191. return source.Type == LoginSMTP
  192. }
  193. // IsPAM returns true of this source is of the PAM type.
  194. func (source *LoginSource) IsPAM() bool {
  195. return source.Type == LoginPAM
  196. }
  197. // IsOAuth2 returns true of this source is of the OAuth2 type.
  198. func (source *LoginSource) IsOAuth2() bool {
  199. return source.Type == LoginOAuth2
  200. }
  201. // HasTLS returns true of this source supports TLS.
  202. func (source *LoginSource) HasTLS() bool {
  203. return ((source.IsLDAP() || source.IsDLDAP()) &&
  204. source.LDAP().SecurityProtocol > ldap.SecurityProtocolUnencrypted) ||
  205. source.IsSMTP()
  206. }
  207. // UseTLS returns true of this source is configured to use TLS.
  208. func (source *LoginSource) UseTLS() bool {
  209. switch source.Type {
  210. case LoginLDAP, LoginDLDAP:
  211. return source.LDAP().SecurityProtocol != ldap.SecurityProtocolUnencrypted
  212. case LoginSMTP:
  213. return source.SMTP().TLS
  214. }
  215. return false
  216. }
  217. // SkipVerify returns true if this source is configured to skip SSL
  218. // verification.
  219. func (source *LoginSource) SkipVerify() bool {
  220. switch source.Type {
  221. case LoginLDAP, LoginDLDAP:
  222. return source.LDAP().SkipVerify
  223. case LoginSMTP:
  224. return source.SMTP().SkipVerify
  225. }
  226. return false
  227. }
  228. // LDAP returns LDAPConfig for this source, if of LDAP type.
  229. func (source *LoginSource) LDAP() *LDAPConfig {
  230. return source.Cfg.(*LDAPConfig)
  231. }
  232. // SMTP returns SMTPConfig for this source, if of SMTP type.
  233. func (source *LoginSource) SMTP() *SMTPConfig {
  234. return source.Cfg.(*SMTPConfig)
  235. }
  236. // PAM returns PAMConfig for this source, if of PAM type.
  237. func (source *LoginSource) PAM() *PAMConfig {
  238. return source.Cfg.(*PAMConfig)
  239. }
  240. // OAuth2 returns OAuth2Config for this source, if of OAuth2 type.
  241. func (source *LoginSource) OAuth2() *OAuth2Config {
  242. return source.Cfg.(*OAuth2Config)
  243. }
  244. // CreateLoginSource inserts a LoginSource in the DB if not already
  245. // existing with the given name.
  246. func CreateLoginSource(source *LoginSource) error {
  247. has, err := x.Get(&LoginSource{Name: source.Name})
  248. if err != nil {
  249. return err
  250. } else if has {
  251. return ErrLoginSourceAlreadyExist{source.Name}
  252. }
  253. // Synchronization is only aviable with LDAP for now
  254. if !source.IsLDAP() {
  255. source.IsSyncEnabled = false
  256. }
  257. _, err = x.Insert(source)
  258. if err == nil && source.IsOAuth2() && source.IsActived {
  259. oAuth2Config := source.OAuth2()
  260. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  261. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  262. if err != nil {
  263. // remove the LoginSource in case of errors while registering OAuth2 providers
  264. x.Delete(source)
  265. }
  266. }
  267. return err
  268. }
  269. // LoginSources returns a slice of all login sources found in DB.
  270. func LoginSources() ([]*LoginSource, error) {
  271. auths := make([]*LoginSource, 0, 6)
  272. return auths, x.Find(&auths)
  273. }
  274. // GetLoginSourceByID returns login source by given ID.
  275. func GetLoginSourceByID(id int64) (*LoginSource, error) {
  276. source := new(LoginSource)
  277. has, err := x.Id(id).Get(source)
  278. if err != nil {
  279. return nil, err
  280. } else if !has {
  281. return nil, ErrLoginSourceNotExist{id}
  282. }
  283. return source, nil
  284. }
  285. // UpdateSource updates a LoginSource record in DB.
  286. func UpdateSource(source *LoginSource) error {
  287. var originalLoginSource *LoginSource
  288. if source.IsOAuth2() {
  289. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  290. var err error
  291. if originalLoginSource, err = GetLoginSourceByID(source.ID); err != nil {
  292. return err
  293. }
  294. }
  295. _, err := x.Id(source.ID).AllCols().Update(source)
  296. if err == nil && source.IsOAuth2() && source.IsActived {
  297. oAuth2Config := source.OAuth2()
  298. err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping)
  299. err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config)
  300. if err != nil {
  301. // restore original values since we cannot update the provider it self
  302. x.Id(source.ID).AllCols().Update(originalLoginSource)
  303. }
  304. }
  305. return err
  306. }
  307. // DeleteSource deletes a LoginSource record in DB.
  308. func DeleteSource(source *LoginSource) error {
  309. count, err := x.Count(&User{LoginSource: source.ID})
  310. if err != nil {
  311. return err
  312. } else if count > 0 {
  313. return ErrLoginSourceInUse{source.ID}
  314. }
  315. count, err = x.Count(&ExternalLoginUser{LoginSourceID: source.ID})
  316. if err != nil {
  317. return err
  318. } else if count > 0 {
  319. return ErrLoginSourceInUse{source.ID}
  320. }
  321. if source.IsOAuth2() {
  322. oauth2.RemoveProvider(source.Name)
  323. }
  324. _, err = x.Id(source.ID).Delete(new(LoginSource))
  325. return err
  326. }
  327. // CountLoginSources returns number of login sources.
  328. func CountLoginSources() int64 {
  329. count, _ := x.Count(new(LoginSource))
  330. return count
  331. }
  332. // .____ ________ _____ __________
  333. // | | \______ \ / _ \\______ \
  334. // | | | | \ / /_\ \| ___/
  335. // | |___ | ` \/ | \ |
  336. // |_______ \/_______ /\____|__ /____|
  337. // \/ \/ \/
  338. func composeFullName(firstname, surname, username string) string {
  339. switch {
  340. case len(firstname) == 0 && len(surname) == 0:
  341. return username
  342. case len(firstname) == 0:
  343. return surname
  344. case len(surname) == 0:
  345. return firstname
  346. default:
  347. return firstname + " " + surname
  348. }
  349. }
  350. // LoginViaLDAP queries if login/password is valid against the LDAP directory pool,
  351. // and create a local user if success when enabled.
  352. func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  353. sr := source.Cfg.(*LDAPConfig).SearchEntry(login, password, source.Type == LoginDLDAP)
  354. if sr == nil {
  355. // User not in LDAP, do nothing
  356. return nil, ErrUserNotExist{0, login, 0}
  357. }
  358. if !autoRegister {
  359. return user, nil
  360. }
  361. // Fallback.
  362. if len(sr.Username) == 0 {
  363. sr.Username = login
  364. }
  365. // Validate username make sure it satisfies requirement.
  366. if binding.AlphaDashDotPattern.MatchString(sr.Username) {
  367. return nil, fmt.Errorf("Invalid pattern for attribute 'username' [%s]: must be valid alpha or numeric or dash(-_) or dot characters", sr.Username)
  368. }
  369. if len(sr.Mail) == 0 {
  370. sr.Mail = fmt.Sprintf("%s@localhost", sr.Username)
  371. }
  372. user = &User{
  373. LowerName: strings.ToLower(sr.Username),
  374. Name: sr.Username,
  375. FullName: composeFullName(sr.Name, sr.Surname, sr.Username),
  376. Email: sr.Mail,
  377. LoginType: source.Type,
  378. LoginSource: source.ID,
  379. LoginName: login,
  380. IsActive: true,
  381. IsAdmin: sr.IsAdmin,
  382. }
  383. return user, CreateUser(user)
  384. }
  385. // _________ __________________________
  386. // / _____/ / \__ ___/\______ \
  387. // \_____ \ / \ / \| | | ___/
  388. // / \/ Y \ | | |
  389. // /_______ /\____|__ /____| |____|
  390. // \/ \/
  391. type smtpLoginAuth struct {
  392. username, password string
  393. }
  394. func (auth *smtpLoginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  395. return "LOGIN", []byte(auth.username), nil
  396. }
  397. func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  398. if more {
  399. switch string(fromServer) {
  400. case "Username:":
  401. return []byte(auth.username), nil
  402. case "Password:":
  403. return []byte(auth.password), nil
  404. }
  405. }
  406. return nil, nil
  407. }
  408. // SMTP authentication type names.
  409. const (
  410. SMTPPlain = "PLAIN"
  411. SMTPLogin = "LOGIN"
  412. )
  413. // SMTPAuths contains available SMTP authentication type names.
  414. var SMTPAuths = []string{SMTPPlain, SMTPLogin}
  415. // SMTPAuth performs an SMTP authentication.
  416. func SMTPAuth(a smtp.Auth, cfg *SMTPConfig) error {
  417. c, err := smtp.Dial(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port))
  418. if err != nil {
  419. return err
  420. }
  421. defer c.Close()
  422. if err = c.Hello("gogs"); err != nil {
  423. return err
  424. }
  425. if cfg.TLS {
  426. if ok, _ := c.Extension("STARTTLS"); ok {
  427. if err = c.StartTLS(&tls.Config{
  428. InsecureSkipVerify: cfg.SkipVerify,
  429. ServerName: cfg.Host,
  430. }); err != nil {
  431. return err
  432. }
  433. } else {
  434. return errors.New("SMTP server unsupports TLS")
  435. }
  436. }
  437. if ok, _ := c.Extension("AUTH"); ok {
  438. if err = c.Auth(a); err != nil {
  439. return err
  440. }
  441. return nil
  442. }
  443. return ErrUnsupportedLoginType
  444. }
  445. // LoginViaSMTP queries if login/password is valid against the SMTP,
  446. // and create a local user if success when enabled.
  447. func LoginViaSMTP(user *User, login, password string, sourceID int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  448. // Verify allowed domains.
  449. if len(cfg.AllowedDomains) > 0 {
  450. idx := strings.Index(login, "@")
  451. if idx == -1 {
  452. return nil, ErrUserNotExist{0, login, 0}
  453. } else if !com.IsSliceContainsStr(strings.Split(cfg.AllowedDomains, ","), login[idx+1:]) {
  454. return nil, ErrUserNotExist{0, login, 0}
  455. }
  456. }
  457. var auth smtp.Auth
  458. if cfg.Auth == SMTPPlain {
  459. auth = smtp.PlainAuth("", login, password, cfg.Host)
  460. } else if cfg.Auth == SMTPLogin {
  461. auth = &smtpLoginAuth{login, password}
  462. } else {
  463. return nil, errors.New("Unsupported SMTP auth type")
  464. }
  465. if err := SMTPAuth(auth, cfg); err != nil {
  466. // Check standard error format first,
  467. // then fallback to worse case.
  468. tperr, ok := err.(*textproto.Error)
  469. if (ok && tperr.Code == 535) ||
  470. strings.Contains(err.Error(), "Username and Password not accepted") {
  471. return nil, ErrUserNotExist{0, login, 0}
  472. }
  473. return nil, err
  474. }
  475. if !autoRegister {
  476. return user, nil
  477. }
  478. username := login
  479. idx := strings.Index(login, "@")
  480. if idx > -1 {
  481. username = login[:idx]
  482. }
  483. user = &User{
  484. LowerName: strings.ToLower(username),
  485. Name: strings.ToLower(username),
  486. Email: login,
  487. Passwd: password,
  488. LoginType: LoginSMTP,
  489. LoginSource: sourceID,
  490. LoginName: login,
  491. IsActive: true,
  492. }
  493. return user, CreateUser(user)
  494. }
  495. // __________ _____ _____
  496. // \______ \/ _ \ / \
  497. // | ___/ /_\ \ / \ / \
  498. // | | / | \/ Y \
  499. // |____| \____|__ /\____|__ /
  500. // \/ \/
  501. // LoginViaPAM queries if login/password is valid against the PAM,
  502. // and create a local user if success when enabled.
  503. func LoginViaPAM(user *User, login, password string, sourceID int64, cfg *PAMConfig, autoRegister bool) (*User, error) {
  504. if err := pam.Auth(cfg.ServiceName, login, password); err != nil {
  505. if strings.Contains(err.Error(), "Authentication failure") {
  506. return nil, ErrUserNotExist{0, login, 0}
  507. }
  508. return nil, err
  509. }
  510. if !autoRegister {
  511. return user, nil
  512. }
  513. user = &User{
  514. LowerName: strings.ToLower(login),
  515. Name: login,
  516. Email: login,
  517. Passwd: password,
  518. LoginType: LoginPAM,
  519. LoginSource: sourceID,
  520. LoginName: login,
  521. IsActive: true,
  522. }
  523. return user, CreateUser(user)
  524. }
  525. // ExternalUserLogin attempts a login using external source types.
  526. func ExternalUserLogin(user *User, login, password string, source *LoginSource, autoRegister bool) (*User, error) {
  527. if !source.IsActived {
  528. return nil, ErrLoginSourceNotActived
  529. }
  530. switch source.Type {
  531. case LoginLDAP, LoginDLDAP:
  532. return LoginViaLDAP(user, login, password, source, autoRegister)
  533. case LoginSMTP:
  534. return LoginViaSMTP(user, login, password, source.ID, source.Cfg.(*SMTPConfig), autoRegister)
  535. case LoginPAM:
  536. return LoginViaPAM(user, login, password, source.ID, source.Cfg.(*PAMConfig), autoRegister)
  537. }
  538. return nil, ErrUnsupportedLoginType
  539. }
  540. // UserSignIn validates user name and password.
  541. func UserSignIn(username, password string) (*User, error) {
  542. var user *User
  543. if strings.Contains(username, "@") {
  544. user = &User{Email: strings.ToLower(strings.TrimSpace(username))}
  545. // check same email
  546. cnt, err := x.Count(user)
  547. if err != nil {
  548. return nil, err
  549. }
  550. if cnt > 1 {
  551. return nil, ErrEmailAlreadyUsed{
  552. Email: user.Email,
  553. }
  554. }
  555. } else {
  556. trimmedUsername := strings.TrimSpace(username)
  557. if len(trimmedUsername) == 0 {
  558. return nil, ErrUserNotExist{0, username, 0}
  559. }
  560. user = &User{LowerName: strings.ToLower(trimmedUsername)}
  561. }
  562. hasUser, err := x.Get(user)
  563. if err != nil {
  564. return nil, err
  565. }
  566. if hasUser {
  567. switch user.LoginType {
  568. case LoginNoType, LoginPlain, LoginOAuth2:
  569. if user.ValidatePassword(password) {
  570. return user, nil
  571. }
  572. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  573. default:
  574. var source LoginSource
  575. hasSource, err := x.Id(user.LoginSource).Get(&source)
  576. if err != nil {
  577. return nil, err
  578. } else if !hasSource {
  579. return nil, ErrLoginSourceNotExist{user.LoginSource}
  580. }
  581. return ExternalUserLogin(user, user.LoginName, password, &source, false)
  582. }
  583. }
  584. sources := make([]*LoginSource, 0, 5)
  585. if err = x.UseBool().Find(&sources, &LoginSource{IsActived: true}); err != nil {
  586. return nil, err
  587. }
  588. for _, source := range sources {
  589. if source.IsOAuth2() {
  590. // don't try to authenticate against OAuth2 sources
  591. continue
  592. }
  593. authUser, err := ExternalUserLogin(nil, username, password, source, true)
  594. if err == nil {
  595. return authUser, nil
  596. }
  597. log.Warn("Failed to login '%s' via '%s': %v", username, source.Name, err)
  598. }
  599. return nil, ErrUserNotExist{user.ID, user.Name, 0}
  600. }