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

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