You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  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/md5"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. "image"
  15. // Needed for jpeg support
  16. _ "image/jpeg"
  17. "image/png"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "time"
  22. "unicode/utf8"
  23. "github.com/Unknwon/com"
  24. "github.com/go-xorm/builder"
  25. "github.com/go-xorm/xorm"
  26. "github.com/nfnt/resize"
  27. "golang.org/x/crypto/pbkdf2"
  28. "code.gitea.io/git"
  29. api "code.gitea.io/sdk/gitea"
  30. "code.gitea.io/gitea/modules/avatar"
  31. "code.gitea.io/gitea/modules/base"
  32. "code.gitea.io/gitea/modules/generate"
  33. "code.gitea.io/gitea/modules/log"
  34. "code.gitea.io/gitea/modules/setting"
  35. "code.gitea.io/gitea/modules/util"
  36. )
  37. // UserType defines the user type
  38. type UserType int
  39. const (
  40. // UserTypeIndividual defines an individual user
  41. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  42. // UserTypeOrganization defines an organization
  43. UserTypeOrganization
  44. )
  45. const syncExternalUsers = "sync_external_users"
  46. var (
  47. // ErrUserNotKeyOwner user does not own this key error
  48. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  49. // ErrEmailNotExist e-mail does not exist error
  50. ErrEmailNotExist = errors.New("E-mail does not exist")
  51. // ErrEmailNotActivated e-mail address has not been activated error
  52. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  53. // ErrUserNameIllegal user name contains illegal characters error
  54. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  55. // ErrLoginSourceNotActived login source is not actived error
  56. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  57. // ErrUnsupportedLoginType login source is unknown error
  58. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  59. )
  60. // User represents the object of individual and member of organization.
  61. type User struct {
  62. ID int64 `xorm:"pk autoincr"`
  63. LowerName string `xorm:"UNIQUE NOT NULL"`
  64. Name string `xorm:"UNIQUE NOT NULL"`
  65. FullName string
  66. // Email is the primary email address (to be used for communication)
  67. Email string `xorm:"NOT NULL"`
  68. KeepEmailPrivate bool
  69. Passwd string `xorm:"NOT NULL"`
  70. LoginType LoginType
  71. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  72. LoginName string
  73. Type UserType
  74. OwnedOrgs []*User `xorm:"-"`
  75. Orgs []*User `xorm:"-"`
  76. Repos []*Repository `xorm:"-"`
  77. Location string
  78. Website string
  79. Rands string `xorm:"VARCHAR(10)"`
  80. Salt string `xorm:"VARCHAR(10)"`
  81. Language string `xorm:"VARCHAR(5)"`
  82. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  83. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  84. LastLoginUnix util.TimeStamp `xorm:"INDEX"`
  85. // Remember visibility choice for convenience, true for private
  86. LastRepoVisibility bool
  87. // Maximum repository creation limit, -1 means use global default
  88. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  89. // Permissions
  90. IsActive bool `xorm:"INDEX"` // Activate primary email
  91. IsAdmin bool
  92. AllowGitHook bool
  93. AllowImportLocal bool // Allow migrate repository by local path
  94. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  95. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  96. // Avatar
  97. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  98. AvatarEmail string `xorm:"NOT NULL"`
  99. UseCustomAvatar bool
  100. // Counters
  101. NumFollowers int
  102. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  103. NumStars int
  104. NumRepos int
  105. // For organization
  106. Description string
  107. NumTeams int
  108. NumMembers int
  109. Teams []*Team `xorm:"-"`
  110. Members []*User `xorm:"-"`
  111. // Preferences
  112. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  113. }
  114. // BeforeUpdate is invoked from XORM before updating this object.
  115. func (u *User) BeforeUpdate() {
  116. if u.MaxRepoCreation < -1 {
  117. u.MaxRepoCreation = -1
  118. }
  119. // Organization does not need email
  120. u.Email = strings.ToLower(u.Email)
  121. if !u.IsOrganization() {
  122. if len(u.AvatarEmail) == 0 {
  123. u.AvatarEmail = u.Email
  124. }
  125. if len(u.AvatarEmail) > 0 && u.Avatar == "" {
  126. u.Avatar = base.HashEmail(u.AvatarEmail)
  127. }
  128. }
  129. u.LowerName = strings.ToLower(u.Name)
  130. u.Location = base.TruncateString(u.Location, 255)
  131. u.Website = base.TruncateString(u.Website, 255)
  132. u.Description = base.TruncateString(u.Description, 255)
  133. }
  134. // SetLastLogin set time to last login
  135. func (u *User) SetLastLogin() {
  136. u.LastLoginUnix = util.TimeStampNow()
  137. }
  138. // UpdateDiffViewStyle updates the users diff view style
  139. func (u *User) UpdateDiffViewStyle(style string) error {
  140. u.DiffViewStyle = style
  141. return UpdateUserCols(u, "diff_view_style")
  142. }
  143. // getEmail returns an noreply email, if the user has set to keep his
  144. // email address private, otherwise the primary email address.
  145. func (u *User) getEmail() string {
  146. if u.KeepEmailPrivate {
  147. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  148. }
  149. return u.Email
  150. }
  151. // APIFormat converts a User to api.User
  152. func (u *User) APIFormat() *api.User {
  153. return &api.User{
  154. ID: u.ID,
  155. UserName: u.Name,
  156. FullName: u.FullName,
  157. Email: u.getEmail(),
  158. AvatarURL: u.AvatarLink(),
  159. Language: u.Language,
  160. }
  161. }
  162. // IsLocal returns true if user login type is LoginPlain.
  163. func (u *User) IsLocal() bool {
  164. return u.LoginType <= LoginPlain
  165. }
  166. // IsOAuth2 returns true if user login type is LoginOAuth2.
  167. func (u *User) IsOAuth2() bool {
  168. return u.LoginType == LoginOAuth2
  169. }
  170. // HasForkedRepo checks if user has already forked a repository with given ID.
  171. func (u *User) HasForkedRepo(repoID int64) bool {
  172. _, has := HasForkedRepo(u.ID, repoID)
  173. return has
  174. }
  175. // MaxCreationLimit returns the number of repositories a user is allowed to create
  176. func (u *User) MaxCreationLimit() int {
  177. if u.MaxRepoCreation <= -1 {
  178. return setting.Repository.MaxCreationLimit
  179. }
  180. return u.MaxRepoCreation
  181. }
  182. // CanCreateRepo returns if user login can create a repository
  183. func (u *User) CanCreateRepo() bool {
  184. if u.IsAdmin {
  185. return true
  186. }
  187. if u.MaxRepoCreation <= -1 {
  188. if setting.Repository.MaxCreationLimit <= -1 {
  189. return true
  190. }
  191. return u.NumRepos < setting.Repository.MaxCreationLimit
  192. }
  193. return u.NumRepos < u.MaxRepoCreation
  194. }
  195. // CanCreateOrganization returns true if user can create organisation.
  196. func (u *User) CanCreateOrganization() bool {
  197. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  198. }
  199. // CanEditGitHook returns true if user can edit Git hooks.
  200. func (u *User) CanEditGitHook() bool {
  201. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  202. }
  203. // CanImportLocal returns true if user can migrate repository by local path.
  204. func (u *User) CanImportLocal() bool {
  205. if !setting.ImportLocalPaths {
  206. return false
  207. }
  208. return u.IsAdmin || u.AllowImportLocal
  209. }
  210. // DashboardLink returns the user dashboard page link.
  211. func (u *User) DashboardLink() string {
  212. if u.IsOrganization() {
  213. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  214. }
  215. return setting.AppSubURL + "/"
  216. }
  217. // HomeLink returns the user or organization home page link.
  218. func (u *User) HomeLink() string {
  219. return setting.AppSubURL + "/" + u.Name
  220. }
  221. // HTMLURL returns the user or organization's full link.
  222. func (u *User) HTMLURL() string {
  223. return setting.AppURL + u.Name
  224. }
  225. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  226. func (u *User) GenerateEmailActivateCode(email string) string {
  227. code := base.CreateTimeLimitCode(
  228. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  229. setting.Service.ActiveCodeLives, nil)
  230. // Add tail hex username
  231. code += hex.EncodeToString([]byte(u.LowerName))
  232. return code
  233. }
  234. // GenerateActivateCode generates an activate code based on user information.
  235. func (u *User) GenerateActivateCode() string {
  236. return u.GenerateEmailActivateCode(u.Email)
  237. }
  238. // CustomAvatarPath returns user custom avatar file path.
  239. func (u *User) CustomAvatarPath() string {
  240. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  241. }
  242. // GenerateRandomAvatar generates a random avatar for user.
  243. func (u *User) GenerateRandomAvatar() error {
  244. return u.generateRandomAvatar(x)
  245. }
  246. func (u *User) generateRandomAvatar(e Engine) error {
  247. seed := u.Email
  248. if len(seed) == 0 {
  249. seed = u.Name
  250. }
  251. img, err := avatar.RandomImage([]byte(seed))
  252. if err != nil {
  253. return fmt.Errorf("RandomImage: %v", err)
  254. }
  255. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  256. // since random image is not a user's photo, there is no security for enumable
  257. if u.Avatar == "" {
  258. u.Avatar = fmt.Sprintf("%d", u.ID)
  259. }
  260. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  261. return fmt.Errorf("MkdirAll: %v", err)
  262. }
  263. fw, err := os.Create(u.CustomAvatarPath())
  264. if err != nil {
  265. return fmt.Errorf("Create: %v", err)
  266. }
  267. defer fw.Close()
  268. if _, err := e.ID(u.ID).Cols("avatar").Update(u); err != nil {
  269. return err
  270. }
  271. if err = png.Encode(fw, img); err != nil {
  272. return fmt.Errorf("Encode: %v", err)
  273. }
  274. log.Info("New random avatar created: %d", u.ID)
  275. return nil
  276. }
  277. // SizedRelAvatarLink returns a relative link to the user's avatar. When
  278. // applicable, the link is for an avatar of the indicated size (in pixels).
  279. func (u *User) SizedRelAvatarLink(size int) string {
  280. if u.ID == -1 {
  281. return base.DefaultAvatarLink()
  282. }
  283. switch {
  284. case u.UseCustomAvatar:
  285. if !com.IsFile(u.CustomAvatarPath()) {
  286. return base.DefaultAvatarLink()
  287. }
  288. return setting.AppSubURL + "/avatars/" + u.Avatar
  289. case setting.DisableGravatar, setting.OfflineMode:
  290. if !com.IsFile(u.CustomAvatarPath()) {
  291. if err := u.GenerateRandomAvatar(); err != nil {
  292. log.Error(3, "GenerateRandomAvatar: %v", err)
  293. }
  294. }
  295. return setting.AppSubURL + "/avatars/" + u.Avatar
  296. }
  297. return base.SizedAvatarLink(u.AvatarEmail, size)
  298. }
  299. // RelAvatarLink returns a relative link to the user's avatar. The link
  300. // may either be a sub-URL to this site, or a full URL to an external avatar
  301. // service.
  302. func (u *User) RelAvatarLink() string {
  303. return u.SizedRelAvatarLink(base.DefaultAvatarSize)
  304. }
  305. // AvatarLink returns user avatar absolute link.
  306. func (u *User) AvatarLink() string {
  307. link := u.RelAvatarLink()
  308. if link[0] == '/' && link[1] != '/' {
  309. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  310. }
  311. return link
  312. }
  313. // GetFollowers returns range of user's followers.
  314. func (u *User) GetFollowers(page int) ([]*User, error) {
  315. users := make([]*User, 0, ItemsPerPage)
  316. sess := x.
  317. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  318. Where("follow.follow_id=?", u.ID)
  319. if setting.UsePostgreSQL {
  320. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  321. } else {
  322. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  323. }
  324. return users, sess.Find(&users)
  325. }
  326. // IsFollowing returns true if user is following followID.
  327. func (u *User) IsFollowing(followID int64) bool {
  328. return IsFollowing(u.ID, followID)
  329. }
  330. // GetFollowing returns range of user's following.
  331. func (u *User) GetFollowing(page int) ([]*User, error) {
  332. users := make([]*User, 0, ItemsPerPage)
  333. sess := x.
  334. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  335. Where("follow.user_id=?", u.ID)
  336. if setting.UsePostgreSQL {
  337. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  338. } else {
  339. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  340. }
  341. return users, sess.Find(&users)
  342. }
  343. // NewGitSig generates and returns the signature of given user.
  344. func (u *User) NewGitSig() *git.Signature {
  345. return &git.Signature{
  346. Name: u.DisplayName(),
  347. Email: u.getEmail(),
  348. When: time.Now(),
  349. }
  350. }
  351. func hashPassword(passwd, salt string) string {
  352. tempPasswd := pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  353. return fmt.Sprintf("%x", tempPasswd)
  354. }
  355. // HashPassword hashes a password using PBKDF.
  356. func (u *User) HashPassword(passwd string) {
  357. u.Passwd = hashPassword(passwd, u.Salt)
  358. }
  359. // ValidatePassword checks if given password matches the one belongs to the user.
  360. func (u *User) ValidatePassword(passwd string) bool {
  361. tempHash := hashPassword(passwd, u.Salt)
  362. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1
  363. }
  364. // IsPasswordSet checks if the password is set or left empty
  365. func (u *User) IsPasswordSet() bool {
  366. return !u.ValidatePassword("")
  367. }
  368. // UploadAvatar saves custom avatar for user.
  369. // FIXME: split uploads to different subdirs in case we have massive users.
  370. func (u *User) UploadAvatar(data []byte) error {
  371. img, _, err := image.Decode(bytes.NewReader(data))
  372. if err != nil {
  373. return fmt.Errorf("Decode: %v", err)
  374. }
  375. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  376. sess := x.NewSession()
  377. defer sess.Close()
  378. if err = sess.Begin(); err != nil {
  379. return err
  380. }
  381. u.UseCustomAvatar = true
  382. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  383. if err = updateUser(sess, u); err != nil {
  384. return fmt.Errorf("updateUser: %v", err)
  385. }
  386. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  387. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  388. }
  389. fw, err := os.Create(u.CustomAvatarPath())
  390. if err != nil {
  391. return fmt.Errorf("Create: %v", err)
  392. }
  393. defer fw.Close()
  394. if err = png.Encode(fw, m); err != nil {
  395. return fmt.Errorf("Encode: %v", err)
  396. }
  397. return sess.Commit()
  398. }
  399. // DeleteAvatar deletes the user's custom avatar.
  400. func (u *User) DeleteAvatar() error {
  401. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  402. if len(u.Avatar) > 0 {
  403. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  404. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  405. }
  406. }
  407. u.UseCustomAvatar = false
  408. u.Avatar = ""
  409. if _, err := x.ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  410. return fmt.Errorf("UpdateUser: %v", err)
  411. }
  412. return nil
  413. }
  414. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  415. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  416. has, err := HasAccess(u.ID, repo, AccessModeAdmin)
  417. if err != nil {
  418. log.Error(3, "HasAccess: %v", err)
  419. }
  420. return has
  421. }
  422. // IsWriterOfRepo returns true if user has write access to given repository.
  423. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  424. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  425. if err != nil {
  426. log.Error(3, "HasAccess: %v", err)
  427. }
  428. return has
  429. }
  430. // IsOrganization returns true if user is actually a organization.
  431. func (u *User) IsOrganization() bool {
  432. return u.Type == UserTypeOrganization
  433. }
  434. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  435. func (u *User) IsUserOrgOwner(orgID int64) bool {
  436. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  437. if err != nil {
  438. log.Error(4, "IsOrganizationOwner: %v", err)
  439. return false
  440. }
  441. return isOwner
  442. }
  443. // IsPublicMember returns true if user public his/her membership in given organization.
  444. func (u *User) IsPublicMember(orgID int64) bool {
  445. isMember, err := IsPublicMembership(orgID, u.ID)
  446. if err != nil {
  447. log.Error(4, "IsPublicMembership: %v", err)
  448. return false
  449. }
  450. return isMember
  451. }
  452. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  453. return e.
  454. Where("uid=?", u.ID).
  455. Count(new(OrgUser))
  456. }
  457. // GetOrganizationCount returns count of membership of organization of user.
  458. func (u *User) GetOrganizationCount() (int64, error) {
  459. return u.getOrganizationCount(x)
  460. }
  461. // GetRepositories returns repositories that user owns, including private repositories.
  462. func (u *User) GetRepositories(page, pageSize int) (err error) {
  463. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  464. return err
  465. }
  466. // GetRepositoryIDs returns repositories IDs where user owned
  467. func (u *User) GetRepositoryIDs() ([]int64, error) {
  468. var ids []int64
  469. return ids, x.Table("repository").Cols("id").Where("owner_id = ?", u.ID).Find(&ids)
  470. }
  471. // GetOrgRepositoryIDs returns repositories IDs where user's team owned
  472. func (u *User) GetOrgRepositoryIDs() ([]int64, error) {
  473. var ids []int64
  474. return ids, x.Table("repository").
  475. Cols("repository.id").
  476. Join("INNER", "team_user", "repository.owner_id = team_user.org_id AND team_user.uid = ?", u.ID).
  477. GroupBy("repository.id").Find(&ids)
  478. }
  479. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  480. func (u *User) GetAccessRepoIDs() ([]int64, error) {
  481. ids, err := u.GetRepositoryIDs()
  482. if err != nil {
  483. return nil, err
  484. }
  485. ids2, err := u.GetOrgRepositoryIDs()
  486. if err != nil {
  487. return nil, err
  488. }
  489. return append(ids, ids2...), nil
  490. }
  491. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  492. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  493. return GetUserMirrorRepositories(u.ID)
  494. }
  495. // GetOwnedOrganizations returns all organizations that user owns.
  496. func (u *User) GetOwnedOrganizations() (err error) {
  497. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  498. return err
  499. }
  500. // GetOrganizations returns all organizations that user belongs to.
  501. func (u *User) GetOrganizations(all bool) error {
  502. ous, err := GetOrgUsersByUserID(u.ID, all)
  503. if err != nil {
  504. return err
  505. }
  506. u.Orgs = make([]*User, len(ous))
  507. for i, ou := range ous {
  508. u.Orgs[i], err = GetUserByID(ou.OrgID)
  509. if err != nil {
  510. return err
  511. }
  512. }
  513. return nil
  514. }
  515. // DisplayName returns full name if it's not empty,
  516. // returns username otherwise.
  517. func (u *User) DisplayName() string {
  518. if len(u.FullName) > 0 {
  519. return u.FullName
  520. }
  521. return u.Name
  522. }
  523. // ShortName ellipses username to length
  524. func (u *User) ShortName(length int) string {
  525. return base.EllipsisString(u.Name, length)
  526. }
  527. // IsMailable checks if a user is eligible
  528. // to receive emails.
  529. func (u *User) IsMailable() bool {
  530. return u.IsActive
  531. }
  532. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  533. if len(name) == 0 {
  534. return false, nil
  535. }
  536. return e.
  537. Where("id!=?", uid).
  538. Get(&User{LowerName: strings.ToLower(name)})
  539. }
  540. // IsUserExist checks if given user name exist,
  541. // the user name should be noncased unique.
  542. // If uid is presented, then check will rule out that one,
  543. // it is used when update a user name in settings page.
  544. func IsUserExist(uid int64, name string) (bool, error) {
  545. return isUserExist(x, uid, name)
  546. }
  547. // GetUserSalt returns a random user salt token.
  548. func GetUserSalt() (string, error) {
  549. return generate.GetRandomString(10)
  550. }
  551. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  552. func NewGhostUser() *User {
  553. return &User{
  554. ID: -1,
  555. Name: "Ghost",
  556. LowerName: "ghost",
  557. }
  558. }
  559. var (
  560. reservedUsernames = []string{"assets", "css", "explore", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatars", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "error", "new", ".", ".."}
  561. reservedUserPatterns = []string{"*.keys"}
  562. )
  563. // isUsableName checks if name is reserved or pattern of name is not allowed
  564. // based on given reserved names and patterns.
  565. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  566. func isUsableName(names, patterns []string, name string) error {
  567. name = strings.TrimSpace(strings.ToLower(name))
  568. if utf8.RuneCountInString(name) == 0 {
  569. return ErrNameEmpty
  570. }
  571. for i := range names {
  572. if name == names[i] {
  573. return ErrNameReserved{name}
  574. }
  575. }
  576. for _, pat := range patterns {
  577. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  578. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  579. return ErrNamePatternNotAllowed{pat}
  580. }
  581. }
  582. return nil
  583. }
  584. // IsUsableUsername returns an error when a username is reserved
  585. func IsUsableUsername(name string) error {
  586. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  587. }
  588. // CreateUser creates record of a new user.
  589. func CreateUser(u *User) (err error) {
  590. if err = IsUsableUsername(u.Name); err != nil {
  591. return err
  592. }
  593. sess := x.NewSession()
  594. defer sess.Close()
  595. if err = sess.Begin(); err != nil {
  596. return err
  597. }
  598. isExist, err := isUserExist(sess, 0, u.Name)
  599. if err != nil {
  600. return err
  601. } else if isExist {
  602. return ErrUserAlreadyExist{u.Name}
  603. }
  604. u.Email = strings.ToLower(u.Email)
  605. isExist, err = sess.
  606. Where("email=?", u.Email).
  607. Get(new(User))
  608. if err != nil {
  609. return err
  610. } else if isExist {
  611. return ErrEmailAlreadyUsed{u.Email}
  612. }
  613. isExist, err = isEmailUsed(sess, u.Email)
  614. if err != nil {
  615. return err
  616. } else if isExist {
  617. return ErrEmailAlreadyUsed{u.Email}
  618. }
  619. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  620. u.LowerName = strings.ToLower(u.Name)
  621. u.AvatarEmail = u.Email
  622. u.Avatar = base.HashEmail(u.AvatarEmail)
  623. if u.Rands, err = GetUserSalt(); err != nil {
  624. return err
  625. }
  626. if u.Salt, err = GetUserSalt(); err != nil {
  627. return err
  628. }
  629. u.HashPassword(u.Passwd)
  630. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  631. u.MaxRepoCreation = -1
  632. if _, err = sess.Insert(u); err != nil {
  633. return err
  634. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  635. return err
  636. }
  637. return sess.Commit()
  638. }
  639. func countUsers(e Engine) int64 {
  640. count, _ := e.
  641. Where("type=0").
  642. Count(new(User))
  643. return count
  644. }
  645. // CountUsers returns number of users.
  646. func CountUsers() int64 {
  647. return countUsers(x)
  648. }
  649. // get user by verify code
  650. func getVerifyUser(code string) (user *User) {
  651. if len(code) <= base.TimeLimitCodeLength {
  652. return nil
  653. }
  654. // use tail hex username query user
  655. hexStr := code[base.TimeLimitCodeLength:]
  656. if b, err := hex.DecodeString(hexStr); err == nil {
  657. if user, err = GetUserByName(string(b)); user != nil {
  658. return user
  659. }
  660. log.Error(4, "user.getVerifyUser: %v", err)
  661. }
  662. return nil
  663. }
  664. // VerifyUserActiveCode verifies active code when active account
  665. func VerifyUserActiveCode(code string) (user *User) {
  666. minutes := setting.Service.ActiveCodeLives
  667. if user = getVerifyUser(code); user != nil {
  668. // time limit code
  669. prefix := code[:base.TimeLimitCodeLength]
  670. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  671. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  672. return user
  673. }
  674. }
  675. return nil
  676. }
  677. // VerifyActiveEmailCode verifies active email code when active account
  678. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  679. minutes := setting.Service.ActiveCodeLives
  680. if user := getVerifyUser(code); user != nil {
  681. // time limit code
  682. prefix := code[:base.TimeLimitCodeLength]
  683. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  684. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  685. emailAddress := &EmailAddress{Email: email}
  686. if has, _ := x.Get(emailAddress); has {
  687. return emailAddress
  688. }
  689. }
  690. }
  691. return nil
  692. }
  693. // ChangeUserName changes all corresponding setting from old user name to new one.
  694. func ChangeUserName(u *User, newUserName string) (err error) {
  695. if err = IsUsableUsername(newUserName); err != nil {
  696. return err
  697. }
  698. isExist, err := IsUserExist(0, newUserName)
  699. if err != nil {
  700. return err
  701. } else if isExist {
  702. return ErrUserAlreadyExist{newUserName}
  703. }
  704. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  705. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  706. }
  707. // Delete all local copies of repository wiki that user owns.
  708. if err = x.BufferSize(setting.IterateBufferSize).
  709. Where("owner_id=?", u.ID).
  710. Iterate(new(Repository), func(idx int, bean interface{}) error {
  711. repo := bean.(*Repository)
  712. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  713. return nil
  714. }); err != nil {
  715. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  716. }
  717. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  718. }
  719. // checkDupEmail checks whether there are the same email with the user
  720. func checkDupEmail(e Engine, u *User) error {
  721. u.Email = strings.ToLower(u.Email)
  722. has, err := e.
  723. Where("id!=?", u.ID).
  724. And("type=?", u.Type).
  725. And("email=?", u.Email).
  726. Get(new(User))
  727. if err != nil {
  728. return err
  729. } else if has {
  730. return ErrEmailAlreadyUsed{u.Email}
  731. }
  732. return nil
  733. }
  734. func updateUser(e Engine, u *User) error {
  735. _, err := e.ID(u.ID).AllCols().Update(u)
  736. return err
  737. }
  738. // UpdateUser updates user's information.
  739. func UpdateUser(u *User) error {
  740. return updateUser(x, u)
  741. }
  742. // UpdateUserCols update user according special columns
  743. func UpdateUserCols(u *User, cols ...string) error {
  744. return updateUserCols(x, u, cols...)
  745. }
  746. func updateUserCols(e Engine, u *User, cols ...string) error {
  747. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  748. return err
  749. }
  750. // UpdateUserSetting updates user's settings.
  751. func UpdateUserSetting(u *User) error {
  752. if !u.IsOrganization() {
  753. if err := checkDupEmail(x, u); err != nil {
  754. return err
  755. }
  756. }
  757. return updateUser(x, u)
  758. }
  759. // deleteBeans deletes all given beans, beans should contain delete conditions.
  760. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  761. for i := range beans {
  762. if _, err = e.Delete(beans[i]); err != nil {
  763. return err
  764. }
  765. }
  766. return nil
  767. }
  768. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  769. func deleteUser(e *xorm.Session, u *User) error {
  770. // Note: A user owns any repository or belongs to any organization
  771. // cannot perform delete operation.
  772. // Check ownership of repository.
  773. count, err := getRepositoryCount(e, u)
  774. if err != nil {
  775. return fmt.Errorf("GetRepositoryCount: %v", err)
  776. } else if count > 0 {
  777. return ErrUserOwnRepos{UID: u.ID}
  778. }
  779. // Check membership of organization.
  780. count, err = u.getOrganizationCount(e)
  781. if err != nil {
  782. return fmt.Errorf("GetOrganizationCount: %v", err)
  783. } else if count > 0 {
  784. return ErrUserHasOrgs{UID: u.ID}
  785. }
  786. // ***** START: Watch *****
  787. watchedRepoIDs := make([]int64, 0, 10)
  788. if err = e.Table("watch").Cols("watch.repo_id").
  789. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  790. return fmt.Errorf("get all watches: %v", err)
  791. }
  792. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).Update(new(Repository)); err != nil {
  793. return fmt.Errorf("decrease repository num_watches: %v", err)
  794. }
  795. // ***** END: Watch *****
  796. // ***** START: Star *****
  797. starredRepoIDs := make([]int64, 0, 10)
  798. if err = e.Table("star").Cols("star.repo_id").
  799. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  800. return fmt.Errorf("get all stars: %v", err)
  801. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).Update(new(Repository)); err != nil {
  802. return fmt.Errorf("decrease repository num_stars: %v", err)
  803. }
  804. // ***** END: Star *****
  805. // ***** START: Follow *****
  806. followeeIDs := make([]int64, 0, 10)
  807. if err = e.Table("follow").Cols("follow.follow_id").
  808. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  809. return fmt.Errorf("get all followees: %v", err)
  810. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  811. return fmt.Errorf("decrease user num_followers: %v", err)
  812. }
  813. followerIDs := make([]int64, 0, 10)
  814. if err = e.Table("follow").Cols("follow.user_id").
  815. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  816. return fmt.Errorf("get all followers: %v", err)
  817. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  818. return fmt.Errorf("decrease user num_following: %v", err)
  819. }
  820. // ***** END: Follow *****
  821. if err = deleteBeans(e,
  822. &AccessToken{UID: u.ID},
  823. &Collaboration{UserID: u.ID},
  824. &Access{UserID: u.ID},
  825. &Watch{UserID: u.ID},
  826. &Star{UID: u.ID},
  827. &Follow{UserID: u.ID},
  828. &Follow{FollowID: u.ID},
  829. &Action{UserID: u.ID},
  830. &IssueUser{UID: u.ID},
  831. &EmailAddress{UID: u.ID},
  832. &UserOpenID{UID: u.ID},
  833. &Reaction{UserID: u.ID},
  834. ); err != nil {
  835. return fmt.Errorf("deleteBeans: %v", err)
  836. }
  837. // ***** START: PublicKey *****
  838. keys := make([]*PublicKey, 0, 10)
  839. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  840. return fmt.Errorf("get all public keys: %v", err)
  841. }
  842. keyIDs := make([]int64, len(keys))
  843. for i := range keys {
  844. keyIDs[i] = keys[i].ID
  845. }
  846. if err = deletePublicKeys(e, keyIDs...); err != nil {
  847. return fmt.Errorf("deletePublicKeys: %v", err)
  848. }
  849. // ***** END: PublicKey *****
  850. // Clear assignee.
  851. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  852. return fmt.Errorf("clear assignee: %v", err)
  853. }
  854. // ***** START: ExternalLoginUser *****
  855. if err = removeAllAccountLinks(e, u); err != nil {
  856. return fmt.Errorf("ExternalLoginUser: %v", err)
  857. }
  858. // ***** END: ExternalLoginUser *****
  859. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  860. return fmt.Errorf("Delete: %v", err)
  861. }
  862. // FIXME: system notice
  863. // Note: There are something just cannot be roll back,
  864. // so just keep error logs of those operations.
  865. path := UserPath(u.Name)
  866. if err := os.RemoveAll(path); err != nil {
  867. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  868. }
  869. if len(u.Avatar) > 0 {
  870. avatarPath := u.CustomAvatarPath()
  871. if com.IsExist(avatarPath) {
  872. if err := os.Remove(avatarPath); err != nil {
  873. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  874. }
  875. }
  876. }
  877. return nil
  878. }
  879. // DeleteUser completely and permanently deletes everything of a user,
  880. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  881. func DeleteUser(u *User) (err error) {
  882. sess := x.NewSession()
  883. defer sess.Close()
  884. if err = sess.Begin(); err != nil {
  885. return err
  886. }
  887. if err = deleteUser(sess, u); err != nil {
  888. // Note: don't wrapper error here.
  889. return err
  890. }
  891. if err = sess.Commit(); err != nil {
  892. return err
  893. }
  894. return RewriteAllPublicKeys()
  895. }
  896. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  897. func DeleteInactivateUsers() (err error) {
  898. users := make([]*User, 0, 10)
  899. if err = x.
  900. Where("is_active = ?", false).
  901. Find(&users); err != nil {
  902. return fmt.Errorf("get all inactive users: %v", err)
  903. }
  904. // FIXME: should only update authorized_keys file once after all deletions.
  905. for _, u := range users {
  906. if err = DeleteUser(u); err != nil {
  907. // Ignore users that were set inactive by admin.
  908. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  909. continue
  910. }
  911. return err
  912. }
  913. }
  914. _, err = x.
  915. Where("is_activated = ?", false).
  916. Delete(new(EmailAddress))
  917. return err
  918. }
  919. // UserPath returns the path absolute path of user repositories.
  920. func UserPath(userName string) string {
  921. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  922. }
  923. // GetUserByKeyID get user information by user's public key id
  924. func GetUserByKeyID(keyID int64) (*User, error) {
  925. var user User
  926. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  927. Where("`public_key`.id=?", keyID).
  928. Get(&user)
  929. if err != nil {
  930. return nil, err
  931. }
  932. if !has {
  933. return nil, ErrUserNotExist{0, "", keyID}
  934. }
  935. return &user, nil
  936. }
  937. func getUserByID(e Engine, id int64) (*User, error) {
  938. u := new(User)
  939. has, err := e.ID(id).Get(u)
  940. if err != nil {
  941. return nil, err
  942. } else if !has {
  943. return nil, ErrUserNotExist{id, "", 0}
  944. }
  945. return u, nil
  946. }
  947. // GetUserByID returns the user object by given ID if exists.
  948. func GetUserByID(id int64) (*User, error) {
  949. return getUserByID(x, id)
  950. }
  951. // GetAssigneeByID returns the user with write access of repository by given ID.
  952. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  953. has, err := HasAccess(userID, repo, AccessModeWrite)
  954. if err != nil {
  955. return nil, err
  956. } else if !has {
  957. return nil, ErrUserNotExist{userID, "", 0}
  958. }
  959. return GetUserByID(userID)
  960. }
  961. // GetUserByName returns user by given name.
  962. func GetUserByName(name string) (*User, error) {
  963. return getUserByName(x, name)
  964. }
  965. func getUserByName(e Engine, name string) (*User, error) {
  966. if len(name) == 0 {
  967. return nil, ErrUserNotExist{0, name, 0}
  968. }
  969. u := &User{LowerName: strings.ToLower(name)}
  970. has, err := e.Get(u)
  971. if err != nil {
  972. return nil, err
  973. } else if !has {
  974. return nil, ErrUserNotExist{0, name, 0}
  975. }
  976. return u, nil
  977. }
  978. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  979. func GetUserEmailsByNames(names []string) []string {
  980. return getUserEmailsByNames(x, names)
  981. }
  982. func getUserEmailsByNames(e Engine, names []string) []string {
  983. mails := make([]string, 0, len(names))
  984. for _, name := range names {
  985. u, err := getUserByName(e, name)
  986. if err != nil {
  987. continue
  988. }
  989. if u.IsMailable() {
  990. mails = append(mails, u.Email)
  991. }
  992. }
  993. return mails
  994. }
  995. // GetUsersByIDs returns all resolved users from a list of Ids.
  996. func GetUsersByIDs(ids []int64) ([]*User, error) {
  997. ous := make([]*User, 0, len(ids))
  998. if len(ids) == 0 {
  999. return ous, nil
  1000. }
  1001. err := x.In("id", ids).
  1002. Asc("name").
  1003. Find(&ous)
  1004. return ous, err
  1005. }
  1006. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1007. func GetUserIDsByNames(names []string) []int64 {
  1008. ids := make([]int64, 0, len(names))
  1009. for _, name := range names {
  1010. u, err := GetUserByName(name)
  1011. if err != nil {
  1012. continue
  1013. }
  1014. ids = append(ids, u.ID)
  1015. }
  1016. return ids
  1017. }
  1018. // UserCommit represents a commit with validation of user.
  1019. type UserCommit struct {
  1020. User *User
  1021. *git.Commit
  1022. }
  1023. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1024. func ValidateCommitWithEmail(c *git.Commit) *User {
  1025. if c.Author == nil {
  1026. return nil
  1027. }
  1028. u, err := GetUserByEmail(c.Author.Email)
  1029. if err != nil {
  1030. return nil
  1031. }
  1032. return u
  1033. }
  1034. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1035. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1036. var (
  1037. u *User
  1038. emails = map[string]*User{}
  1039. newCommits = list.New()
  1040. e = oldCommits.Front()
  1041. )
  1042. for e != nil {
  1043. c := e.Value.(*git.Commit)
  1044. if c.Author != nil {
  1045. if v, ok := emails[c.Author.Email]; !ok {
  1046. u, _ = GetUserByEmail(c.Author.Email)
  1047. emails[c.Author.Email] = u
  1048. } else {
  1049. u = v
  1050. }
  1051. } else {
  1052. u = nil
  1053. }
  1054. newCommits.PushBack(UserCommit{
  1055. User: u,
  1056. Commit: c,
  1057. })
  1058. e = e.Next()
  1059. }
  1060. return newCommits
  1061. }
  1062. // GetUserByEmail returns the user object by given e-mail if exists.
  1063. func GetUserByEmail(email string) (*User, error) {
  1064. if len(email) == 0 {
  1065. return nil, ErrUserNotExist{0, email, 0}
  1066. }
  1067. email = strings.ToLower(email)
  1068. // First try to find the user by primary email
  1069. user := &User{Email: email}
  1070. has, err := x.Get(user)
  1071. if err != nil {
  1072. return nil, err
  1073. }
  1074. if has {
  1075. return user, nil
  1076. }
  1077. // Otherwise, check in alternative list for activated email addresses
  1078. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1079. has, err = x.Get(emailAddress)
  1080. if err != nil {
  1081. return nil, err
  1082. }
  1083. if has {
  1084. return GetUserByID(emailAddress.UID)
  1085. }
  1086. return nil, ErrUserNotExist{0, email, 0}
  1087. }
  1088. // GetUser checks if a user already exists
  1089. func GetUser(user *User) (bool, error) {
  1090. return x.Get(user)
  1091. }
  1092. // SearchUserOptions contains the options for searching
  1093. type SearchUserOptions struct {
  1094. Keyword string
  1095. Type UserType
  1096. OrderBy string
  1097. Page int
  1098. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1099. IsActive util.OptionalBool
  1100. SearchByEmail bool // Search by email as well as username/full name
  1101. }
  1102. func (opts *SearchUserOptions) toConds() builder.Cond {
  1103. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1104. if len(opts.Keyword) > 0 {
  1105. lowerKeyword := strings.ToLower(opts.Keyword)
  1106. keywordCond := builder.Or(
  1107. builder.Like{"lower_name", lowerKeyword},
  1108. builder.Like{"LOWER(full_name)", lowerKeyword},
  1109. )
  1110. if opts.SearchByEmail {
  1111. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1112. }
  1113. cond = cond.And(keywordCond)
  1114. }
  1115. if !opts.IsActive.IsNone() {
  1116. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1117. }
  1118. return cond
  1119. }
  1120. // SearchUsers takes options i.e. keyword and part of user name to search,
  1121. // it returns results in given range and number of total results.
  1122. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1123. cond := opts.toConds()
  1124. count, err := x.Where(cond).Count(new(User))
  1125. if err != nil {
  1126. return nil, 0, fmt.Errorf("Count: %v", err)
  1127. }
  1128. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1129. opts.PageSize = setting.UI.ExplorePagingNum
  1130. }
  1131. if opts.Page <= 0 {
  1132. opts.Page = 1
  1133. }
  1134. if len(opts.OrderBy) == 0 {
  1135. opts.OrderBy = "name ASC"
  1136. }
  1137. users = make([]*User, 0, opts.PageSize)
  1138. return users, count, x.Where(cond).
  1139. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  1140. OrderBy(opts.OrderBy).
  1141. Find(&users)
  1142. }
  1143. // GetStarredRepos returns the repos starred by a particular user
  1144. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1145. sess := x.Where("star.uid=?", userID).
  1146. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1147. if !private {
  1148. sess = sess.And("is_private=?", false)
  1149. }
  1150. repos := make([]*Repository, 0, 10)
  1151. err := sess.Find(&repos)
  1152. if err != nil {
  1153. return nil, err
  1154. }
  1155. return repos, nil
  1156. }
  1157. // GetWatchedRepos returns the repos watched by a particular user
  1158. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1159. sess := x.Where("watch.user_id=?", userID).
  1160. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1161. if !private {
  1162. sess = sess.And("is_private=?", false)
  1163. }
  1164. repos := make([]*Repository, 0, 10)
  1165. err := sess.Find(&repos)
  1166. if err != nil {
  1167. return nil, err
  1168. }
  1169. return repos, nil
  1170. }
  1171. // SyncExternalUsers is used to synchronize users with external authorization source
  1172. func SyncExternalUsers() {
  1173. if !taskStatusTable.StartIfNotRunning(syncExternalUsers) {
  1174. return
  1175. }
  1176. defer taskStatusTable.Stop(syncExternalUsers)
  1177. log.Trace("Doing: SyncExternalUsers")
  1178. ls, err := LoginSources()
  1179. if err != nil {
  1180. log.Error(4, "SyncExternalUsers: %v", err)
  1181. return
  1182. }
  1183. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1184. for _, s := range ls {
  1185. if !s.IsActived || !s.IsSyncEnabled {
  1186. continue
  1187. }
  1188. if s.IsLDAP() {
  1189. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1190. var existingUsers []int64
  1191. // Find all users with this login type
  1192. var users []User
  1193. x.Where("login_type = ?", LoginLDAP).
  1194. And("login_source = ?", s.ID).
  1195. Find(&users)
  1196. sr := s.LDAP().SearchEntries()
  1197. for _, su := range sr {
  1198. if len(su.Username) == 0 {
  1199. continue
  1200. }
  1201. if len(su.Mail) == 0 {
  1202. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1203. }
  1204. var usr *User
  1205. // Search for existing user
  1206. for _, du := range users {
  1207. if du.LowerName == strings.ToLower(su.Username) {
  1208. usr = &du
  1209. break
  1210. }
  1211. }
  1212. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1213. // If no existing user found, create one
  1214. if usr == nil {
  1215. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1216. usr = &User{
  1217. LowerName: strings.ToLower(su.Username),
  1218. Name: su.Username,
  1219. FullName: fullName,
  1220. LoginType: s.Type,
  1221. LoginSource: s.ID,
  1222. LoginName: su.Username,
  1223. Email: su.Mail,
  1224. IsAdmin: su.IsAdmin,
  1225. IsActive: true,
  1226. }
  1227. err = CreateUser(usr)
  1228. if err != nil {
  1229. log.Error(4, "SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1230. }
  1231. } else if updateExisting {
  1232. existingUsers = append(existingUsers, usr.ID)
  1233. // Check if user data has changed
  1234. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1235. strings.ToLower(usr.Email) != strings.ToLower(su.Mail) ||
  1236. usr.FullName != fullName ||
  1237. !usr.IsActive {
  1238. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1239. usr.FullName = fullName
  1240. usr.Email = su.Mail
  1241. // Change existing admin flag only if AdminFilter option is set
  1242. if len(s.LDAP().AdminFilter) > 0 {
  1243. usr.IsAdmin = su.IsAdmin
  1244. }
  1245. usr.IsActive = true
  1246. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1247. if err != nil {
  1248. log.Error(4, "SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1249. }
  1250. }
  1251. }
  1252. }
  1253. // Deactivate users not present in LDAP
  1254. if updateExisting {
  1255. for _, usr := range users {
  1256. found := false
  1257. for _, uid := range existingUsers {
  1258. if usr.ID == uid {
  1259. found = true
  1260. break
  1261. }
  1262. }
  1263. if !found {
  1264. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1265. usr.IsActive = false
  1266. err = UpdateUserCols(&usr, "is_active")
  1267. if err != nil {
  1268. log.Error(4, "SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. }
  1275. }