login.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. "strings"
  12. "time"
  13. "github.com/go-xorm/core"
  14. "github.com/go-xorm/xorm"
  15. "github.com/gogits/gogs/modules/auth/ldap"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/uuid"
  18. )
  19. type LoginType int
  20. const (
  21. NOTYPE LoginType = iota
  22. PLAIN
  23. LDAP
  24. SMTP
  25. )
  26. var (
  27. ErrAuthenticationAlreadyExist = errors.New("Authentication already exist")
  28. ErrAuthenticationNotExist = errors.New("Authentication does not exist")
  29. ErrAuthenticationUserUsed = errors.New("Authentication has been used by some users")
  30. )
  31. var LoginTypes = map[LoginType]string{
  32. LDAP: "LDAP",
  33. SMTP: "SMTP",
  34. }
  35. // Ensure structs implemented interface.
  36. var (
  37. _ core.Conversion = &LDAPConfig{}
  38. _ core.Conversion = &SMTPConfig{}
  39. )
  40. type LDAPConfig struct {
  41. ldap.Ldapsource
  42. }
  43. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  44. return json.Unmarshal(bs, &cfg.Ldapsource)
  45. }
  46. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  47. return json.Marshal(cfg.Ldapsource)
  48. }
  49. type SMTPConfig struct {
  50. Auth string
  51. Host string
  52. Port int
  53. TLS bool
  54. }
  55. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  56. return json.Unmarshal(bs, cfg)
  57. }
  58. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  59. return json.Marshal(cfg)
  60. }
  61. type LoginSource struct {
  62. Id int64
  63. Type LoginType
  64. Name string `xorm:"UNIQUE"`
  65. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  66. Cfg core.Conversion `xorm:"TEXT"`
  67. AllowAutoRegister bool `xorm:"NOT NULL DEFAULT false"`
  68. Created time.Time `xorm:"CREATED"`
  69. Updated time.Time `xorm:"UPDATED"`
  70. }
  71. func (source *LoginSource) TypeString() string {
  72. return LoginTypes[source.Type]
  73. }
  74. func (source *LoginSource) LDAP() *LDAPConfig {
  75. return source.Cfg.(*LDAPConfig)
  76. }
  77. func (source *LoginSource) SMTP() *SMTPConfig {
  78. return source.Cfg.(*SMTPConfig)
  79. }
  80. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  81. if colName == "type" {
  82. ty := (*val).(int64)
  83. switch LoginType(ty) {
  84. case LDAP:
  85. source.Cfg = new(LDAPConfig)
  86. case SMTP:
  87. source.Cfg = new(SMTPConfig)
  88. }
  89. }
  90. }
  91. func CreateSource(source *LoginSource) error {
  92. _, err := x.Insert(source)
  93. return err
  94. }
  95. func GetAuths() ([]*LoginSource, error) {
  96. var auths = make([]*LoginSource, 0, 5)
  97. err := x.Find(&auths)
  98. return auths, err
  99. }
  100. func GetLoginSourceById(id int64) (*LoginSource, error) {
  101. source := new(LoginSource)
  102. has, err := x.Id(id).Get(source)
  103. if err != nil {
  104. return nil, err
  105. } else if !has {
  106. return nil, ErrAuthenticationNotExist
  107. }
  108. return source, nil
  109. }
  110. func UpdateSource(source *LoginSource) error {
  111. _, err := x.Id(source.Id).AllCols().Update(source)
  112. return err
  113. }
  114. func DelLoginSource(source *LoginSource) error {
  115. cnt, err := x.Count(&User{LoginSource: source.Id})
  116. if err != nil {
  117. return err
  118. }
  119. if cnt > 0 {
  120. return ErrAuthenticationUserUsed
  121. }
  122. _, err = x.Id(source.Id).Delete(&LoginSource{})
  123. return err
  124. }
  125. // UserSignIn validates user name and password.
  126. func UserSignIn(uname, passwd string) (*User, error) {
  127. u := new(User)
  128. if strings.Contains(uname, "@") {
  129. u = &User{Email: uname}
  130. } else {
  131. u = &User{LowerName: strings.ToLower(uname)}
  132. }
  133. has, err := x.Get(u)
  134. if err != nil {
  135. return nil, err
  136. }
  137. if u.LoginType == NOTYPE && has {
  138. u.LoginType = PLAIN
  139. }
  140. // For plain login, user must exist to reach this line.
  141. // Now verify password.
  142. if u.LoginType == PLAIN {
  143. newUser := &User{Passwd: passwd, Salt: u.Salt}
  144. newUser.EncodePasswd()
  145. if u.Passwd != newUser.Passwd {
  146. return nil, ErrUserNotExist
  147. }
  148. return u, nil
  149. } else {
  150. if !has {
  151. var sources []LoginSource
  152. if err = x.UseBool().Find(&sources,
  153. &LoginSource{IsActived: true, AllowAutoRegister: true}); err != nil {
  154. return nil, err
  155. }
  156. for _, source := range sources {
  157. if source.Type == LDAP {
  158. u, err := LoginUserLdapSource(nil, uname, passwd,
  159. source.Id, source.Cfg.(*LDAPConfig), true)
  160. if err == nil {
  161. return u, nil
  162. }
  163. log.Warn("Fail to login(%s) by LDAP(%s): %v", uname, source.Name, err)
  164. } else if source.Type == SMTP {
  165. u, err := LoginUserSMTPSource(nil, uname, passwd,
  166. source.Id, source.Cfg.(*SMTPConfig), true)
  167. if err == nil {
  168. return u, nil
  169. }
  170. log.Warn("Fail to login(%s) by SMTP(%s): %v", uname, source.Name, err)
  171. }
  172. }
  173. return nil, ErrUserNotExist
  174. }
  175. var source LoginSource
  176. hasSource, err := x.Id(u.LoginSource).Get(&source)
  177. if err != nil {
  178. return nil, err
  179. } else if !hasSource {
  180. return nil, ErrLoginSourceNotExist
  181. } else if !source.IsActived {
  182. return nil, ErrLoginSourceNotActived
  183. }
  184. switch u.LoginType {
  185. case LDAP:
  186. return LoginUserLdapSource(u, u.LoginName, passwd,
  187. source.Id, source.Cfg.(*LDAPConfig), false)
  188. case SMTP:
  189. return LoginUserSMTPSource(u, u.LoginName, passwd,
  190. source.Id, source.Cfg.(*SMTPConfig), false)
  191. }
  192. return nil, ErrUnsupportedLoginType
  193. }
  194. }
  195. // Query if name/passwd can login against the LDAP directory pool
  196. // Create a local user if success
  197. // Return the same LoginUserPlain semantic
  198. // FIXME: https://github.com/gogits/gogs/issues/672
  199. func LoginUserLdapSource(u *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) {
  200. mail, logged := cfg.Ldapsource.SearchEntry(name, passwd)
  201. if !logged {
  202. // User not in LDAP, do nothing
  203. return nil, ErrUserNotExist
  204. }
  205. if !autoRegister {
  206. return u, nil
  207. }
  208. // Fallback.
  209. if len(mail) == 0 {
  210. mail = uuid.NewV4().String() + "@localhost"
  211. }
  212. u = &User{
  213. Name: name,
  214. LoginType: LDAP,
  215. LoginSource: sourceId,
  216. LoginName: name,
  217. Passwd: passwd,
  218. Email: mail,
  219. IsActive: true,
  220. }
  221. return u, CreateUser(u)
  222. }
  223. type loginAuth struct {
  224. username, password string
  225. }
  226. func LoginAuth(username, password string) smtp.Auth {
  227. return &loginAuth{username, password}
  228. }
  229. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  230. return "LOGIN", []byte(a.username), nil
  231. }
  232. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  233. if more {
  234. switch string(fromServer) {
  235. case "Username:":
  236. return []byte(a.username), nil
  237. case "Password:":
  238. return []byte(a.password), nil
  239. }
  240. }
  241. return nil, nil
  242. }
  243. var (
  244. SMTP_PLAIN = "PLAIN"
  245. SMTP_LOGIN = "LOGIN"
  246. SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  247. )
  248. func SmtpAuth(host string, port int, a smtp.Auth, useTls bool) error {
  249. c, err := smtp.Dial(fmt.Sprintf("%s:%d", host, port))
  250. if err != nil {
  251. return err
  252. }
  253. defer c.Close()
  254. if err = c.Hello("gogs"); err != nil {
  255. return err
  256. }
  257. if useTls {
  258. if ok, _ := c.Extension("STARTTLS"); ok {
  259. config := &tls.Config{ServerName: host}
  260. if err = c.StartTLS(config); err != nil {
  261. return err
  262. }
  263. } else {
  264. return errors.New("SMTP server unsupports TLS")
  265. }
  266. }
  267. if ok, _ := c.Extension("AUTH"); ok {
  268. if err = c.Auth(a); err != nil {
  269. return err
  270. }
  271. return nil
  272. }
  273. return ErrUnsupportedLoginType
  274. }
  275. // Query if name/passwd can login against the LDAP directory pool
  276. // Create a local user if success
  277. // Return the same LoginUserPlain semantic
  278. func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  279. var auth smtp.Auth
  280. if cfg.Auth == SMTP_PLAIN {
  281. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  282. } else if cfg.Auth == SMTP_LOGIN {
  283. auth = LoginAuth(name, passwd)
  284. } else {
  285. return nil, errors.New("Unsupported SMTP auth type")
  286. }
  287. if err := SmtpAuth(cfg.Host, cfg.Port, auth, cfg.TLS); err != nil {
  288. if strings.Contains(err.Error(), "Username and Password not accepted") {
  289. return nil, ErrUserNotExist
  290. }
  291. return nil, err
  292. }
  293. if !autoRegister {
  294. return u, nil
  295. }
  296. var loginName = name
  297. idx := strings.Index(name, "@")
  298. if idx > -1 {
  299. loginName = name[:idx]
  300. }
  301. // fake a local user creation
  302. u = &User{
  303. LowerName: strings.ToLower(loginName),
  304. Name: strings.ToLower(loginName),
  305. LoginType: SMTP,
  306. LoginSource: sourceId,
  307. LoginName: name,
  308. IsActive: true,
  309. Passwd: passwd,
  310. Email: name,
  311. }
  312. err := CreateUser(u)
  313. return u, err
  314. }