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

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