login.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. if !u.ValidtePassword(passwd) {
  144. return nil, ErrUserNotExist
  145. }
  146. return u, nil
  147. }
  148. if !has {
  149. var sources []LoginSource
  150. if err = x.UseBool().Find(&sources,
  151. &LoginSource{IsActived: true, AllowAutoRegister: true}); err != nil {
  152. return nil, err
  153. }
  154. for _, source := range sources {
  155. if source.Type == LDAP {
  156. u, err := LoginUserLdapSource(nil, uname, passwd,
  157. source.Id, source.Cfg.(*LDAPConfig), true)
  158. if err == nil {
  159. return u, nil
  160. }
  161. log.Warn("Fail to login(%s) by LDAP(%s): %v", uname, source.Name, err)
  162. } else if source.Type == SMTP {
  163. u, err := LoginUserSMTPSource(nil, uname, passwd,
  164. source.Id, source.Cfg.(*SMTPConfig), true)
  165. if err == nil {
  166. return u, nil
  167. }
  168. log.Warn("Fail to login(%s) by SMTP(%s): %v", uname, source.Name, err)
  169. }
  170. }
  171. return nil, ErrUserNotExist
  172. }
  173. var source LoginSource
  174. hasSource, err := x.Id(u.LoginSource).Get(&source)
  175. if err != nil {
  176. return nil, err
  177. } else if !hasSource {
  178. return nil, ErrLoginSourceNotExist
  179. } else if !source.IsActived {
  180. return nil, ErrLoginSourceNotActived
  181. }
  182. switch u.LoginType {
  183. case LDAP:
  184. return LoginUserLdapSource(u, u.LoginName, passwd, source.Id, source.Cfg.(*LDAPConfig), false)
  185. case SMTP:
  186. return LoginUserSMTPSource(u, u.LoginName, passwd, source.Id, source.Cfg.(*SMTPConfig), false)
  187. }
  188. return nil, ErrUnsupportedLoginType
  189. }
  190. // Query if name/passwd can login against the LDAP directory pool
  191. // Create a local user if success
  192. // Return the same LoginUserPlain semantic
  193. // FIXME: https://github.com/gogits/gogs/issues/672
  194. func LoginUserLdapSource(u *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) {
  195. name, fn, sn, mail, logged := cfg.Ldapsource.SearchEntry(name, passwd)
  196. if !logged {
  197. // User not in LDAP, do nothing
  198. return nil, ErrUserNotExist
  199. }
  200. if !autoRegister {
  201. return u, nil
  202. }
  203. // Fallback.
  204. if len(mail) == 0 {
  205. mail = uuid.NewV4().String() + "@localhost"
  206. }
  207. u = &User{
  208. LowerName: strings.ToLower(name),
  209. Name: name,
  210. FullName: fn + " " + sn,
  211. LoginType: LDAP,
  212. LoginSource: sourceId,
  213. LoginName: name,
  214. Passwd: passwd,
  215. Email: mail,
  216. IsActive: true,
  217. }
  218. return u, CreateUser(u)
  219. }
  220. type loginAuth struct {
  221. username, password string
  222. }
  223. func LoginAuth(username, password string) smtp.Auth {
  224. return &loginAuth{username, password}
  225. }
  226. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  227. return "LOGIN", []byte(a.username), nil
  228. }
  229. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  230. if more {
  231. switch string(fromServer) {
  232. case "Username:":
  233. return []byte(a.username), nil
  234. case "Password:":
  235. return []byte(a.password), nil
  236. }
  237. }
  238. return nil, nil
  239. }
  240. var (
  241. SMTP_PLAIN = "PLAIN"
  242. SMTP_LOGIN = "LOGIN"
  243. SMTPAuths = []string{SMTP_PLAIN, SMTP_LOGIN}
  244. )
  245. func SmtpAuth(host string, port int, a smtp.Auth, useTls bool) error {
  246. c, err := smtp.Dial(fmt.Sprintf("%s:%d", host, port))
  247. if err != nil {
  248. return err
  249. }
  250. defer c.Close()
  251. if err = c.Hello("gogs"); err != nil {
  252. return err
  253. }
  254. if useTls {
  255. if ok, _ := c.Extension("STARTTLS"); ok {
  256. config := &tls.Config{ServerName: host}
  257. if err = c.StartTLS(config); err != nil {
  258. return err
  259. }
  260. } else {
  261. return errors.New("SMTP server unsupports TLS")
  262. }
  263. }
  264. if ok, _ := c.Extension("AUTH"); ok {
  265. if err = c.Auth(a); err != nil {
  266. return err
  267. }
  268. return nil
  269. }
  270. return ErrUnsupportedLoginType
  271. }
  272. // Query if name/passwd can login against the LDAP directory pool
  273. // Create a local user if success
  274. // Return the same LoginUserPlain semantic
  275. func LoginUserSMTPSource(u *User, name, passwd string, sourceId int64, cfg *SMTPConfig, autoRegister bool) (*User, error) {
  276. var auth smtp.Auth
  277. if cfg.Auth == SMTP_PLAIN {
  278. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  279. } else if cfg.Auth == SMTP_LOGIN {
  280. auth = LoginAuth(name, passwd)
  281. } else {
  282. return nil, errors.New("Unsupported SMTP auth type")
  283. }
  284. if err := SmtpAuth(cfg.Host, cfg.Port, auth, cfg.TLS); err != nil {
  285. if strings.Contains(err.Error(), "Username and Password not accepted") {
  286. return nil, ErrUserNotExist
  287. }
  288. return nil, err
  289. }
  290. if !autoRegister {
  291. return u, nil
  292. }
  293. var loginName = name
  294. idx := strings.Index(name, "@")
  295. if idx > -1 {
  296. loginName = name[:idx]
  297. }
  298. // fake a local user creation
  299. u = &User{
  300. LowerName: strings.ToLower(loginName),
  301. Name: strings.ToLower(loginName),
  302. LoginType: SMTP,
  303. LoginSource: sourceId,
  304. LoginName: name,
  305. IsActive: true,
  306. Passwd: passwd,
  307. Email: name,
  308. }
  309. err := CreateUser(u)
  310. return u, err
  311. }