Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

user.go 40KB

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