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

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