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

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