Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

user.go 40KB

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