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

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