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

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