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

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