login.go 7.9 KB

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