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.

360 lines
8.0 KiB

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
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
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
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
  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. )
  18. type LoginType int
  19. const (
  20. NOTYPE LoginType = iota
  21. PLAIN
  22. LDAP
  23. SMTP
  24. )
  25. var (
  26. ErrAuthenticationAlreadyExist = errors.New("Authentication already exist")
  27. ErrAuthenticationNotExist = errors.New("Authentication does not exist")
  28. ErrAuthenticationUserUsed = errors.New("Authentication has been used by some users")
  29. )
  30. var LoginTypes = map[LoginType]string{
  31. LDAP: "LDAP",
  32. SMTP: "SMTP",
  33. }
  34. // Ensure structs implmented interface.
  35. var (
  36. _ core.Conversion = &LDAPConfig{}
  37. _ core.Conversion = &SMTPConfig{}
  38. )
  39. type LDAPConfig struct {
  40. ldap.Ldapsource
  41. }
  42. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  43. return json.Unmarshal(bs, &cfg.Ldapsource)
  44. }
  45. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  46. return json.Marshal(cfg.Ldapsource)
  47. }
  48. type SMTPConfig struct {
  49. Auth string
  50. Host string
  51. Port int
  52. TLS bool
  53. }
  54. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  55. return json.Unmarshal(bs, cfg)
  56. }
  57. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  58. return json.Marshal(cfg)
  59. }
  60. type LoginSource struct {
  61. Id int64
  62. Type LoginType
  63. Name string `xorm:"UNIQUE"`
  64. IsActived bool `xorm:"NOT NULL DEFAULT false"`
  65. Cfg core.Conversion `xorm:"TEXT"`
  66. AllowAutoRegister bool `xorm:"NOT NULL DEFAULT false"`
  67. Created time.Time `xorm:"CREATED"`
  68. Updated time.Time `xorm:"UPDATED"`
  69. }
  70. func (source *LoginSource) TypeString() string {
  71. return LoginTypes[source.Type]
  72. }
  73. func (source *LoginSource) LDAP() *LDAPConfig {
  74. return source.Cfg.(*LDAPConfig)
  75. }
  76. func (source *LoginSource) SMTP() *SMTPConfig {
  77. return source.Cfg.(*SMTPConfig)
  78. }
  79. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  80. if colName == "type" {
  81. ty := (*val).(int64)
  82. switch LoginType(ty) {
  83. case LDAP:
  84. source.Cfg = new(LDAPConfig)
  85. case SMTP:
  86. source.Cfg = new(SMTPConfig)
  87. }
  88. }
  89. }
  90. func CreateSource(source *LoginSource) error {
  91. _, err := x.Insert(source)
  92. return err
  93. }
  94. func GetAuths() ([]*LoginSource, error) {
  95. var auths = make([]*LoginSource, 0, 5)
  96. err := x.Find(&auths)
  97. return auths, err
  98. }
  99. func GetLoginSourceById(id int64) (*LoginSource, error) {
  100. source := new(LoginSource)
  101. has, err := x.Id(id).Get(source)
  102. if err != nil {
  103. return nil, err
  104. } else if !has {
  105. return nil, ErrAuthenticationNotExist
  106. }
  107. return source, nil
  108. }
  109. func UpdateSource(source *LoginSource) error {
  110. _, err := x.Id(source.Id).AllCols().Update(source)
  111. return err
  112. }
  113. func DelLoginSource(source *LoginSource) error {
  114. cnt, err := x.Count(&User{LoginSource: source.Id})
  115. if err != nil {
  116. return err
  117. }
  118. if cnt > 0 {
  119. return ErrAuthenticationUserUsed
  120. }
  121. _, err = x.Id(source.Id).Delete(&LoginSource{})
  122. return err
  123. }
  124. // UserSignIn validates user name and password.
  125. func UserSignIn(uname, passwd string) (*User, error) {
  126. u := new(User)
  127. if strings.Contains(uname, "@") {
  128. u = &User{Email: uname}
  129. } else {
  130. u = &User{LowerName: strings.ToLower(uname)}
  131. }
  132. has, err := x.Get(u)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if u.LoginType == NOTYPE && has {
  137. u.LoginType = PLAIN
  138. }
  139. // For plain login, user must exist to reach this line.
  140. // Now verify password.
  141. if u.LoginType == PLAIN {
  142. newUser := &User{Passwd: passwd, Salt: u.Salt}
  143. newUser.EncodePasswd()
  144. if u.Passwd != newUser.Passwd {
  145. return nil, ErrUserNotExist
  146. }
  147. return u, nil
  148. } else {
  149. if !has {
  150. var sources []LoginSource
  151. if err = x.UseBool().Find(&sources,
  152. &LoginSource{IsActived: true, AllowAutoRegister: true}); err != nil {
  153. return nil, err
  154. }
  155. for _, source := range sources {
  156. if source.Type == LDAP {
  157. u, err := LoginUserLdapSource(nil, uname, passwd,
  158. source.Id, source.Cfg.(*LDAPConfig), true)
  159. if err == nil {
  160. return u, nil
  161. }
  162. log.Warn("Fail to login(%s) by LDAP(%s): %v", uname, source.Name, err)
  163. } else if source.Type == SMTP {
  164. u, err := LoginUserSMTPSource(nil, uname, passwd,
  165. source.Id, source.Cfg.(*SMTPConfig), true)
  166. if err == nil {
  167. return u, nil
  168. }
  169. log.Warn("Fail to login(%s) by SMTP(%s): %v", uname, source.Name, err)
  170. }
  171. }
  172. return nil, ErrUserNotExist
  173. }
  174. var source LoginSource
  175. hasSource, err := x.Id(u.LoginSource).Get(&source)
  176. if err != nil {
  177. return nil, err
  178. } else if !hasSource {
  179. return nil, ErrLoginSourceNotExist
  180. } else if !source.IsActived {
  181. return nil, ErrLoginSourceNotActived
  182. }
  183. switch u.LoginType {
  184. case LDAP:
  185. return LoginUserLdapSource(u, u.LoginName, passwd,
  186. source.Id, source.Cfg.(*LDAPConfig), false)
  187. case SMTP:
  188. return LoginUserSMTPSource(u, u.LoginName, passwd,
  189. source.Id, source.Cfg.(*SMTPConfig), false)
  190. }
  191. return nil, ErrUnsupportedLoginType
  192. }
  193. }
  194. // Query if name/passwd can login against the LDAP direcotry pool
  195. // Create a local user if success
  196. // Return the same LoginUserPlain semantic
  197. func LoginUserLdapSource(u *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) {
  198. mail, logged := cfg.Ldapsource.SearchEntry(name, passwd)
  199. if !logged {
  200. // user not in LDAP, do nothing
  201. return nil, ErrUserNotExist
  202. }
  203. if !autoRegister {
  204. return u, nil
  205. }
  206. // fake a local user creation
  207. u = &User{
  208. LowerName: strings.ToLower(name),
  209. Name: strings.ToLower(name),
  210. LoginType: LDAP,
  211. LoginSource: sourceId,
  212. LoginName: name,
  213. IsActive: true,
  214. Passwd: passwd,
  215. Email: mail,
  216. }
  217. err := CreateUser(u)
  218. return u, err
  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 direcotry 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. }