user.go 31 KB

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