user.go 30 KB

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