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

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