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 45KB

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