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.go 8.1KB

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