You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 14 kB

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