You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 45KB

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