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