Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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