user.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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/sha256"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/gogits/git"
  15. "github.com/gogits/gogs/modules/base"
  16. "github.com/gogits/gogs/modules/log"
  17. "github.com/gogits/gogs/modules/setting"
  18. )
  19. type UserType int
  20. const (
  21. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  22. ORGANIZATION
  23. )
  24. var (
  25. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  26. ErrUserAlreadyExist = errors.New("User already exist")
  27. ErrUserNotExist = errors.New("User does not exist")
  28. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  29. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  30. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  31. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  32. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  33. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  34. )
  35. // User represents the object of individual and member of organization.
  36. type User struct {
  37. Id int64
  38. LowerName string `xorm:"unique not null"`
  39. Name string `xorm:"unique not null"`
  40. FullName string
  41. Email string `xorm:"unique not null"`
  42. Passwd string `xorm:"not null"`
  43. LoginType LoginType
  44. LoginSource int64 `xorm:"not null default 0"`
  45. LoginName string
  46. Type UserType
  47. Orgs []*User `xorm:"-"`
  48. NumFollowers int
  49. NumFollowings int
  50. NumStars int
  51. NumRepos int
  52. Avatar string `xorm:"varchar(2048) not null"`
  53. AvatarEmail string `xorm:"not null"`
  54. Location string
  55. Website string
  56. IsActive bool
  57. IsAdmin bool
  58. Rands string `xorm:"VARCHAR(10)"`
  59. Salt string `xorm:"VARCHAR(10)"`
  60. Created time.Time `xorm:"created"`
  61. Updated time.Time `xorm:"updated"`
  62. // For organization.
  63. NumTeams int
  64. NumMembers int
  65. }
  66. // HomeLink returns the user home page link.
  67. func (u *User) HomeLink() string {
  68. return "/user/" + u.Name
  69. }
  70. // AvatarLink returns user gravatar link.
  71. func (u *User) AvatarLink() string {
  72. if setting.DisableGravatar {
  73. return "/img/avatar_default.jpg"
  74. } else if setting.Service.EnableCacheAvatar {
  75. return "/avatar/" + u.Avatar
  76. }
  77. return "//1.gravatar.com/avatar/" + u.Avatar
  78. }
  79. // NewGitSig generates and returns the signature of given user.
  80. func (u *User) NewGitSig() *git.Signature {
  81. return &git.Signature{
  82. Name: u.Name,
  83. Email: u.Email,
  84. When: time.Now(),
  85. }
  86. }
  87. // EncodePasswd encodes password to safe format.
  88. func (u *User) EncodePasswd() {
  89. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  90. u.Passwd = fmt.Sprintf("%x", newPasswd)
  91. }
  92. func (u *User) IsOrganization() bool {
  93. return u.Type == ORGANIZATION
  94. }
  95. func (u *User) GetOrganizations() error {
  96. ous, err := GetOrgUsersByUserId(u.Id)
  97. if err != nil {
  98. return err
  99. }
  100. u.Orgs = make([]*User, len(ous))
  101. for i, ou := range ous {
  102. u.Orgs[i], err = GetUserById(ou.OrgId)
  103. if err != nil {
  104. return err
  105. }
  106. }
  107. return nil
  108. }
  109. // Member represents user is member of organization.
  110. type Member struct {
  111. Id int64
  112. OrgId int64 `xorm:"unique(member) index"`
  113. UserId int64 `xorm:"unique(member)"`
  114. }
  115. // IsUserExist checks if given user name exist,
  116. // the user name should be noncased unique.
  117. func IsUserExist(name string) (bool, error) {
  118. if len(name) == 0 {
  119. return false, nil
  120. }
  121. return x.Get(&User{LowerName: strings.ToLower(name)})
  122. }
  123. // IsEmailUsed returns true if the e-mail has been used.
  124. func IsEmailUsed(email string) (bool, error) {
  125. if len(email) == 0 {
  126. return false, nil
  127. }
  128. return x.Get(&User{Email: email})
  129. }
  130. // GetUserSalt returns a user salt token
  131. func GetUserSalt() string {
  132. return base.GetRandomString(10)
  133. }
  134. // CreateUser creates record of a new user.
  135. func CreateUser(u *User) (*User, error) {
  136. if !IsLegalName(u.Name) {
  137. return nil, ErrUserNameIllegal
  138. }
  139. isExist, err := IsUserExist(u.Name)
  140. if err != nil {
  141. return nil, err
  142. } else if isExist {
  143. return nil, ErrUserAlreadyExist
  144. }
  145. isExist, err = IsEmailUsed(u.Email)
  146. if err != nil {
  147. return nil, err
  148. } else if isExist {
  149. return nil, ErrEmailAlreadyUsed
  150. }
  151. u.LowerName = strings.ToLower(u.Name)
  152. u.Avatar = base.EncodeMd5(u.Email)
  153. u.AvatarEmail = u.Email
  154. u.Rands = GetUserSalt()
  155. u.Salt = GetUserSalt()
  156. u.EncodePasswd()
  157. sess := x.NewSession()
  158. defer sess.Close()
  159. if err = sess.Begin(); err != nil {
  160. return nil, err
  161. }
  162. if _, err = sess.Insert(u); err != nil {
  163. sess.Rollback()
  164. return nil, err
  165. }
  166. if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  167. sess.Rollback()
  168. return nil, err
  169. }
  170. if err = sess.Commit(); err != nil {
  171. return nil, err
  172. }
  173. // Auto-set admin for user whose ID is 1.
  174. if u.Id == 1 {
  175. u.IsAdmin = true
  176. u.IsActive = true
  177. _, err = x.Id(u.Id).UseBool().Update(u)
  178. }
  179. return u, err
  180. }
  181. // CreateOrganization creates record of a new organization.
  182. func CreateOrganization(org, owner *User) (*User, error) {
  183. if !IsLegalName(org.Name) {
  184. return nil, ErrUserNameIllegal
  185. }
  186. isExist, err := IsUserExist(org.Name)
  187. if err != nil {
  188. return nil, err
  189. } else if isExist {
  190. return nil, ErrUserAlreadyExist
  191. }
  192. isExist, err = IsEmailUsed(org.Email)
  193. if err != nil {
  194. return nil, err
  195. } else if isExist {
  196. return nil, ErrEmailAlreadyUsed
  197. }
  198. org.LowerName = strings.ToLower(org.Name)
  199. org.Avatar = base.EncodeMd5(org.Email)
  200. org.AvatarEmail = org.Email
  201. // No password for organization.
  202. org.NumTeams = 1
  203. org.NumMembers = 1
  204. sess := x.NewSession()
  205. defer sess.Close()
  206. if err = sess.Begin(); err != nil {
  207. return nil, err
  208. }
  209. if _, err = sess.Insert(org); err != nil {
  210. sess.Rollback()
  211. return nil, err
  212. }
  213. // Create default owner team.
  214. t := &Team{
  215. OrgId: org.Id,
  216. Name: "Owner",
  217. Authorize: ORG_ADMIN,
  218. NumMembers: 1,
  219. }
  220. if _, err = sess.Insert(t); err != nil {
  221. sess.Rollback()
  222. return nil, err
  223. }
  224. // Add initial creator to organization and owner team.
  225. ou := &OrgUser{
  226. Uid: owner.Id,
  227. OrgId: org.Id,
  228. IsOwner: true,
  229. NumTeam: 1,
  230. }
  231. if _, err = sess.Insert(ou); err != nil {
  232. sess.Rollback()
  233. return nil, err
  234. }
  235. tu := &TeamUser{
  236. Uid: owner.Id,
  237. OrgId: org.Id,
  238. TeamId: t.Id,
  239. }
  240. if _, err = sess.Insert(tu); err != nil {
  241. sess.Rollback()
  242. return nil, err
  243. }
  244. return org, sess.Commit()
  245. }
  246. // GetUsers returns given number of user objects with offset.
  247. func GetUsers(num, offset int) ([]User, error) {
  248. users := make([]User, 0, num)
  249. err := x.Limit(num, offset).Asc("id").Find(&users)
  250. return users, err
  251. }
  252. // get user by erify code
  253. func getVerifyUser(code string) (user *User) {
  254. if len(code) <= base.TimeLimitCodeLength {
  255. return nil
  256. }
  257. // use tail hex username query user
  258. hexStr := code[base.TimeLimitCodeLength:]
  259. if b, err := hex.DecodeString(hexStr); err == nil {
  260. if user, err = GetUserByName(string(b)); user != nil {
  261. return user
  262. }
  263. log.Error("user.getVerifyUser: %v", err)
  264. }
  265. return nil
  266. }
  267. // verify active code when active account
  268. func VerifyUserActiveCode(code string) (user *User) {
  269. minutes := setting.Service.ActiveCodeLives
  270. if user = getVerifyUser(code); user != nil {
  271. // time limit code
  272. prefix := code[:base.TimeLimitCodeLength]
  273. data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  274. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  275. return user
  276. }
  277. }
  278. return nil
  279. }
  280. // ChangeUserName changes all corresponding setting from old user name to new one.
  281. func ChangeUserName(user *User, newUserName string) (err error) {
  282. newUserName = strings.ToLower(newUserName)
  283. // Update accesses of user.
  284. accesses := make([]Access, 0, 10)
  285. if err = x.Find(&accesses, &Access{UserName: user.LowerName}); err != nil {
  286. return err
  287. }
  288. sess := x.NewSession()
  289. defer sess.Close()
  290. if err = sess.Begin(); err != nil {
  291. return err
  292. }
  293. for i := range accesses {
  294. accesses[i].UserName = newUserName
  295. if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") {
  296. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1)
  297. }
  298. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  299. return err
  300. }
  301. }
  302. repos, err := GetRepositories(user.Id, true)
  303. if err != nil {
  304. return err
  305. }
  306. for i := range repos {
  307. accesses = make([]Access, 0, 10)
  308. // Update accesses of user repository.
  309. if err = x.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repos[i].LowerName}); err != nil {
  310. return err
  311. }
  312. for j := range accesses {
  313. accesses[j].UserName = newUserName
  314. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  315. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  316. return err
  317. }
  318. }
  319. }
  320. // Change user directory name.
  321. if err = os.Rename(UserPath(user.LowerName), UserPath(newUserName)); err != nil {
  322. sess.Rollback()
  323. return err
  324. }
  325. return sess.Commit()
  326. }
  327. // UpdateUser updates user's information.
  328. func UpdateUser(u *User) (err error) {
  329. u.LowerName = strings.ToLower(u.Name)
  330. if len(u.Location) > 255 {
  331. u.Location = u.Location[:255]
  332. }
  333. if len(u.Website) > 255 {
  334. u.Website = u.Website[:255]
  335. }
  336. _, err = x.Id(u.Id).AllCols().Update(u)
  337. return err
  338. }
  339. // DeleteUser completely deletes everything of the user.
  340. func DeleteUser(user *User) error {
  341. // Check ownership of repository.
  342. count, err := GetRepositoryCount(user)
  343. if err != nil {
  344. return errors.New("modesl.GetRepositories: " + err.Error())
  345. } else if count > 0 {
  346. return ErrUserOwnRepos
  347. }
  348. // TODO: check issues, other repos' commits
  349. // Delete all followers.
  350. if _, err = x.Delete(&Follow{FollowId: user.Id}); err != nil {
  351. return err
  352. }
  353. // Delete oauth2.
  354. if _, err = x.Delete(&Oauth2{Uid: user.Id}); err != nil {
  355. return err
  356. }
  357. // Delete all feeds.
  358. if _, err = x.Delete(&Action{UserId: user.Id}); err != nil {
  359. return err
  360. }
  361. // Delete all watches.
  362. if _, err = x.Delete(&Watch{UserId: user.Id}); err != nil {
  363. return err
  364. }
  365. // Delete all accesses.
  366. if _, err = x.Delete(&Access{UserName: user.LowerName}); err != nil {
  367. return err
  368. }
  369. // Delete all SSH keys.
  370. keys := make([]*PublicKey, 0, 10)
  371. if err = x.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  372. return err
  373. }
  374. for _, key := range keys {
  375. if err = DeletePublicKey(key); err != nil {
  376. return err
  377. }
  378. }
  379. // Delete user directory.
  380. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  381. return err
  382. }
  383. _, err = x.Delete(user)
  384. return err
  385. }
  386. // DeleteInactivateUsers deletes all inactivate users.
  387. func DeleteInactivateUsers() error {
  388. _, err := x.Where("is_active=?", false).Delete(new(User))
  389. return err
  390. }
  391. // UserPath returns the path absolute path of user repositories.
  392. func UserPath(userName string) string {
  393. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  394. }
  395. func GetUserByKeyId(keyId int64) (*User, error) {
  396. user := new(User)
  397. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  398. has, err := x.Sql(rawSql, keyId).Get(user)
  399. if err != nil {
  400. return nil, err
  401. } else if !has {
  402. return nil, ErrUserNotKeyOwner
  403. }
  404. return user, nil
  405. }
  406. // GetUserById returns the user object by given ID if exists.
  407. func GetUserById(id int64) (*User, error) {
  408. u := new(User)
  409. has, err := x.Id(id).Get(u)
  410. if err != nil {
  411. return nil, err
  412. } else if !has {
  413. return nil, ErrUserNotExist
  414. }
  415. return u, nil
  416. }
  417. // GetUserByName returns the user object by given name if exists.
  418. func GetUserByName(name string) (*User, error) {
  419. if len(name) == 0 {
  420. return nil, ErrUserNotExist
  421. }
  422. user := &User{LowerName: strings.ToLower(name)}
  423. has, err := x.Get(user)
  424. if err != nil {
  425. return nil, err
  426. } else if !has {
  427. return nil, ErrUserNotExist
  428. }
  429. return user, nil
  430. }
  431. // GetUserEmailsByNames returns a slice of e-mails corresponds to names.
  432. func GetUserEmailsByNames(names []string) []string {
  433. mails := make([]string, 0, len(names))
  434. for _, name := range names {
  435. u, err := GetUserByName(name)
  436. if err != nil {
  437. continue
  438. }
  439. mails = append(mails, u.Email)
  440. }
  441. return mails
  442. }
  443. // GetUserIdsByNames returns a slice of ids corresponds to names.
  444. func GetUserIdsByNames(names []string) []int64 {
  445. ids := make([]int64, 0, len(names))
  446. for _, name := range names {
  447. u, err := GetUserByName(name)
  448. if err != nil {
  449. continue
  450. }
  451. ids = append(ids, u.Id)
  452. }
  453. return ids
  454. }
  455. // GetUserByEmail returns the user object by given e-mail if exists.
  456. func GetUserByEmail(email string) (*User, error) {
  457. if len(email) == 0 {
  458. return nil, ErrUserNotExist
  459. }
  460. user := &User{Email: strings.ToLower(email)}
  461. has, err := x.Get(user)
  462. if err != nil {
  463. return nil, err
  464. } else if !has {
  465. return nil, ErrUserNotExist
  466. }
  467. return user, nil
  468. }
  469. // SearchUserByName returns given number of users whose name contains keyword.
  470. func SearchUserByName(key string, limit int) (us []*User, err error) {
  471. // Prevent SQL inject.
  472. key = strings.TrimSpace(key)
  473. if len(key) == 0 {
  474. return us, nil
  475. }
  476. key = strings.Split(key, " ")[0]
  477. if len(key) == 0 {
  478. return us, nil
  479. }
  480. key = strings.ToLower(key)
  481. us = make([]*User, 0, limit)
  482. err = x.Limit(limit).Where("lower_name like '%" + key + "%'").Find(&us)
  483. return us, err
  484. }
  485. // Follow is connection request for receiving user notifycation.
  486. type Follow struct {
  487. Id int64
  488. UserId int64 `xorm:"unique(follow)"`
  489. FollowId int64 `xorm:"unique(follow)"`
  490. }
  491. // FollowUser marks someone be another's follower.
  492. func FollowUser(userId int64, followId int64) (err error) {
  493. session := x.NewSession()
  494. defer session.Close()
  495. session.Begin()
  496. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  497. session.Rollback()
  498. return err
  499. }
  500. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  501. if _, err = session.Exec(rawSql, followId); err != nil {
  502. session.Rollback()
  503. return err
  504. }
  505. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  506. if _, err = session.Exec(rawSql, userId); err != nil {
  507. session.Rollback()
  508. return err
  509. }
  510. return session.Commit()
  511. }
  512. // UnFollowUser unmarks someone be another's follower.
  513. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  514. session := x.NewSession()
  515. defer session.Close()
  516. session.Begin()
  517. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  518. session.Rollback()
  519. return err
  520. }
  521. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  522. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  523. session.Rollback()
  524. return err
  525. }
  526. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  527. if _, err = session.Exec(rawSql, userId); err != nil {
  528. session.Rollback()
  529. return err
  530. }
  531. return session.Commit()
  532. }