user.go 31 KB

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