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 29 kB

11 years ago
11 years ago
11 years ago
11 years ago
9 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
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 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
10 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
9 years ago
10 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 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
9 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "image"
  13. "image/jpeg"
  14. _ "image/jpeg"
  15. "image/png"
  16. "os"
  17. "path"
  18. "path/filepath"
  19. "strings"
  20. "time"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. "github.com/nfnt/resize"
  24. "github.com/gogits/git-shell"
  25. "github.com/gogits/gogs/modules/avatar"
  26. "github.com/gogits/gogs/modules/base"
  27. "github.com/gogits/gogs/modules/log"
  28. "github.com/gogits/gogs/modules/setting"
  29. )
  30. type UserType int
  31. const (
  32. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  33. ORGANIZATION
  34. )
  35. var (
  36. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  37. ErrEmailNotExist = errors.New("E-mail does not exist")
  38. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  39. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  40. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  41. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  42. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  43. )
  44. // User represents the object of individual and member of organization.
  45. type User struct {
  46. Id int64
  47. LowerName string `xorm:"UNIQUE NOT NULL"`
  48. Name string `xorm:"UNIQUE NOT NULL"`
  49. FullName string
  50. // Email is the primary email address (to be used for communication).
  51. Email string `xorm:"NOT NULL"`
  52. Passwd string `xorm:"NOT NULL"`
  53. LoginType LoginType
  54. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  55. LoginName string
  56. Type UserType
  57. OwnedOrgs []*User `xorm:"-"`
  58. Orgs []*User `xorm:"-"`
  59. Repos []*Repository `xorm:"-"`
  60. Location string
  61. Website string
  62. Rands string `xorm:"VARCHAR(10)"`
  63. Salt string `xorm:"VARCHAR(10)"`
  64. Created time.Time `xorm:"CREATED"`
  65. Updated time.Time `xorm:"UPDATED"`
  66. // Remember visibility choice for convenience, true for private
  67. LastRepoVisibility bool
  68. // Maximum repository creation limit, 0 means use gloabl default
  69. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  70. // Permissions.
  71. IsActive bool
  72. IsAdmin bool
  73. AllowGitHook bool
  74. AllowImportLocal bool // Allow migrate repository by local path
  75. // Avatar.
  76. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  77. AvatarEmail string `xorm:"NOT NULL"`
  78. UseCustomAvatar bool
  79. // Counters.
  80. NumFollowers int
  81. NumFollowings int
  82. NumStars int
  83. NumRepos int
  84. // For organization.
  85. Description string
  86. NumTeams int
  87. NumMembers int
  88. Teams []*Team `xorm:"-"`
  89. Members []*User `xorm:"-"`
  90. }
  91. func (u *User) BeforeUpdate() {
  92. if u.MaxRepoCreation < -1 {
  93. u.MaxRepoCreation = -1
  94. }
  95. }
  96. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  97. switch colName {
  98. case "full_name":
  99. u.FullName = base.Sanitizer.Sanitize(u.FullName)
  100. case "created":
  101. u.Created = regulateTimeZone(u.Created)
  102. }
  103. }
  104. // returns true if user login type is LOGIN_PLAIN.
  105. func (u *User) IsLocal() bool {
  106. return u.LoginType <= LOGIN_PLAIN
  107. }
  108. // HasForkedRepo checks if user has already forked a repository with given ID.
  109. func (u *User) HasForkedRepo(repoID int64) bool {
  110. _, has := HasForkedRepo(u.Id, repoID)
  111. return has
  112. }
  113. func (u *User) RepoCreationNum() int {
  114. if u.MaxRepoCreation <= -1 {
  115. return setting.Repository.MaxCreationLimit
  116. }
  117. return u.MaxRepoCreation
  118. }
  119. func (u *User) CanCreateRepo() bool {
  120. if u.MaxRepoCreation <= -1 {
  121. if setting.Repository.MaxCreationLimit == -1 {
  122. return true
  123. }
  124. return u.NumRepos < setting.Repository.MaxCreationLimit
  125. }
  126. return u.NumRepos < u.MaxRepoCreation
  127. }
  128. // CanEditGitHook returns true if user can edit Git hooks.
  129. func (u *User) CanEditGitHook() bool {
  130. return u.IsAdmin || u.AllowGitHook
  131. }
  132. // CanImportLocal returns true if user can migrate repository by local path.
  133. func (u *User) CanImportLocal() bool {
  134. return u.IsAdmin || u.AllowImportLocal
  135. }
  136. // EmailAdresses is the list of all email addresses of a user. Can contain the
  137. // primary email address, but is not obligatory
  138. type EmailAddress struct {
  139. ID int64 `xorm:"pk autoincr"`
  140. UID int64 `xorm:"INDEX NOT NULL"`
  141. Email string `xorm:"UNIQUE NOT NULL"`
  142. IsActivated bool
  143. IsPrimary bool `xorm:"-"`
  144. }
  145. // DashboardLink returns the user dashboard page link.
  146. func (u *User) DashboardLink() string {
  147. if u.IsOrganization() {
  148. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  149. }
  150. return setting.AppSubUrl + "/"
  151. }
  152. // HomeLink returns the user or organization home page link.
  153. func (u *User) HomeLink() string {
  154. return setting.AppSubUrl + "/" + u.Name
  155. }
  156. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  157. func (u *User) GenerateEmailActivateCode(email string) string {
  158. code := base.CreateTimeLimitCode(
  159. com.ToStr(u.Id)+email+u.LowerName+u.Passwd+u.Rands,
  160. setting.Service.ActiveCodeLives, nil)
  161. // Add tail hex username
  162. code += hex.EncodeToString([]byte(u.LowerName))
  163. return code
  164. }
  165. // GenerateActivateCode generates an activate code based on user information.
  166. func (u *User) GenerateActivateCode() string {
  167. return u.GenerateEmailActivateCode(u.Email)
  168. }
  169. // CustomAvatarPath returns user custom avatar file path.
  170. func (u *User) CustomAvatarPath() string {
  171. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
  172. }
  173. // GenerateRandomAvatar generates a random avatar for user.
  174. func (u *User) GenerateRandomAvatar() error {
  175. seed := u.Email
  176. if len(seed) == 0 {
  177. seed = u.Name
  178. }
  179. img, err := avatar.RandomImage([]byte(seed))
  180. if err != nil {
  181. return fmt.Errorf("RandomImage: %v", err)
  182. }
  183. if err = os.MkdirAll(path.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  184. return fmt.Errorf("MkdirAll: %v", err)
  185. }
  186. fw, err := os.Create(u.CustomAvatarPath())
  187. if err != nil {
  188. return fmt.Errorf("Create: %v", err)
  189. }
  190. defer fw.Close()
  191. if err = jpeg.Encode(fw, img, nil); err != nil {
  192. return fmt.Errorf("Encode: %v", err)
  193. }
  194. log.Info("New random avatar created: %d", u.Id)
  195. return nil
  196. }
  197. func (u *User) RelAvatarLink() string {
  198. defaultImgUrl := "/img/avatar_default.jpg"
  199. if u.Id == -1 {
  200. return defaultImgUrl
  201. }
  202. switch {
  203. case u.UseCustomAvatar:
  204. if !com.IsExist(u.CustomAvatarPath()) {
  205. return defaultImgUrl
  206. }
  207. return "/avatars/" + com.ToStr(u.Id)
  208. case setting.DisableGravatar, setting.OfflineMode:
  209. if !com.IsExist(u.CustomAvatarPath()) {
  210. if err := u.GenerateRandomAvatar(); err != nil {
  211. log.Error(3, "GenerateRandomAvatar: %v", err)
  212. }
  213. }
  214. return "/avatars/" + com.ToStr(u.Id)
  215. case setting.Service.EnableCacheAvatar:
  216. return "/avatar/" + u.Avatar
  217. }
  218. return setting.GravatarSource + u.Avatar
  219. }
  220. // AvatarLink returns user gravatar link.
  221. func (u *User) AvatarLink() string {
  222. link := u.RelAvatarLink()
  223. if link[0] == '/' && link[1] != '/' {
  224. return setting.AppSubUrl + link
  225. }
  226. return link
  227. }
  228. // NewGitSig generates and returns the signature of given user.
  229. func (u *User) NewGitSig() *git.Signature {
  230. return &git.Signature{
  231. Name: u.Name,
  232. Email: u.Email,
  233. When: time.Now(),
  234. }
  235. }
  236. // EncodePasswd encodes password to safe format.
  237. func (u *User) EncodePasswd() {
  238. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  239. u.Passwd = fmt.Sprintf("%x", newPasswd)
  240. }
  241. // ValidatePassword checks if given password matches the one belongs to the user.
  242. func (u *User) ValidatePassword(passwd string) bool {
  243. newUser := &User{Passwd: passwd, Salt: u.Salt}
  244. newUser.EncodePasswd()
  245. return u.Passwd == newUser.Passwd
  246. }
  247. // UploadAvatar saves custom avatar for user.
  248. // FIXME: split uploads to different subdirs in case we have massive users.
  249. func (u *User) UploadAvatar(data []byte) error {
  250. img, _, err := image.Decode(bytes.NewReader(data))
  251. if err != nil {
  252. return fmt.Errorf("Decode: %v", err)
  253. }
  254. m := resize.Resize(290, 290, img, resize.NearestNeighbor)
  255. sess := x.NewSession()
  256. defer sessionRelease(sess)
  257. if err = sess.Begin(); err != nil {
  258. return err
  259. }
  260. u.UseCustomAvatar = true
  261. if err = updateUser(sess, u); err != nil {
  262. return fmt.Errorf("updateUser: %v", err)
  263. }
  264. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  265. fw, err := os.Create(u.CustomAvatarPath())
  266. if err != nil {
  267. return fmt.Errorf("Create: %v", err)
  268. }
  269. defer fw.Close()
  270. if err = png.Encode(fw, m); err != nil {
  271. return fmt.Errorf("Encode: %v", err)
  272. }
  273. return sess.Commit()
  274. }
  275. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  276. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  277. if err := repo.GetOwner(); err != nil {
  278. log.Error(3, "GetOwner: %v", err)
  279. return false
  280. }
  281. if repo.Owner.IsOrganization() {
  282. has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
  283. if err != nil {
  284. log.Error(3, "HasAccess: %v", err)
  285. return false
  286. }
  287. return has
  288. }
  289. return repo.IsOwnedBy(u.Id)
  290. }
  291. // IsOrganization returns true if user is actually a organization.
  292. func (u *User) IsOrganization() bool {
  293. return u.Type == ORGANIZATION
  294. }
  295. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  296. func (u *User) IsUserOrgOwner(orgId int64) bool {
  297. return IsOrganizationOwner(orgId, u.Id)
  298. }
  299. // IsPublicMember returns true if user public his/her membership in give organization.
  300. func (u *User) IsPublicMember(orgId int64) bool {
  301. return IsPublicMembership(orgId, u.Id)
  302. }
  303. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  304. return e.Where("uid=?", u.Id).Count(new(OrgUser))
  305. }
  306. // GetOrganizationCount returns count of membership of organization of user.
  307. func (u *User) GetOrganizationCount() (int64, error) {
  308. return u.getOrganizationCount(x)
  309. }
  310. // GetRepositories returns all repositories that user owns, including private repositories.
  311. func (u *User) GetRepositories() (err error) {
  312. u.Repos, err = GetRepositories(u.Id, true)
  313. return err
  314. }
  315. // GetOwnedOrganizations returns all organizations that user owns.
  316. func (u *User) GetOwnedOrganizations() (err error) {
  317. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.Id)
  318. return err
  319. }
  320. // GetOrganizations returns all organizations that user belongs to.
  321. func (u *User) GetOrganizations() error {
  322. ous, err := GetOrgUsersByUserId(u.Id)
  323. if err != nil {
  324. return err
  325. }
  326. u.Orgs = make([]*User, len(ous))
  327. for i, ou := range ous {
  328. u.Orgs[i], err = GetUserByID(ou.OrgID)
  329. if err != nil {
  330. return err
  331. }
  332. }
  333. return nil
  334. }
  335. // DisplayName returns full name if it's not empty,
  336. // returns username otherwise.
  337. func (u *User) DisplayName() string {
  338. if len(u.FullName) > 0 {
  339. return u.FullName
  340. }
  341. return u.Name
  342. }
  343. // ShortName returns shorted user name with given maximum length,
  344. // it adds "..." at the end if user name has more length than maximum.
  345. func (u *User) ShortName(length int) string {
  346. if len(u.Name) < length {
  347. return u.Name
  348. }
  349. return u.Name[:length] + "..."
  350. }
  351. // IsUserExist checks if given user name exist,
  352. // the user name should be noncased unique.
  353. // If uid is presented, then check will rule out that one,
  354. // it is used when update a user name in settings page.
  355. func IsUserExist(uid int64, name string) (bool, error) {
  356. if len(name) == 0 {
  357. return false, nil
  358. }
  359. return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)})
  360. }
  361. // IsEmailUsed returns true if the e-mail has been used.
  362. func IsEmailUsed(email string) (bool, error) {
  363. if len(email) == 0 {
  364. return false, nil
  365. }
  366. email = strings.ToLower(email)
  367. if has, err := x.Get(&EmailAddress{Email: email}); has || err != nil {
  368. return has, err
  369. }
  370. return x.Get(&User{Email: email})
  371. }
  372. // GetUserSalt returns a ramdom user salt token.
  373. func GetUserSalt() string {
  374. return base.GetRandomString(10)
  375. }
  376. // NewFakeUser creates and returns a fake user for someone has deleted his/her account.
  377. func NewFakeUser() *User {
  378. return &User{
  379. Id: -1,
  380. Name: "Someone",
  381. LowerName: "someone",
  382. }
  383. }
  384. // CreateUser creates record of a new user.
  385. func CreateUser(u *User) (err error) {
  386. if err = IsUsableName(u.Name); err != nil {
  387. return err
  388. }
  389. isExist, err := IsUserExist(0, u.Name)
  390. if err != nil {
  391. return err
  392. } else if isExist {
  393. return ErrUserAlreadyExist{u.Name}
  394. }
  395. u.Email = strings.ToLower(u.Email)
  396. isExist, err = IsEmailUsed(u.Email)
  397. if err != nil {
  398. return err
  399. } else if isExist {
  400. return ErrEmailAlreadyUsed{u.Email}
  401. }
  402. u.LowerName = strings.ToLower(u.Name)
  403. u.AvatarEmail = u.Email
  404. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  405. u.Rands = GetUserSalt()
  406. u.Salt = GetUserSalt()
  407. u.EncodePasswd()
  408. sess := x.NewSession()
  409. defer sess.Close()
  410. if err = sess.Begin(); err != nil {
  411. return err
  412. }
  413. if _, err = sess.Insert(u); err != nil {
  414. sess.Rollback()
  415. return err
  416. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  417. sess.Rollback()
  418. return err
  419. }
  420. return sess.Commit()
  421. }
  422. func countUsers(e Engine) int64 {
  423. count, _ := e.Where("type=0").Count(new(User))
  424. return count
  425. }
  426. // CountUsers returns number of users.
  427. func CountUsers() int64 {
  428. return countUsers(x)
  429. }
  430. // Users returns number of users in given page.
  431. func Users(page, pageSize int) ([]*User, error) {
  432. users := make([]*User, 0, pageSize)
  433. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  434. }
  435. // get user by erify code
  436. func getVerifyUser(code string) (user *User) {
  437. if len(code) <= base.TimeLimitCodeLength {
  438. return nil
  439. }
  440. // use tail hex username query user
  441. hexStr := code[base.TimeLimitCodeLength:]
  442. if b, err := hex.DecodeString(hexStr); err == nil {
  443. if user, err = GetUserByName(string(b)); user != nil {
  444. return user
  445. }
  446. log.Error(4, "user.getVerifyUser: %v", err)
  447. }
  448. return nil
  449. }
  450. // verify active code when active account
  451. func VerifyUserActiveCode(code string) (user *User) {
  452. minutes := setting.Service.ActiveCodeLives
  453. if user = getVerifyUser(code); user != nil {
  454. // time limit code
  455. prefix := code[:base.TimeLimitCodeLength]
  456. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  457. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  458. return user
  459. }
  460. }
  461. return nil
  462. }
  463. // verify active code when active account
  464. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  465. minutes := setting.Service.ActiveCodeLives
  466. if user := getVerifyUser(code); user != nil {
  467. // time limit code
  468. prefix := code[:base.TimeLimitCodeLength]
  469. data := com.ToStr(user.Id) + email + user.LowerName + user.Passwd + user.Rands
  470. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  471. emailAddress := &EmailAddress{Email: email}
  472. if has, _ := x.Get(emailAddress); has {
  473. return emailAddress
  474. }
  475. }
  476. }
  477. return nil
  478. }
  479. // ChangeUserName changes all corresponding setting from old user name to new one.
  480. func ChangeUserName(u *User, newUserName string) (err error) {
  481. if err = IsUsableName(newUserName); err != nil {
  482. return err
  483. }
  484. isExist, err := IsUserExist(0, newUserName)
  485. if err != nil {
  486. return err
  487. } else if isExist {
  488. return ErrUserAlreadyExist{newUserName}
  489. }
  490. return os.Rename(UserPath(u.LowerName), UserPath(newUserName))
  491. }
  492. func updateUser(e Engine, u *User) error {
  493. // Organization does not need e-mail.
  494. if !u.IsOrganization() {
  495. u.Email = strings.ToLower(u.Email)
  496. has, err := e.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  497. if err != nil {
  498. return err
  499. } else if has {
  500. return ErrEmailAlreadyUsed{u.Email}
  501. }
  502. if len(u.AvatarEmail) == 0 {
  503. u.AvatarEmail = u.Email
  504. }
  505. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  506. }
  507. u.LowerName = strings.ToLower(u.Name)
  508. if len(u.Location) > 255 {
  509. u.Location = u.Location[:255]
  510. }
  511. if len(u.Website) > 255 {
  512. u.Website = u.Website[:255]
  513. }
  514. if len(u.Description) > 255 {
  515. u.Description = u.Description[:255]
  516. }
  517. u.FullName = base.Sanitizer.Sanitize(u.FullName)
  518. _, err := e.Id(u.Id).AllCols().Update(u)
  519. return err
  520. }
  521. // UpdateUser updates user's information.
  522. func UpdateUser(u *User) error {
  523. return updateUser(x, u)
  524. }
  525. // deleteBeans deletes all given beans, beans should contain delete conditions.
  526. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  527. for i := range beans {
  528. if _, err = e.Delete(beans[i]); err != nil {
  529. return err
  530. }
  531. }
  532. return nil
  533. }
  534. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  535. func deleteUser(e *xorm.Session, u *User) error {
  536. // Note: A user owns any repository or belongs to any organization
  537. // cannot perform delete operation.
  538. // Check ownership of repository.
  539. count, err := getRepositoryCount(e, u)
  540. if err != nil {
  541. return fmt.Errorf("GetRepositoryCount: %v", err)
  542. } else if count > 0 {
  543. return ErrUserOwnRepos{UID: u.Id}
  544. }
  545. // Check membership of organization.
  546. count, err = u.getOrganizationCount(e)
  547. if err != nil {
  548. return fmt.Errorf("GetOrganizationCount: %v", err)
  549. } else if count > 0 {
  550. return ErrUserHasOrgs{UID: u.Id}
  551. }
  552. // ***** START: Watch *****
  553. watches := make([]*Watch, 0, 10)
  554. if err = e.Find(&watches, &Watch{UserID: u.Id}); err != nil {
  555. return fmt.Errorf("get all watches: %v", err)
  556. }
  557. for i := range watches {
  558. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  559. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  560. }
  561. }
  562. // ***** END: Watch *****
  563. // ***** START: Star *****
  564. stars := make([]*Star, 0, 10)
  565. if err = e.Find(&stars, &Star{UID: u.Id}); err != nil {
  566. return fmt.Errorf("get all stars: %v", err)
  567. }
  568. for i := range stars {
  569. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  570. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  571. }
  572. }
  573. // ***** END: Star *****
  574. // ***** START: Follow *****
  575. followers := make([]*Follow, 0, 10)
  576. if err = e.Find(&followers, &Follow{UserID: u.Id}); err != nil {
  577. return fmt.Errorf("get all followers: %v", err)
  578. }
  579. for i := range followers {
  580. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  581. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  582. }
  583. }
  584. // ***** END: Follow *****
  585. if err = deleteBeans(e,
  586. &AccessToken{UID: u.Id},
  587. &Collaboration{UserID: u.Id},
  588. &Access{UserID: u.Id},
  589. &Watch{UserID: u.Id},
  590. &Star{UID: u.Id},
  591. &Follow{FollowID: u.Id},
  592. &Action{UserID: u.Id},
  593. &IssueUser{UID: u.Id},
  594. &EmailAddress{UID: u.Id},
  595. ); err != nil {
  596. return fmt.Errorf("deleteBeans: %v", err)
  597. }
  598. // ***** START: PublicKey *****
  599. keys := make([]*PublicKey, 0, 10)
  600. if err = e.Find(&keys, &PublicKey{OwnerID: u.Id}); err != nil {
  601. return fmt.Errorf("get all public keys: %v", err)
  602. }
  603. for _, key := range keys {
  604. if err = deletePublicKey(e, key.ID); err != nil {
  605. return fmt.Errorf("deletePublicKey: %v", err)
  606. }
  607. }
  608. // ***** END: PublicKey *****
  609. // Clear assignee.
  610. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.Id); err != nil {
  611. return fmt.Errorf("clear assignee: %v", err)
  612. }
  613. if _, err = e.Id(u.Id).Delete(new(User)); err != nil {
  614. return fmt.Errorf("Delete: %v", err)
  615. }
  616. // FIXME: system notice
  617. // Note: There are something just cannot be roll back,
  618. // so just keep error logs of those operations.
  619. RewriteAllPublicKeys()
  620. os.RemoveAll(UserPath(u.Name))
  621. os.Remove(u.CustomAvatarPath())
  622. return nil
  623. }
  624. // DeleteUser completely and permanently deletes everything of a user,
  625. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  626. func DeleteUser(u *User) (err error) {
  627. sess := x.NewSession()
  628. defer sessionRelease(sess)
  629. if err = sess.Begin(); err != nil {
  630. return err
  631. }
  632. if err = deleteUser(sess, u); err != nil {
  633. // Note: don't wrapper error here.
  634. return err
  635. }
  636. return sess.Commit()
  637. }
  638. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  639. func DeleteInactivateUsers() (err error) {
  640. users := make([]*User, 0, 10)
  641. if err = x.Where("is_active=?", false).Find(&users); err != nil {
  642. return fmt.Errorf("get all inactive users: %v", err)
  643. }
  644. for _, u := range users {
  645. if err = DeleteUser(u); err != nil {
  646. // Ignore users that were set inactive by admin.
  647. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  648. continue
  649. }
  650. return err
  651. }
  652. }
  653. _, err = x.Where("is_activated=?", false).Delete(new(EmailAddress))
  654. return err
  655. }
  656. // UserPath returns the path absolute path of user repositories.
  657. func UserPath(userName string) string {
  658. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  659. }
  660. func GetUserByKeyID(keyID int64) (*User, error) {
  661. user := new(User)
  662. has, err := x.Sql("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  663. if err != nil {
  664. return nil, err
  665. } else if !has {
  666. return nil, ErrUserNotKeyOwner
  667. }
  668. return user, nil
  669. }
  670. func getUserByID(e Engine, id int64) (*User, error) {
  671. u := new(User)
  672. has, err := e.Id(id).Get(u)
  673. if err != nil {
  674. return nil, err
  675. } else if !has {
  676. return nil, ErrUserNotExist{id, ""}
  677. }
  678. return u, nil
  679. }
  680. // GetUserByID returns the user object by given ID if exists.
  681. func GetUserByID(id int64) (*User, error) {
  682. return getUserByID(x, id)
  683. }
  684. // GetAssigneeByID returns the user with write access of repository by given ID.
  685. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  686. has, err := HasAccess(&User{Id: userID}, repo, ACCESS_MODE_WRITE)
  687. if err != nil {
  688. return nil, err
  689. } else if !has {
  690. return nil, ErrUserNotExist{userID, ""}
  691. }
  692. return GetUserByID(userID)
  693. }
  694. // GetUserByName returns user by given name.
  695. func GetUserByName(name string) (*User, error) {
  696. if len(name) == 0 {
  697. return nil, ErrUserNotExist{0, name}
  698. }
  699. u := &User{LowerName: strings.ToLower(name)}
  700. has, err := x.Get(u)
  701. if err != nil {
  702. return nil, err
  703. } else if !has {
  704. return nil, ErrUserNotExist{0, name}
  705. }
  706. return u, nil
  707. }
  708. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  709. func GetUserEmailsByNames(names []string) []string {
  710. mails := make([]string, 0, len(names))
  711. for _, name := range names {
  712. u, err := GetUserByName(name)
  713. if err != nil {
  714. continue
  715. }
  716. mails = append(mails, u.Email)
  717. }
  718. return mails
  719. }
  720. // GetUserIdsByNames returns a slice of ids corresponds to names.
  721. func GetUserIdsByNames(names []string) []int64 {
  722. ids := make([]int64, 0, len(names))
  723. for _, name := range names {
  724. u, err := GetUserByName(name)
  725. if err != nil {
  726. continue
  727. }
  728. ids = append(ids, u.Id)
  729. }
  730. return ids
  731. }
  732. // GetEmailAddresses returns all e-mail addresses belongs to given user.
  733. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
  734. emails := make([]*EmailAddress, 0, 5)
  735. err := x.Where("uid=?", uid).Find(&emails)
  736. if err != nil {
  737. return nil, err
  738. }
  739. u, err := GetUserByID(uid)
  740. if err != nil {
  741. return nil, err
  742. }
  743. isPrimaryFound := false
  744. for _, email := range emails {
  745. if email.Email == u.Email {
  746. isPrimaryFound = true
  747. email.IsPrimary = true
  748. } else {
  749. email.IsPrimary = false
  750. }
  751. }
  752. // We alway want the primary email address displayed, even if it's not in
  753. // the emailaddress table (yet)
  754. if !isPrimaryFound {
  755. emails = append(emails, &EmailAddress{
  756. Email: u.Email,
  757. IsActivated: true,
  758. IsPrimary: true,
  759. })
  760. }
  761. return emails, nil
  762. }
  763. func AddEmailAddress(email *EmailAddress) error {
  764. email.Email = strings.ToLower(email.Email)
  765. used, err := IsEmailUsed(email.Email)
  766. if err != nil {
  767. return err
  768. } else if used {
  769. return ErrEmailAlreadyUsed{email.Email}
  770. }
  771. _, err = x.Insert(email)
  772. return err
  773. }
  774. func (email *EmailAddress) Activate() error {
  775. email.IsActivated = true
  776. if _, err := x.Id(email.ID).AllCols().Update(email); err != nil {
  777. return err
  778. }
  779. if user, err := GetUserByID(email.UID); err != nil {
  780. return err
  781. } else {
  782. user.Rands = GetUserSalt()
  783. return UpdateUser(user)
  784. }
  785. }
  786. func DeleteEmailAddress(email *EmailAddress) error {
  787. has, err := x.Get(email)
  788. if err != nil {
  789. return err
  790. } else if !has {
  791. return ErrEmailNotExist
  792. }
  793. if _, err = x.Id(email.ID).Delete(email); err != nil {
  794. return err
  795. }
  796. return nil
  797. }
  798. func MakeEmailPrimary(email *EmailAddress) error {
  799. has, err := x.Get(email)
  800. if err != nil {
  801. return err
  802. } else if !has {
  803. return ErrEmailNotExist
  804. }
  805. if !email.IsActivated {
  806. return ErrEmailNotActivated
  807. }
  808. user := &User{Id: email.UID}
  809. has, err = x.Get(user)
  810. if err != nil {
  811. return err
  812. } else if !has {
  813. return ErrUserNotExist{email.UID, ""}
  814. }
  815. // Make sure the former primary email doesn't disappear
  816. former_primary_email := &EmailAddress{Email: user.Email}
  817. has, err = x.Get(former_primary_email)
  818. if err != nil {
  819. return err
  820. } else if !has {
  821. former_primary_email.UID = user.Id
  822. former_primary_email.IsActivated = user.IsActive
  823. x.Insert(former_primary_email)
  824. }
  825. user.Email = email.Email
  826. _, err = x.Id(user.Id).AllCols().Update(user)
  827. return err
  828. }
  829. // UserCommit represents a commit with validation of user.
  830. type UserCommit struct {
  831. User *User
  832. *git.Commit
  833. }
  834. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  835. func ValidateCommitWithEmail(c *git.Commit) *User {
  836. u, err := GetUserByEmail(c.Author.Email)
  837. if err != nil {
  838. return nil
  839. }
  840. return u
  841. }
  842. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  843. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  844. var (
  845. u *User
  846. emails = map[string]*User{}
  847. newCommits = list.New()
  848. e = oldCommits.Front()
  849. )
  850. for e != nil {
  851. c := e.Value.(*git.Commit)
  852. if v, ok := emails[c.Author.Email]; !ok {
  853. u, _ = GetUserByEmail(c.Author.Email)
  854. emails[c.Author.Email] = u
  855. } else {
  856. u = v
  857. }
  858. newCommits.PushBack(UserCommit{
  859. User: u,
  860. Commit: c,
  861. })
  862. e = e.Next()
  863. }
  864. return newCommits
  865. }
  866. // GetUserByEmail returns the user object by given e-mail if exists.
  867. func GetUserByEmail(email string) (*User, error) {
  868. if len(email) == 0 {
  869. return nil, ErrUserNotExist{0, "email"}
  870. }
  871. email = strings.ToLower(email)
  872. // First try to find the user by primary email
  873. user := &User{Email: email}
  874. has, err := x.Get(user)
  875. if err != nil {
  876. return nil, err
  877. }
  878. if has {
  879. return user, nil
  880. }
  881. // Otherwise, check in alternative list for activated email addresses
  882. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  883. has, err = x.Get(emailAddress)
  884. if err != nil {
  885. return nil, err
  886. }
  887. if has {
  888. return GetUserByID(emailAddress.UID)
  889. }
  890. return nil, ErrUserNotExist{0, email}
  891. }
  892. // SearchUserByName returns given number of users whose name contains keyword.
  893. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  894. if len(opt.Keyword) == 0 {
  895. return us, nil
  896. }
  897. opt.Keyword = strings.ToLower(opt.Keyword)
  898. us = make([]*User, 0, opt.Limit)
  899. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  900. return us, err
  901. }
  902. // Follow is connection request for receiving user notification.
  903. type Follow struct {
  904. ID int64 `xorm:"pk autoincr"`
  905. UserID int64 `xorm:"UNIQUE(follow)"`
  906. FollowID int64 `xorm:"UNIQUE(follow)"`
  907. }
  908. // FollowUser marks someone be another's follower.
  909. func FollowUser(userId int64, followId int64) (err error) {
  910. sess := x.NewSession()
  911. defer sess.Close()
  912. sess.Begin()
  913. if _, err = sess.Insert(&Follow{UserID: userId, FollowID: followId}); err != nil {
  914. sess.Rollback()
  915. return err
  916. }
  917. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  918. if _, err = sess.Exec(rawSql, followId); err != nil {
  919. sess.Rollback()
  920. return err
  921. }
  922. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  923. if _, err = sess.Exec(rawSql, userId); err != nil {
  924. sess.Rollback()
  925. return err
  926. }
  927. return sess.Commit()
  928. }
  929. // UnFollowUser unmarks someone be another's follower.
  930. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  931. session := x.NewSession()
  932. defer session.Close()
  933. session.Begin()
  934. if _, err = session.Delete(&Follow{UserID: userId, FollowID: unFollowId}); err != nil {
  935. session.Rollback()
  936. return err
  937. }
  938. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  939. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  940. session.Rollback()
  941. return err
  942. }
  943. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  944. if _, err = session.Exec(rawSql, userId); err != nil {
  945. session.Rollback()
  946. return err
  947. }
  948. return session.Commit()
  949. }
  950. func UpdateMentions(userNames []string, issueId int64) error {
  951. for i := range userNames {
  952. userNames[i] = strings.ToLower(userNames[i])
  953. }
  954. users := make([]*User, 0, len(userNames))
  955. if err := x.Where("lower_name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("lower_name ASC").Find(&users); err != nil {
  956. return err
  957. }
  958. ids := make([]int64, 0, len(userNames))
  959. for _, user := range users {
  960. ids = append(ids, user.Id)
  961. if !user.IsOrganization() {
  962. continue
  963. }
  964. if user.NumMembers == 0 {
  965. continue
  966. }
  967. tempIds := make([]int64, 0, user.NumMembers)
  968. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  969. if err != nil {
  970. return err
  971. }
  972. for _, orgUser := range orgUsers {
  973. tempIds = append(tempIds, orgUser.ID)
  974. }
  975. ids = append(ids, tempIds...)
  976. }
  977. if err := UpdateIssueUsersByMentions(ids, issueId); err != nil {
  978. return err
  979. }
  980. return nil
  981. }