user.go 30 KB

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