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

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