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

user.go 48KB

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