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

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