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

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