login.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. var _ core.Conversion = &LDAPConfig{}
  33. type LDAPConfig struct {
  34. ldap.Ldapsource
  35. }
  36. // implement
  37. func (cfg *LDAPConfig) FromDB(bs []byte) error {
  38. return json.Unmarshal(bs, &cfg.Ldapsource)
  39. }
  40. func (cfg *LDAPConfig) ToDB() ([]byte, error) {
  41. return json.Marshal(cfg.Ldapsource)
  42. }
  43. type SMTPConfig struct {
  44. Auth string
  45. Host string
  46. Post string
  47. TLS bool
  48. }
  49. // implement
  50. func (cfg *SMTPConfig) FromDB(bs []byte) error {
  51. return json.Unmarshal(bs, cfg)
  52. }
  53. func (cfg *SMTPConfig) ToDB() ([]byte, error) {
  54. return json.Marshal(cfg)
  55. }
  56. type LoginSource struct {
  57. Id int64
  58. Type int
  59. Name string `xorm:"unique"`
  60. IsActived bool `xorm:"not null default false"`
  61. Cfg core.Conversion `xorm:"TEXT"`
  62. Created time.Time `xorm:"created"`
  63. Updated time.Time `xorm:"updated"`
  64. AllowAutoRegisted bool `xorm:"not null default false"`
  65. }
  66. func (source *LoginSource) TypeString() string {
  67. return LoginTypes[source.Type]
  68. }
  69. func (source *LoginSource) LDAP() *LDAPConfig {
  70. return source.Cfg.(*LDAPConfig)
  71. }
  72. func (source *LoginSource) SMTP() *SMTPConfig {
  73. return source.Cfg.(*SMTPConfig)
  74. }
  75. // for xorm callback
  76. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) {
  77. if colName == "type" {
  78. ty := (*val).(int64)
  79. switch ty {
  80. case LT_LDAP:
  81. source.Cfg = new(LDAPConfig)
  82. case LT_SMTP:
  83. source.Cfg = new(SMTPConfig)
  84. }
  85. }
  86. }
  87. func GetAuths() ([]*LoginSource, error) {
  88. var auths = make([]*LoginSource, 0)
  89. err := orm.Find(&auths)
  90. return auths, err
  91. }
  92. func GetLoginSourceById(id int64) (*LoginSource, error) {
  93. source := new(LoginSource)
  94. has, err := orm.Id(id).Get(source)
  95. if err != nil {
  96. return nil, err
  97. }
  98. if !has {
  99. return nil, ErrAuthenticationNotExist
  100. }
  101. return source, nil
  102. }
  103. func AddLDAPSource(name string, cfg *LDAPConfig) error {
  104. _, err := orm.Insert(&LoginSource{Type: LT_LDAP,
  105. Name: name,
  106. IsActived: true,
  107. Cfg: cfg,
  108. })
  109. return err
  110. }
  111. func UpdateLDAPSource(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. var emailLogin bool
  130. if strings.Contains(uname, "@") {
  131. u = &User{Email: uname}
  132. emailLogin = true
  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 email login, then we cannot auto register
  141. if emailLogin {
  142. if !has {
  143. return nil, ErrUserNotExist
  144. }
  145. }
  146. if u.LoginType == LT_NOTYPE {
  147. u.LoginType = LT_PLAIN
  148. }
  149. // for plain login, user must have existed.
  150. if u.LoginType == LT_PLAIN {
  151. if !has {
  152. return nil, ErrUserNotExist
  153. }
  154. newUser := &User{Passwd: passwd, Salt: u.Salt}
  155. newUser.EncodePasswd()
  156. if u.Passwd != newUser.Passwd {
  157. return nil, ErrUserNotExist
  158. }
  159. return u, nil
  160. } else {
  161. if !has {
  162. var sources []LoginSource
  163. cond := &LoginSource{IsActived: true, AllowAutoRegisted: true}
  164. err = orm.UseBool().Find(&sources, cond)
  165. if err != nil {
  166. return nil, err
  167. }
  168. for _, source := range sources {
  169. if source.Type == LT_LDAP {
  170. u, err := LoginUserLdapSource(nil, u.LoginName, passwd,
  171. source.Id, source.Cfg.(*LDAPConfig), true)
  172. if err == nil {
  173. return u, err
  174. }
  175. } else if source.Type == LT_SMTP {
  176. u, err := LoginUserSMTPSource(nil, u.LoginName, passwd,
  177. source.Id, source.Cfg.(*SMTPConfig), true)
  178. if err == nil {
  179. return u, 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. }
  190. if !hasSource {
  191. return nil, ErrLoginSourceNotExist
  192. }
  193. if !source.IsActived {
  194. return nil, ErrLoginSourceNotActived
  195. }
  196. switch u.LoginType {
  197. case LT_LDAP:
  198. return LoginUserLdapSource(u, u.LoginName, passwd,
  199. source.Id, source.Cfg.(*LDAPConfig), false)
  200. case LT_SMTP:
  201. return LoginUserSMTPSource(u, u.LoginName, passwd,
  202. source.Id, source.Cfg.(*SMTPConfig), false)
  203. }
  204. return nil, ErrUnsupportedLoginType
  205. }
  206. }
  207. // Query if name/passwd can login against the LDAP direcotry pool
  208. // Create a local user if success
  209. // Return the same LoginUserPlain semantic
  210. func LoginUserLdapSource(user *User, name, passwd string, sourceId int64, cfg *LDAPConfig, autoRegister bool) (*User, error) {
  211. mail, logged := cfg.Ldapsource.SearchEntry(name, passwd)
  212. if !logged {
  213. // user not in LDAP, do nothing
  214. return nil, ErrUserNotExist
  215. }
  216. if !autoRegister {
  217. return user, nil
  218. }
  219. // fake a local user creation
  220. user = &User{
  221. LowerName: strings.ToLower(name),
  222. Name: strings.ToLower(name),
  223. LoginType: LT_LDAP,
  224. LoginSource: sourceId,
  225. LoginName: name,
  226. IsActive: true,
  227. Passwd: passwd,
  228. Email: mail,
  229. }
  230. return RegisterUser(user)
  231. }
  232. type loginAuth struct {
  233. username, password string
  234. }
  235. func LoginAuth(username, password string) smtp.Auth {
  236. return &loginAuth{username, password}
  237. }
  238. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  239. return "LOGIN", []byte(a.username), nil
  240. }
  241. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  242. if more {
  243. switch string(fromServer) {
  244. case "Username:":
  245. return []byte(a.username), nil
  246. case "Password:":
  247. return []byte(a.password), nil
  248. }
  249. }
  250. return nil, nil
  251. }
  252. var (
  253. smtpAuths = []string{"plain", "login", ""}
  254. )
  255. func SmtpAuth(addr string, a smtp.Auth) error {
  256. c, err := smtp.Dial(addr)
  257. if err != nil {
  258. return err
  259. }
  260. defer c.Close()
  261. if ok, _ := c.Extension("STARTTLS"); ok {
  262. if err = c.StartTLS(nil); err != nil {
  263. return err
  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 == "plain" {
  281. auth = smtp.PlainAuth("", name, passwd, cfg.Host)
  282. } else if cfg.Auth == "login" {
  283. auth = LoginAuth(name, passwd)
  284. }
  285. err := SmtpAuth(fmt.Sprintf("%s:%d", cfg.Host, cfg.Post), auth)
  286. if err != nil {
  287. return nil, err
  288. }
  289. if !autoRegister {
  290. return user, nil
  291. }
  292. // fake a local user creation
  293. user = &User{
  294. LowerName: strings.ToLower(name),
  295. Name: strings.ToLower(name),
  296. LoginType: LT_SMTP,
  297. LoginSource: sourceId,
  298. LoginName: name,
  299. IsActive: true,
  300. Passwd: passwd,
  301. Email: name,
  302. }
  303. return RegisterUser(user)
  304. }