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

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