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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  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. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  854. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  855. }
  856. // Do not fail if directory does not exist
  857. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  858. return fmt.Errorf("Rename user directory: %v", err)
  859. }
  860. return nil
  861. }
  862. // checkDupEmail checks whether there are the same email with the user
  863. func checkDupEmail(e Engine, u *User) error {
  864. u.Email = strings.ToLower(u.Email)
  865. has, err := e.
  866. Where("id!=?", u.ID).
  867. And("type=?", u.Type).
  868. And("email=?", u.Email).
  869. Get(new(User))
  870. if err != nil {
  871. return err
  872. } else if has {
  873. return ErrEmailAlreadyUsed{u.Email}
  874. }
  875. return nil
  876. }
  877. func updateUser(e Engine, u *User) error {
  878. _, err := e.ID(u.ID).AllCols().Update(u)
  879. return err
  880. }
  881. // UpdateUser updates user's information.
  882. func UpdateUser(u *User) error {
  883. return updateUser(x, u)
  884. }
  885. // UpdateUserCols update user according special columns
  886. func UpdateUserCols(u *User, cols ...string) error {
  887. return updateUserCols(x, u, cols...)
  888. }
  889. func updateUserCols(e Engine, u *User, cols ...string) error {
  890. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  891. return err
  892. }
  893. // UpdateUserSetting updates user's settings.
  894. func UpdateUserSetting(u *User) error {
  895. if !u.IsOrganization() {
  896. if err := checkDupEmail(x, u); err != nil {
  897. return err
  898. }
  899. }
  900. return updateUser(x, u)
  901. }
  902. // deleteBeans deletes all given beans, beans should contain delete conditions.
  903. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  904. for i := range beans {
  905. if _, err = e.Delete(beans[i]); err != nil {
  906. return err
  907. }
  908. }
  909. return nil
  910. }
  911. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  912. func deleteUser(e *xorm.Session, u *User) error {
  913. // Note: A user owns any repository or belongs to any organization
  914. // cannot perform delete operation.
  915. // Check ownership of repository.
  916. count, err := getRepositoryCount(e, u)
  917. if err != nil {
  918. return fmt.Errorf("GetRepositoryCount: %v", err)
  919. } else if count > 0 {
  920. return ErrUserOwnRepos{UID: u.ID}
  921. }
  922. // Check membership of organization.
  923. count, err = u.getOrganizationCount(e)
  924. if err != nil {
  925. return fmt.Errorf("GetOrganizationCount: %v", err)
  926. } else if count > 0 {
  927. return ErrUserHasOrgs{UID: u.ID}
  928. }
  929. // ***** START: Watch *****
  930. watchedRepoIDs := make([]int64, 0, 10)
  931. if err = e.Table("watch").Cols("watch.repo_id").
  932. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  933. return fmt.Errorf("get all watches: %v", err)
  934. }
  935. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  936. return fmt.Errorf("decrease repository num_watches: %v", err)
  937. }
  938. // ***** END: Watch *****
  939. // ***** START: Star *****
  940. starredRepoIDs := make([]int64, 0, 10)
  941. if err = e.Table("star").Cols("star.repo_id").
  942. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  943. return fmt.Errorf("get all stars: %v", err)
  944. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  945. return fmt.Errorf("decrease repository num_stars: %v", err)
  946. }
  947. // ***** END: Star *****
  948. // ***** START: Follow *****
  949. followeeIDs := make([]int64, 0, 10)
  950. if err = e.Table("follow").Cols("follow.follow_id").
  951. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  952. return fmt.Errorf("get all followees: %v", err)
  953. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  954. return fmt.Errorf("decrease user num_followers: %v", err)
  955. }
  956. followerIDs := make([]int64, 0, 10)
  957. if err = e.Table("follow").Cols("follow.user_id").
  958. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  959. return fmt.Errorf("get all followers: %v", err)
  960. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  961. return fmt.Errorf("decrease user num_following: %v", err)
  962. }
  963. // ***** END: Follow *****
  964. if err = deleteBeans(e,
  965. &AccessToken{UID: u.ID},
  966. &Collaboration{UserID: u.ID},
  967. &Access{UserID: u.ID},
  968. &Watch{UserID: u.ID},
  969. &Star{UID: u.ID},
  970. &Follow{UserID: u.ID},
  971. &Follow{FollowID: u.ID},
  972. &Action{UserID: u.ID},
  973. &IssueUser{UID: u.ID},
  974. &EmailAddress{UID: u.ID},
  975. &UserOpenID{UID: u.ID},
  976. &Reaction{UserID: u.ID},
  977. &TeamUser{UID: u.ID},
  978. &Collaboration{UserID: u.ID},
  979. &Stopwatch{UserID: u.ID},
  980. ); err != nil {
  981. return fmt.Errorf("deleteBeans: %v", err)
  982. }
  983. // ***** START: PublicKey *****
  984. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  985. return fmt.Errorf("deletePublicKeys: %v", err)
  986. }
  987. err = rewriteAllPublicKeys(e)
  988. if err != nil {
  989. return err
  990. }
  991. // ***** END: PublicKey *****
  992. // ***** START: GPGPublicKey *****
  993. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  994. return fmt.Errorf("deleteGPGKeys: %v", err)
  995. }
  996. // ***** END: GPGPublicKey *****
  997. // Clear assignee.
  998. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  999. return fmt.Errorf("clear assignee: %v", err)
  1000. }
  1001. // ***** START: ExternalLoginUser *****
  1002. if err = removeAllAccountLinks(e, u); err != nil {
  1003. return fmt.Errorf("ExternalLoginUser: %v", err)
  1004. }
  1005. // ***** END: ExternalLoginUser *****
  1006. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  1007. return fmt.Errorf("Delete: %v", err)
  1008. }
  1009. // FIXME: system notice
  1010. // Note: There are something just cannot be roll back,
  1011. // so just keep error logs of those operations.
  1012. path := UserPath(u.Name)
  1013. if err := os.RemoveAll(path); err != nil {
  1014. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  1015. }
  1016. if len(u.Avatar) > 0 {
  1017. avatarPath := u.CustomAvatarPath()
  1018. if com.IsExist(avatarPath) {
  1019. if err := os.Remove(avatarPath); err != nil {
  1020. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1021. }
  1022. }
  1023. }
  1024. return nil
  1025. }
  1026. // DeleteUser completely and permanently deletes everything of a user,
  1027. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  1028. func DeleteUser(u *User) (err error) {
  1029. sess := x.NewSession()
  1030. defer sess.Close()
  1031. if err = sess.Begin(); err != nil {
  1032. return err
  1033. }
  1034. if err = deleteUser(sess, u); err != nil {
  1035. // Note: don't wrapper error here.
  1036. return err
  1037. }
  1038. return sess.Commit()
  1039. }
  1040. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  1041. func DeleteInactivateUsers() (err error) {
  1042. users := make([]*User, 0, 10)
  1043. if err = x.
  1044. Where("is_active = ?", false).
  1045. Find(&users); err != nil {
  1046. return fmt.Errorf("get all inactive users: %v", err)
  1047. }
  1048. // FIXME: should only update authorized_keys file once after all deletions.
  1049. for _, u := range users {
  1050. if err = DeleteUser(u); err != nil {
  1051. // Ignore users that were set inactive by admin.
  1052. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1053. continue
  1054. }
  1055. return err
  1056. }
  1057. }
  1058. _, err = x.
  1059. Where("is_activated = ?", false).
  1060. Delete(new(EmailAddress))
  1061. return err
  1062. }
  1063. // UserPath returns the path absolute path of user repositories.
  1064. func UserPath(userName string) string {
  1065. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1066. }
  1067. // GetUserByKeyID get user information by user's public key id
  1068. func GetUserByKeyID(keyID int64) (*User, error) {
  1069. var user User
  1070. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  1071. Where("`public_key`.id=?", keyID).
  1072. Get(&user)
  1073. if err != nil {
  1074. return nil, err
  1075. }
  1076. if !has {
  1077. return nil, ErrUserNotExist{0, "", keyID}
  1078. }
  1079. return &user, nil
  1080. }
  1081. func getUserByID(e Engine, id int64) (*User, error) {
  1082. u := new(User)
  1083. has, err := e.ID(id).Get(u)
  1084. if err != nil {
  1085. return nil, err
  1086. } else if !has {
  1087. return nil, ErrUserNotExist{id, "", 0}
  1088. }
  1089. return u, nil
  1090. }
  1091. // GetUserByID returns the user object by given ID if exists.
  1092. func GetUserByID(id int64) (*User, error) {
  1093. return getUserByID(x, id)
  1094. }
  1095. // GetUserByName returns user by given name.
  1096. func GetUserByName(name string) (*User, error) {
  1097. return getUserByName(x, name)
  1098. }
  1099. func getUserByName(e Engine, name string) (*User, error) {
  1100. if len(name) == 0 {
  1101. return nil, ErrUserNotExist{0, name, 0}
  1102. }
  1103. u := &User{LowerName: strings.ToLower(name)}
  1104. has, err := e.Get(u)
  1105. if err != nil {
  1106. return nil, err
  1107. } else if !has {
  1108. return nil, ErrUserNotExist{0, name, 0}
  1109. }
  1110. return u, nil
  1111. }
  1112. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1113. // that have their email notifications set to enabled or onmention.
  1114. func GetUserEmailsByNames(names []string) []string {
  1115. return getUserEmailsByNames(x, names)
  1116. }
  1117. func getUserEmailsByNames(e Engine, names []string) []string {
  1118. mails := make([]string, 0, len(names))
  1119. for _, name := range names {
  1120. u, err := getUserByName(e, name)
  1121. if err != nil {
  1122. continue
  1123. }
  1124. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1125. mails = append(mails, u.Email)
  1126. }
  1127. }
  1128. return mails
  1129. }
  1130. // GetUsersByIDs returns all resolved users from a list of Ids.
  1131. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1132. ous := make([]*User, 0, len(ids))
  1133. if len(ids) == 0 {
  1134. return ous, nil
  1135. }
  1136. err := x.In("id", ids).
  1137. Asc("name").
  1138. Find(&ous)
  1139. return ous, err
  1140. }
  1141. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1142. func GetUserIDsByNames(names []string) []int64 {
  1143. ids := make([]int64, 0, len(names))
  1144. for _, name := range names {
  1145. u, err := GetUserByName(name)
  1146. if err != nil {
  1147. continue
  1148. }
  1149. ids = append(ids, u.ID)
  1150. }
  1151. return ids
  1152. }
  1153. // UserCommit represents a commit with validation of user.
  1154. type UserCommit struct {
  1155. User *User
  1156. *git.Commit
  1157. }
  1158. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1159. func ValidateCommitWithEmail(c *git.Commit) *User {
  1160. if c.Author == nil {
  1161. return nil
  1162. }
  1163. u, err := GetUserByEmail(c.Author.Email)
  1164. if err != nil {
  1165. return nil
  1166. }
  1167. return u
  1168. }
  1169. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1170. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1171. var (
  1172. u *User
  1173. emails = map[string]*User{}
  1174. newCommits = list.New()
  1175. e = oldCommits.Front()
  1176. )
  1177. for e != nil {
  1178. c := e.Value.(*git.Commit)
  1179. if c.Author != nil {
  1180. if v, ok := emails[c.Author.Email]; !ok {
  1181. u, _ = GetUserByEmail(c.Author.Email)
  1182. emails[c.Author.Email] = u
  1183. } else {
  1184. u = v
  1185. }
  1186. } else {
  1187. u = nil
  1188. }
  1189. newCommits.PushBack(UserCommit{
  1190. User: u,
  1191. Commit: c,
  1192. })
  1193. e = e.Next()
  1194. }
  1195. return newCommits
  1196. }
  1197. // GetUserByEmail returns the user object by given e-mail if exists.
  1198. func GetUserByEmail(email string) (*User, error) {
  1199. if len(email) == 0 {
  1200. return nil, ErrUserNotExist{0, email, 0}
  1201. }
  1202. email = strings.ToLower(email)
  1203. // First try to find the user by primary email
  1204. user := &User{Email: email}
  1205. has, err := x.Get(user)
  1206. if err != nil {
  1207. return nil, err
  1208. }
  1209. if has {
  1210. return user, nil
  1211. }
  1212. // Otherwise, check in alternative list for activated email addresses
  1213. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1214. has, err = x.Get(emailAddress)
  1215. if err != nil {
  1216. return nil, err
  1217. }
  1218. if has {
  1219. return GetUserByID(emailAddress.UID)
  1220. }
  1221. // Finally, if email address is the protected email address:
  1222. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1223. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1224. user := &User{LowerName: username}
  1225. has, err := x.Get(user)
  1226. if err != nil {
  1227. return nil, err
  1228. }
  1229. if has {
  1230. return user, nil
  1231. }
  1232. }
  1233. return nil, ErrUserNotExist{0, email, 0}
  1234. }
  1235. // GetUser checks if a user already exists
  1236. func GetUser(user *User) (bool, error) {
  1237. return x.Get(user)
  1238. }
  1239. // SearchUserOptions contains the options for searching
  1240. type SearchUserOptions struct {
  1241. Keyword string
  1242. Type UserType
  1243. UID int64
  1244. OrderBy SearchOrderBy
  1245. Page int
  1246. Private bool // Include private orgs in search
  1247. OwnerID int64 // id of user for visibility calculation
  1248. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1249. IsActive util.OptionalBool
  1250. SearchByEmail bool // Search by email as well as username/full name
  1251. }
  1252. func (opts *SearchUserOptions) toConds() builder.Cond {
  1253. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1254. if len(opts.Keyword) > 0 {
  1255. lowerKeyword := strings.ToLower(opts.Keyword)
  1256. keywordCond := builder.Or(
  1257. builder.Like{"lower_name", lowerKeyword},
  1258. builder.Like{"LOWER(full_name)", lowerKeyword},
  1259. )
  1260. if opts.SearchByEmail {
  1261. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1262. }
  1263. cond = cond.And(keywordCond)
  1264. }
  1265. if !opts.Private {
  1266. // user not logged in and so they won't be allowed to see non-public orgs
  1267. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1268. }
  1269. if opts.OwnerID > 0 {
  1270. var exprCond builder.Cond
  1271. if setting.Database.UseMySQL {
  1272. exprCond = builder.Expr("org_user.org_id = user.id")
  1273. } else if setting.Database.UseMSSQL {
  1274. exprCond = builder.Expr("org_user.org_id = [user].id")
  1275. } else {
  1276. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1277. }
  1278. accessCond := builder.Or(
  1279. 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}))),
  1280. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1281. cond = cond.And(accessCond)
  1282. }
  1283. if opts.UID > 0 {
  1284. cond = cond.And(builder.Eq{"id": opts.UID})
  1285. }
  1286. if !opts.IsActive.IsNone() {
  1287. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1288. }
  1289. return cond
  1290. }
  1291. // SearchUsers takes options i.e. keyword and part of user name to search,
  1292. // it returns results in given range and number of total results.
  1293. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1294. cond := opts.toConds()
  1295. count, err := x.Where(cond).Count(new(User))
  1296. if err != nil {
  1297. return nil, 0, fmt.Errorf("Count: %v", err)
  1298. }
  1299. if opts.PageSize == 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1300. opts.PageSize = setting.UI.ExplorePagingNum
  1301. }
  1302. if opts.Page <= 0 {
  1303. opts.Page = 1
  1304. }
  1305. if len(opts.OrderBy) == 0 {
  1306. opts.OrderBy = SearchOrderByAlphabetically
  1307. }
  1308. sess := x.Where(cond)
  1309. if opts.PageSize > 0 {
  1310. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1311. }
  1312. if opts.PageSize == -1 {
  1313. opts.PageSize = int(count)
  1314. }
  1315. users = make([]*User, 0, opts.PageSize)
  1316. return users, count, sess.OrderBy(opts.OrderBy.String()).Find(&users)
  1317. }
  1318. // GetStarredRepos returns the repos starred by a particular user
  1319. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1320. sess := x.Where("star.uid=?", userID).
  1321. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1322. if !private {
  1323. sess = sess.And("is_private=?", false)
  1324. }
  1325. repos := make([]*Repository, 0, 10)
  1326. err := sess.Find(&repos)
  1327. if err != nil {
  1328. return nil, err
  1329. }
  1330. return repos, nil
  1331. }
  1332. // GetWatchedRepos returns the repos watched by a particular user
  1333. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1334. sess := x.Where("watch.user_id=?", userID).
  1335. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1336. if !private {
  1337. sess = sess.And("is_private=?", false)
  1338. }
  1339. repos := make([]*Repository, 0, 10)
  1340. err := sess.Find(&repos)
  1341. if err != nil {
  1342. return nil, err
  1343. }
  1344. return repos, nil
  1345. }
  1346. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1347. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1348. // Start session
  1349. sess := x.NewSession()
  1350. defer sess.Close()
  1351. if err := sess.Begin(); err != nil {
  1352. return false, err
  1353. }
  1354. // Delete keys marked for deletion
  1355. var sshKeysNeedUpdate bool
  1356. for _, KeyToDelete := range keys {
  1357. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1358. if err != nil {
  1359. log.Error("SearchPublicKeyByContent: %v", err)
  1360. continue
  1361. }
  1362. if err = deletePublicKeys(sess, key.ID); err != nil {
  1363. log.Error("deletePublicKeys: %v", err)
  1364. continue
  1365. }
  1366. sshKeysNeedUpdate = true
  1367. }
  1368. if err := sess.Commit(); err != nil {
  1369. return false, err
  1370. }
  1371. return sshKeysNeedUpdate, nil
  1372. }
  1373. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1374. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1375. var sshKeysNeedUpdate bool
  1376. for _, sshKey := range sshPublicKeys {
  1377. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1378. if err == nil {
  1379. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1380. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1381. if IsErrKeyAlreadyExist(err) {
  1382. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1383. } else {
  1384. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1385. }
  1386. } else {
  1387. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1388. sshKeysNeedUpdate = true
  1389. }
  1390. } else {
  1391. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1392. }
  1393. }
  1394. return sshKeysNeedUpdate
  1395. }
  1396. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1397. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1398. var sshKeysNeedUpdate bool
  1399. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1400. // Get Public Keys from DB with current LDAP source
  1401. var giteaKeys []string
  1402. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1403. if err != nil {
  1404. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1405. }
  1406. for _, v := range keys {
  1407. giteaKeys = append(giteaKeys, v.OmitEmail())
  1408. }
  1409. // Get Public Keys from LDAP and skip duplicate keys
  1410. var ldapKeys []string
  1411. for _, v := range sshPublicKeys {
  1412. sshKeySplit := strings.Split(v, " ")
  1413. if len(sshKeySplit) > 1 {
  1414. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1415. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1416. ldapKeys = append(ldapKeys, ldapKey)
  1417. }
  1418. }
  1419. }
  1420. // Check if Public Key sync is needed
  1421. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1422. 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))
  1423. return false
  1424. }
  1425. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1426. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1427. var newLdapSSHKeys []string
  1428. for _, LDAPPublicSSHKey := range ldapKeys {
  1429. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1430. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1431. }
  1432. }
  1433. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1434. sshKeysNeedUpdate = true
  1435. }
  1436. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1437. var giteaKeysToDelete []string
  1438. for _, giteaKey := range giteaKeys {
  1439. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1440. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1441. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1442. }
  1443. }
  1444. // Delete LDAP keys from DB that doesn't exist in LDAP
  1445. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1446. if err != nil {
  1447. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1448. }
  1449. if needUpd {
  1450. sshKeysNeedUpdate = true
  1451. }
  1452. return sshKeysNeedUpdate
  1453. }
  1454. // SyncExternalUsers is used to synchronize users with external authorization source
  1455. func SyncExternalUsers() {
  1456. log.Trace("Doing: SyncExternalUsers")
  1457. ls, err := LoginSources()
  1458. if err != nil {
  1459. log.Error("SyncExternalUsers: %v", err)
  1460. return
  1461. }
  1462. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1463. for _, s := range ls {
  1464. if !s.IsActived || !s.IsSyncEnabled {
  1465. continue
  1466. }
  1467. if s.IsLDAP() {
  1468. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1469. var existingUsers []int64
  1470. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1471. var sshKeysNeedUpdate bool
  1472. // Find all users with this login type
  1473. var users []*User
  1474. err = x.Where("login_type = ?", LoginLDAP).
  1475. And("login_source = ?", s.ID).
  1476. Find(&users)
  1477. if err != nil {
  1478. log.Error("SyncExternalUsers: %v", err)
  1479. return
  1480. }
  1481. sr, err := s.LDAP().SearchEntries()
  1482. if err != nil {
  1483. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1484. continue
  1485. }
  1486. for _, su := range sr {
  1487. if len(su.Username) == 0 {
  1488. continue
  1489. }
  1490. if len(su.Mail) == 0 {
  1491. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1492. }
  1493. var usr *User
  1494. // Search for existing user
  1495. for _, du := range users {
  1496. if du.LowerName == strings.ToLower(su.Username) {
  1497. usr = du
  1498. break
  1499. }
  1500. }
  1501. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1502. // If no existing user found, create one
  1503. if usr == nil {
  1504. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1505. usr = &User{
  1506. LowerName: strings.ToLower(su.Username),
  1507. Name: su.Username,
  1508. FullName: fullName,
  1509. LoginType: s.Type,
  1510. LoginSource: s.ID,
  1511. LoginName: su.Username,
  1512. Email: su.Mail,
  1513. IsAdmin: su.IsAdmin,
  1514. IsActive: true,
  1515. }
  1516. err = CreateUser(usr)
  1517. if err != nil {
  1518. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1519. } else if isAttributeSSHPublicKeySet {
  1520. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1521. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1522. sshKeysNeedUpdate = true
  1523. }
  1524. }
  1525. } else if updateExisting {
  1526. existingUsers = append(existingUsers, usr.ID)
  1527. // Synchronize SSH Public Key if that attribute is set
  1528. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1529. sshKeysNeedUpdate = true
  1530. }
  1531. // Check if user data has changed
  1532. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1533. !strings.EqualFold(usr.Email, su.Mail) ||
  1534. usr.FullName != fullName ||
  1535. !usr.IsActive {
  1536. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1537. usr.FullName = fullName
  1538. usr.Email = su.Mail
  1539. // Change existing admin flag only if AdminFilter option is set
  1540. if len(s.LDAP().AdminFilter) > 0 {
  1541. usr.IsAdmin = su.IsAdmin
  1542. }
  1543. usr.IsActive = true
  1544. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1545. if err != nil {
  1546. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1547. }
  1548. }
  1549. }
  1550. }
  1551. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1552. if sshKeysNeedUpdate {
  1553. err = RewriteAllPublicKeys()
  1554. if err != nil {
  1555. log.Error("RewriteAllPublicKeys: %v", err)
  1556. }
  1557. }
  1558. // Deactivate users not present in LDAP
  1559. if updateExisting {
  1560. for _, usr := range users {
  1561. found := false
  1562. for _, uid := range existingUsers {
  1563. if usr.ID == uid {
  1564. found = true
  1565. break
  1566. }
  1567. }
  1568. if !found {
  1569. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1570. usr.IsActive = false
  1571. err = UpdateUserCols(usr, "is_active")
  1572. if err != nil {
  1573. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1574. }
  1575. }
  1576. }
  1577. }
  1578. }
  1579. }
  1580. }