login.go 7.7 KB

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