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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "container/list"
  8. "context"
  9. "crypto/md5"
  10. "crypto/sha256"
  11. "crypto/subtle"
  12. "encoding/hex"
  13. "errors"
  14. "fmt"
  15. _ "image/jpeg" // Needed for jpeg support
  16. "image/png"
  17. "os"
  18. "path/filepath"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "unicode/utf8"
  24. "code.gitea.io/gitea/modules/avatar"
  25. "code.gitea.io/gitea/modules/base"
  26. "code.gitea.io/gitea/modules/generate"
  27. "code.gitea.io/gitea/modules/git"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/setting"
  30. "code.gitea.io/gitea/modules/structs"
  31. api "code.gitea.io/gitea/modules/structs"
  32. "code.gitea.io/gitea/modules/timeutil"
  33. "code.gitea.io/gitea/modules/util"
  34. "github.com/unknwon/com"
  35. "golang.org/x/crypto/argon2"
  36. "golang.org/x/crypto/bcrypt"
  37. "golang.org/x/crypto/pbkdf2"
  38. "golang.org/x/crypto/scrypt"
  39. "golang.org/x/crypto/ssh"
  40. "xorm.io/builder"
  41. "xorm.io/xorm"
  42. )
  43. // UserType defines the user type
  44. type UserType int
  45. const (
  46. // UserTypeIndividual defines an individual user
  47. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  48. // UserTypeOrganization defines an organization
  49. UserTypeOrganization
  50. )
  51. const (
  52. algoBcrypt = "bcrypt"
  53. algoScrypt = "scrypt"
  54. algoArgon2 = "argon2"
  55. algoPbkdf2 = "pbkdf2"
  56. // EmailNotificationsEnabled indicates that the user would like to receive all email notifications
  57. EmailNotificationsEnabled = "enabled"
  58. // EmailNotificationsOnMention indicates that the user would like to be notified via email when mentioned.
  59. EmailNotificationsOnMention = "onmention"
  60. // EmailNotificationsDisabled indicates that the user would not like to be notified via email.
  61. EmailNotificationsDisabled = "disabled"
  62. )
  63. var (
  64. // ErrUserNotKeyOwner user does not own this key error
  65. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  66. // ErrEmailNotExist e-mail does not exist error
  67. ErrEmailNotExist = errors.New("E-mail does not exist")
  68. // ErrEmailNotActivated e-mail address has not been activated error
  69. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  70. // ErrUserNameIllegal user name contains illegal characters error
  71. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  72. // ErrLoginSourceNotActived login source is not actived error
  73. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  74. // ErrUnsupportedLoginType login source is unknown error
  75. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  76. // Characters prohibited in a user name (anything except A-Za-z0-9_.-)
  77. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  78. )
  79. // User represents the object of individual and member of organization.
  80. type User struct {
  81. ID int64 `xorm:"pk autoincr"`
  82. LowerName string `xorm:"UNIQUE NOT NULL"`
  83. Name string `xorm:"UNIQUE NOT NULL"`
  84. FullName string
  85. // Email is the primary email address (to be used for communication)
  86. Email string `xorm:"NOT NULL"`
  87. KeepEmailPrivate bool
  88. EmailNotificationsPreference string `xorm:"VARCHAR(20) NOT NULL DEFAULT 'enabled'"`
  89. Passwd string `xorm:"NOT NULL"`
  90. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'pbkdf2'"`
  91. // MustChangePassword is an attribute that determines if a user
  92. // is to change his/her password after registration.
  93. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  94. LoginType LoginType
  95. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  96. LoginName string
  97. Type UserType
  98. OwnedOrgs []*User `xorm:"-"`
  99. Orgs []*User `xorm:"-"`
  100. Repos []*Repository `xorm:"-"`
  101. Location string
  102. Website string
  103. Rands string `xorm:"VARCHAR(10)"`
  104. Salt string `xorm:"VARCHAR(10)"`
  105. Language string `xorm:"VARCHAR(5)"`
  106. Description string
  107. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  108. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  109. LastLoginUnix timeutil.TimeStamp `xorm:"INDEX"`
  110. // Remember visibility choice for convenience, true for private
  111. LastRepoVisibility bool
  112. // Maximum repository creation limit, -1 means use global default
  113. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  114. // Permissions
  115. IsActive bool `xorm:"INDEX"` // Activate primary email
  116. IsAdmin bool
  117. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  118. AllowGitHook bool
  119. AllowImportLocal bool // Allow migrate repository by local path
  120. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  121. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  122. // Avatar
  123. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  124. AvatarEmail string `xorm:"NOT NULL"`
  125. UseCustomAvatar bool
  126. // Counters
  127. NumFollowers int
  128. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  129. NumStars int
  130. NumRepos int
  131. // For organization
  132. NumTeams int
  133. NumMembers int
  134. Teams []*Team `xorm:"-"`
  135. Members UserList `xorm:"-"`
  136. MembersIsPublic map[int64]bool `xorm:"-"`
  137. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  138. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  139. // Preferences
  140. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  141. Theme string `xorm:"NOT NULL DEFAULT ''"`
  142. KeepActivityPrivate bool `xorm:"NOT NULL DEFAULT false"`
  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 = []string{
  752. ".",
  753. "..",
  754. ".well-known",
  755. "admin",
  756. "api",
  757. "assets",
  758. "attachments",
  759. "avatars",
  760. "commits",
  761. "css",
  762. "debug",
  763. "error",
  764. "explore",
  765. "fomantic",
  766. "ghost",
  767. "help",
  768. "img",
  769. "install",
  770. "issues",
  771. "js",
  772. "less",
  773. "login",
  774. "manifest.json",
  775. "metrics",
  776. "milestones",
  777. "new",
  778. "notifications",
  779. "org",
  780. "plugins",
  781. "pulls",
  782. "raw",
  783. "repo",
  784. "robots.txt",
  785. "search",
  786. "stars",
  787. "template",
  788. "user",
  789. "vendor",
  790. }
  791. reservedUserPatterns = []string{"*.keys", "*.gpg"}
  792. )
  793. // isUsableName checks if name is reserved or pattern of name is not allowed
  794. // based on given reserved names and patterns.
  795. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  796. func isUsableName(names, patterns []string, name string) error {
  797. name = strings.TrimSpace(strings.ToLower(name))
  798. if utf8.RuneCountInString(name) == 0 {
  799. return ErrNameEmpty
  800. }
  801. for i := range names {
  802. if name == names[i] {
  803. return ErrNameReserved{name}
  804. }
  805. }
  806. for _, pat := range patterns {
  807. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  808. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  809. return ErrNamePatternNotAllowed{pat}
  810. }
  811. }
  812. return nil
  813. }
  814. // IsUsableUsername returns an error when a username is reserved
  815. func IsUsableUsername(name string) error {
  816. // Validate username make sure it satisfies requirement.
  817. if alphaDashDotPattern.MatchString(name) {
  818. // Note: usually this error is normally caught up earlier in the UI
  819. return ErrNameCharsNotAllowed{Name: name}
  820. }
  821. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  822. }
  823. // CreateUser creates record of a new user.
  824. func CreateUser(u *User) (err error) {
  825. if err = IsUsableUsername(u.Name); err != nil {
  826. return err
  827. }
  828. sess := x.NewSession()
  829. defer sess.Close()
  830. if err = sess.Begin(); err != nil {
  831. return err
  832. }
  833. isExist, err := isUserExist(sess, 0, u.Name)
  834. if err != nil {
  835. return err
  836. } else if isExist {
  837. return ErrUserAlreadyExist{u.Name}
  838. }
  839. u.Email = strings.ToLower(u.Email)
  840. isExist, err = sess.
  841. Where("email=?", u.Email).
  842. Get(new(User))
  843. if err != nil {
  844. return err
  845. } else if isExist {
  846. return ErrEmailAlreadyUsed{u.Email}
  847. }
  848. isExist, err = isEmailUsed(sess, u.Email)
  849. if err != nil {
  850. return err
  851. } else if isExist {
  852. return ErrEmailAlreadyUsed{u.Email}
  853. }
  854. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  855. u.LowerName = strings.ToLower(u.Name)
  856. u.AvatarEmail = u.Email
  857. u.Avatar = base.HashEmail(u.AvatarEmail)
  858. if u.Rands, err = GetUserSalt(); err != nil {
  859. return err
  860. }
  861. if u.Salt, err = GetUserSalt(); err != nil {
  862. return err
  863. }
  864. u.HashPassword(u.Passwd)
  865. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation
  866. u.EmailNotificationsPreference = setting.Admin.DefaultEmailNotification
  867. u.MaxRepoCreation = -1
  868. u.Theme = setting.UI.DefaultTheme
  869. if _, err = sess.Insert(u); err != nil {
  870. return err
  871. }
  872. return sess.Commit()
  873. }
  874. func countUsers(e Engine) int64 {
  875. count, _ := e.
  876. Where("type=0").
  877. Count(new(User))
  878. return count
  879. }
  880. // CountUsers returns number of users.
  881. func CountUsers() int64 {
  882. return countUsers(x)
  883. }
  884. // get user by verify code
  885. func getVerifyUser(code string) (user *User) {
  886. if len(code) <= base.TimeLimitCodeLength {
  887. return nil
  888. }
  889. // use tail hex username query user
  890. hexStr := code[base.TimeLimitCodeLength:]
  891. if b, err := hex.DecodeString(hexStr); err == nil {
  892. if user, err = GetUserByName(string(b)); user != nil {
  893. return user
  894. }
  895. log.Error("user.getVerifyUser: %v", err)
  896. }
  897. return nil
  898. }
  899. // VerifyUserActiveCode verifies active code when active account
  900. func VerifyUserActiveCode(code string) (user *User) {
  901. minutes := setting.Service.ActiveCodeLives
  902. if user = getVerifyUser(code); user != nil {
  903. // time limit code
  904. prefix := code[:base.TimeLimitCodeLength]
  905. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  906. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  907. return user
  908. }
  909. }
  910. return nil
  911. }
  912. // VerifyActiveEmailCode verifies active email code when active account
  913. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  914. minutes := setting.Service.ActiveCodeLives
  915. if user := getVerifyUser(code); user != nil {
  916. // time limit code
  917. prefix := code[:base.TimeLimitCodeLength]
  918. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  919. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  920. emailAddress := &EmailAddress{UID: user.ID, Email: email}
  921. if has, _ := x.Get(emailAddress); has {
  922. return emailAddress
  923. }
  924. }
  925. }
  926. return nil
  927. }
  928. // ChangeUserName changes all corresponding setting from old user name to new one.
  929. func ChangeUserName(u *User, newUserName string) (err error) {
  930. if err = IsUsableUsername(newUserName); err != nil {
  931. return err
  932. }
  933. isExist, err := IsUserExist(0, newUserName)
  934. if err != nil {
  935. return err
  936. } else if isExist {
  937. return ErrUserAlreadyExist{newUserName}
  938. }
  939. sess := x.NewSession()
  940. defer sess.Close()
  941. if err = sess.Begin(); err != nil {
  942. return err
  943. }
  944. if _, err = sess.Exec("UPDATE `repository` SET owner_name=? WHERE owner_name=?", newUserName, u.Name); err != nil {
  945. return fmt.Errorf("Change repo owner name: %v", err)
  946. }
  947. // Do not fail if directory does not exist
  948. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  949. return fmt.Errorf("Rename user directory: %v", err)
  950. }
  951. return sess.Commit()
  952. }
  953. // checkDupEmail checks whether there are the same email with the user
  954. func checkDupEmail(e Engine, u *User) error {
  955. u.Email = strings.ToLower(u.Email)
  956. has, err := e.
  957. Where("id!=?", u.ID).
  958. And("type=?", u.Type).
  959. And("email=?", u.Email).
  960. Get(new(User))
  961. if err != nil {
  962. return err
  963. } else if has {
  964. return ErrEmailAlreadyUsed{u.Email}
  965. }
  966. return nil
  967. }
  968. func updateUser(e Engine, u *User) error {
  969. _, err := e.ID(u.ID).AllCols().Update(u)
  970. return err
  971. }
  972. // UpdateUser updates user's information.
  973. func UpdateUser(u *User) error {
  974. return updateUser(x, u)
  975. }
  976. // UpdateUserCols update user according special columns
  977. func UpdateUserCols(u *User, cols ...string) error {
  978. return updateUserCols(x, u, cols...)
  979. }
  980. func updateUserCols(e Engine, u *User, cols ...string) error {
  981. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  982. return err
  983. }
  984. // UpdateUserSetting updates user's settings.
  985. func UpdateUserSetting(u *User) error {
  986. if !u.IsOrganization() {
  987. if err := checkDupEmail(x, u); err != nil {
  988. return err
  989. }
  990. }
  991. return updateUser(x, u)
  992. }
  993. // deleteBeans deletes all given beans, beans should contain delete conditions.
  994. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  995. for i := range beans {
  996. if _, err = e.Delete(beans[i]); err != nil {
  997. return err
  998. }
  999. }
  1000. return nil
  1001. }
  1002. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  1003. func deleteUser(e *xorm.Session, u *User) error {
  1004. // Note: A user owns any repository or belongs to any organization
  1005. // cannot perform delete operation.
  1006. // Check ownership of repository.
  1007. count, err := getRepositoryCount(e, u)
  1008. if err != nil {
  1009. return fmt.Errorf("GetRepositoryCount: %v", err)
  1010. } else if count > 0 {
  1011. return ErrUserOwnRepos{UID: u.ID}
  1012. }
  1013. // Check membership of organization.
  1014. count, err = u.getOrganizationCount(e)
  1015. if err != nil {
  1016. return fmt.Errorf("GetOrganizationCount: %v", err)
  1017. } else if count > 0 {
  1018. return ErrUserHasOrgs{UID: u.ID}
  1019. }
  1020. // ***** START: Watch *****
  1021. watchedRepoIDs := make([]int64, 0, 10)
  1022. if err = e.Table("watch").Cols("watch.repo_id").
  1023. Where("watch.user_id = ?", u.ID).And("watch.mode <>?", RepoWatchModeDont).Find(&watchedRepoIDs); err != nil {
  1024. return fmt.Errorf("get all watches: %v", err)
  1025. }
  1026. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  1027. return fmt.Errorf("decrease repository num_watches: %v", err)
  1028. }
  1029. // ***** END: Watch *****
  1030. // ***** START: Star *****
  1031. starredRepoIDs := make([]int64, 0, 10)
  1032. if err = e.Table("star").Cols("star.repo_id").
  1033. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  1034. return fmt.Errorf("get all stars: %v", err)
  1035. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  1036. return fmt.Errorf("decrease repository num_stars: %v", err)
  1037. }
  1038. // ***** END: Star *****
  1039. // ***** START: Follow *****
  1040. followeeIDs := make([]int64, 0, 10)
  1041. if err = e.Table("follow").Cols("follow.follow_id").
  1042. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  1043. return fmt.Errorf("get all followees: %v", err)
  1044. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  1045. return fmt.Errorf("decrease user num_followers: %v", err)
  1046. }
  1047. followerIDs := make([]int64, 0, 10)
  1048. if err = e.Table("follow").Cols("follow.user_id").
  1049. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  1050. return fmt.Errorf("get all followers: %v", err)
  1051. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  1052. return fmt.Errorf("decrease user num_following: %v", err)
  1053. }
  1054. // ***** END: Follow *****
  1055. if err = deleteBeans(e,
  1056. &AccessToken{UID: u.ID},
  1057. &Collaboration{UserID: u.ID},
  1058. &Access{UserID: u.ID},
  1059. &Watch{UserID: u.ID},
  1060. &Star{UID: u.ID},
  1061. &Follow{UserID: u.ID},
  1062. &Follow{FollowID: u.ID},
  1063. &Action{UserID: u.ID},
  1064. &IssueUser{UID: u.ID},
  1065. &EmailAddress{UID: u.ID},
  1066. &UserOpenID{UID: u.ID},
  1067. &Reaction{UserID: u.ID},
  1068. &TeamUser{UID: u.ID},
  1069. &Collaboration{UserID: u.ID},
  1070. &Stopwatch{UserID: u.ID},
  1071. ); err != nil {
  1072. return fmt.Errorf("deleteBeans: %v", err)
  1073. }
  1074. // ***** START: PublicKey *****
  1075. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  1076. return fmt.Errorf("deletePublicKeys: %v", err)
  1077. }
  1078. err = rewriteAllPublicKeys(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 := os.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 := os.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) ([]*User, error) {
  1225. if len(ids) == 0 {
  1226. return nil, nil
  1227. }
  1228. ous := make([]*User, 0, len(ids))
  1229. return ous, x.In("id", ids).
  1230. Where("`type` = ?", UserTypeIndividual).
  1231. And("`prohibit_login` = ?", false).
  1232. And("`is_active` = ?", true).
  1233. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  1234. Find(&ous)
  1235. }
  1236. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  1237. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  1238. unames := make([]string, 0, len(ids))
  1239. err := x.In("id", ids).
  1240. Table("user").
  1241. Asc("name").
  1242. Cols("name").
  1243. Find(&unames)
  1244. return unames, err
  1245. }
  1246. // GetUsersByIDs returns all resolved users from a list of Ids.
  1247. func GetUsersByIDs(ids []int64) (UserList, error) {
  1248. ous := make([]*User, 0, len(ids))
  1249. if len(ids) == 0 {
  1250. return ous, nil
  1251. }
  1252. err := x.In("id", ids).
  1253. Asc("name").
  1254. Find(&ous)
  1255. return ous, err
  1256. }
  1257. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1258. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  1259. ids := make([]int64, 0, len(names))
  1260. for _, name := range names {
  1261. u, err := GetUserByName(name)
  1262. if err != nil {
  1263. if ignoreNonExistent {
  1264. continue
  1265. } else {
  1266. return nil, err
  1267. }
  1268. }
  1269. ids = append(ids, u.ID)
  1270. }
  1271. return ids, nil
  1272. }
  1273. // UserCommit represents a commit with validation of user.
  1274. type UserCommit struct {
  1275. User *User
  1276. *git.Commit
  1277. }
  1278. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1279. func ValidateCommitWithEmail(c *git.Commit) *User {
  1280. if c.Author == nil {
  1281. return nil
  1282. }
  1283. u, err := GetUserByEmail(c.Author.Email)
  1284. if err != nil {
  1285. return nil
  1286. }
  1287. return u
  1288. }
  1289. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1290. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1291. var (
  1292. u *User
  1293. emails = map[string]*User{}
  1294. newCommits = list.New()
  1295. e = oldCommits.Front()
  1296. )
  1297. for e != nil {
  1298. c := e.Value.(*git.Commit)
  1299. if c.Author != nil {
  1300. if v, ok := emails[c.Author.Email]; !ok {
  1301. u, _ = GetUserByEmail(c.Author.Email)
  1302. emails[c.Author.Email] = u
  1303. } else {
  1304. u = v
  1305. }
  1306. } else {
  1307. u = nil
  1308. }
  1309. newCommits.PushBack(UserCommit{
  1310. User: u,
  1311. Commit: c,
  1312. })
  1313. e = e.Next()
  1314. }
  1315. return newCommits
  1316. }
  1317. // GetUserByEmail returns the user object by given e-mail if exists.
  1318. func GetUserByEmail(email string) (*User, error) {
  1319. return GetUserByEmailContext(DefaultDBContext(), email)
  1320. }
  1321. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  1322. func GetUserByEmailContext(ctx DBContext, email string) (*User, error) {
  1323. if len(email) == 0 {
  1324. return nil, ErrUserNotExist{0, email, 0}
  1325. }
  1326. email = strings.ToLower(email)
  1327. // First try to find the user by primary email
  1328. user := &User{Email: email}
  1329. has, err := ctx.e.Get(user)
  1330. if err != nil {
  1331. return nil, err
  1332. }
  1333. if has {
  1334. return user, nil
  1335. }
  1336. // Otherwise, check in alternative list for activated email addresses
  1337. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1338. has, err = ctx.e.Get(emailAddress)
  1339. if err != nil {
  1340. return nil, err
  1341. }
  1342. if has {
  1343. return getUserByID(ctx.e, emailAddress.UID)
  1344. }
  1345. // Finally, if email address is the protected email address:
  1346. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1347. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1348. user := &User{LowerName: username}
  1349. has, err := ctx.e.Get(user)
  1350. if err != nil {
  1351. return nil, err
  1352. }
  1353. if has {
  1354. return user, nil
  1355. }
  1356. }
  1357. return nil, ErrUserNotExist{0, email, 0}
  1358. }
  1359. // GetUser checks if a user already exists
  1360. func GetUser(user *User) (bool, error) {
  1361. return x.Get(user)
  1362. }
  1363. // SearchUserOptions contains the options for searching
  1364. type SearchUserOptions struct {
  1365. ListOptions
  1366. Keyword string
  1367. Type UserType
  1368. UID int64
  1369. OrderBy SearchOrderBy
  1370. Visible []structs.VisibleType
  1371. Actor *User // The user doing the search
  1372. IsActive util.OptionalBool
  1373. SearchByEmail bool // Search by email as well as username/full name
  1374. }
  1375. func (opts *SearchUserOptions) toConds() builder.Cond {
  1376. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1377. if len(opts.Keyword) > 0 {
  1378. lowerKeyword := strings.ToLower(opts.Keyword)
  1379. keywordCond := builder.Or(
  1380. builder.Like{"lower_name", lowerKeyword},
  1381. builder.Like{"LOWER(full_name)", lowerKeyword},
  1382. )
  1383. if opts.SearchByEmail {
  1384. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1385. }
  1386. cond = cond.And(keywordCond)
  1387. }
  1388. if len(opts.Visible) > 0 {
  1389. cond = cond.And(builder.In("visibility", opts.Visible))
  1390. } else {
  1391. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1392. }
  1393. if opts.Actor != nil {
  1394. var exprCond builder.Cond
  1395. if setting.Database.UseMySQL {
  1396. exprCond = builder.Expr("org_user.org_id = user.id")
  1397. } else if setting.Database.UseMSSQL {
  1398. exprCond = builder.Expr("org_user.org_id = [user].id")
  1399. } else {
  1400. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1401. }
  1402. var accessCond = builder.NewCond()
  1403. if !opts.Actor.IsRestricted {
  1404. accessCond = builder.Or(
  1405. 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}))),
  1406. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1407. } else {
  1408. // restricted users only see orgs they are a member of
  1409. accessCond = builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID})))
  1410. }
  1411. cond = cond.And(accessCond)
  1412. }
  1413. if opts.UID > 0 {
  1414. cond = cond.And(builder.Eq{"id": opts.UID})
  1415. }
  1416. if !opts.IsActive.IsNone() {
  1417. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1418. }
  1419. return cond
  1420. }
  1421. // SearchUsers takes options i.e. keyword and part of user name to search,
  1422. // it returns results in given range and number of total results.
  1423. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1424. cond := opts.toConds()
  1425. count, err := x.Where(cond).Count(new(User))
  1426. if err != nil {
  1427. return nil, 0, fmt.Errorf("Count: %v", err)
  1428. }
  1429. if len(opts.OrderBy) == 0 {
  1430. opts.OrderBy = SearchOrderByAlphabetically
  1431. }
  1432. sess := x.Where(cond).OrderBy(opts.OrderBy.String())
  1433. if opts.Page != 0 {
  1434. sess = opts.setSessionPagination(sess)
  1435. }
  1436. users = make([]*User, 0, opts.PageSize)
  1437. return users, count, sess.Find(&users)
  1438. }
  1439. // GetStarredRepos returns the repos starred by a particular user
  1440. func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1441. sess := x.Where("star.uid=?", userID).
  1442. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1443. if !private {
  1444. sess = sess.And("is_private=?", false)
  1445. }
  1446. if listOptions.Page != 0 {
  1447. sess = listOptions.setSessionPagination(sess)
  1448. repos := make([]*Repository, 0, listOptions.PageSize)
  1449. return repos, sess.Find(&repos)
  1450. }
  1451. repos := make([]*Repository, 0, 10)
  1452. return repos, sess.Find(&repos)
  1453. }
  1454. // GetWatchedRepos returns the repos watched by a particular user
  1455. func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1456. sess := x.Where("watch.user_id=?", userID).
  1457. And("`watch`.mode<>?", RepoWatchModeDont).
  1458. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1459. if !private {
  1460. sess = sess.And("is_private=?", false)
  1461. }
  1462. if listOptions.Page != 0 {
  1463. sess = listOptions.setSessionPagination(sess)
  1464. repos := make([]*Repository, 0, listOptions.PageSize)
  1465. return repos, sess.Find(&repos)
  1466. }
  1467. repos := make([]*Repository, 0, 10)
  1468. return repos, sess.Find(&repos)
  1469. }
  1470. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1471. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1472. // Start session
  1473. sess := x.NewSession()
  1474. defer sess.Close()
  1475. if err := sess.Begin(); err != nil {
  1476. return false, err
  1477. }
  1478. // Delete keys marked for deletion
  1479. var sshKeysNeedUpdate bool
  1480. for _, KeyToDelete := range keys {
  1481. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1482. if err != nil {
  1483. log.Error("SearchPublicKeyByContent: %v", err)
  1484. continue
  1485. }
  1486. if err = deletePublicKeys(sess, key.ID); err != nil {
  1487. log.Error("deletePublicKeys: %v", err)
  1488. continue
  1489. }
  1490. sshKeysNeedUpdate = true
  1491. }
  1492. if err := sess.Commit(); err != nil {
  1493. return false, err
  1494. }
  1495. return sshKeysNeedUpdate, nil
  1496. }
  1497. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1498. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1499. var sshKeysNeedUpdate bool
  1500. for _, sshKey := range sshPublicKeys {
  1501. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1502. if err == nil {
  1503. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1504. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1505. if IsErrKeyAlreadyExist(err) {
  1506. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1507. } else {
  1508. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1509. }
  1510. } else {
  1511. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1512. sshKeysNeedUpdate = true
  1513. }
  1514. } else {
  1515. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1516. }
  1517. }
  1518. return sshKeysNeedUpdate
  1519. }
  1520. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1521. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1522. var sshKeysNeedUpdate bool
  1523. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1524. // Get Public Keys from DB with current LDAP source
  1525. var giteaKeys []string
  1526. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1527. if err != nil {
  1528. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1529. }
  1530. for _, v := range keys {
  1531. giteaKeys = append(giteaKeys, v.OmitEmail())
  1532. }
  1533. // Get Public Keys from LDAP and skip duplicate keys
  1534. var ldapKeys []string
  1535. for _, v := range sshPublicKeys {
  1536. sshKeySplit := strings.Split(v, " ")
  1537. if len(sshKeySplit) > 1 {
  1538. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1539. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1540. ldapKeys = append(ldapKeys, ldapKey)
  1541. }
  1542. }
  1543. }
  1544. // Check if Public Key sync is needed
  1545. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1546. 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))
  1547. return false
  1548. }
  1549. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1550. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1551. var newLdapSSHKeys []string
  1552. for _, LDAPPublicSSHKey := range ldapKeys {
  1553. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1554. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1555. }
  1556. }
  1557. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1558. sshKeysNeedUpdate = true
  1559. }
  1560. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1561. var giteaKeysToDelete []string
  1562. for _, giteaKey := range giteaKeys {
  1563. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1564. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1565. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1566. }
  1567. }
  1568. // Delete LDAP keys from DB that doesn't exist in LDAP
  1569. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1570. if err != nil {
  1571. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1572. }
  1573. if needUpd {
  1574. sshKeysNeedUpdate = true
  1575. }
  1576. return sshKeysNeedUpdate
  1577. }
  1578. // SyncExternalUsers is used to synchronize users with external authorization source
  1579. func SyncExternalUsers(ctx context.Context, updateExisting bool) error {
  1580. log.Trace("Doing: SyncExternalUsers")
  1581. ls, err := LoginSources()
  1582. if err != nil {
  1583. log.Error("SyncExternalUsers: %v", err)
  1584. return err
  1585. }
  1586. for _, s := range ls {
  1587. if !s.IsActived || !s.IsSyncEnabled {
  1588. continue
  1589. }
  1590. select {
  1591. case <-ctx.Done():
  1592. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1593. return ErrCancelledf("Before update of %s", s.Name)
  1594. default:
  1595. }
  1596. if s.IsLDAP() {
  1597. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1598. var existingUsers []int64
  1599. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1600. var sshKeysNeedUpdate bool
  1601. // Find all users with this login type
  1602. var users []*User
  1603. err = x.Where("login_type = ?", LoginLDAP).
  1604. And("login_source = ?", s.ID).
  1605. Find(&users)
  1606. if err != nil {
  1607. log.Error("SyncExternalUsers: %v", err)
  1608. return err
  1609. }
  1610. select {
  1611. case <-ctx.Done():
  1612. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1613. return ErrCancelledf("Before update of %s", s.Name)
  1614. default:
  1615. }
  1616. sr, err := s.LDAP().SearchEntries()
  1617. if err != nil {
  1618. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1619. continue
  1620. }
  1621. if len(sr) == 0 {
  1622. if !s.LDAP().AllowDeactivateAll {
  1623. log.Error("LDAP search found no entries but did not report an error. Refusing to deactivate all users")
  1624. continue
  1625. } else {
  1626. log.Warn("LDAP search found no entries but did not report an error. All users will be deactivated as per settings")
  1627. }
  1628. }
  1629. for _, su := range sr {
  1630. select {
  1631. case <-ctx.Done():
  1632. log.Warn("SyncExternalUsers: Cancelled at update of %s before completed update of users", s.Name)
  1633. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1634. if sshKeysNeedUpdate {
  1635. err = RewriteAllPublicKeys()
  1636. if err != nil {
  1637. log.Error("RewriteAllPublicKeys: %v", err)
  1638. }
  1639. }
  1640. return ErrCancelledf("During update of %s before completed update of users", s.Name)
  1641. default:
  1642. }
  1643. if len(su.Username) == 0 {
  1644. continue
  1645. }
  1646. if len(su.Mail) == 0 {
  1647. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1648. }
  1649. var usr *User
  1650. // Search for existing user
  1651. for _, du := range users {
  1652. if du.LowerName == strings.ToLower(su.Username) {
  1653. usr = du
  1654. break
  1655. }
  1656. }
  1657. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1658. // If no existing user found, create one
  1659. if usr == nil {
  1660. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1661. usr = &User{
  1662. LowerName: strings.ToLower(su.Username),
  1663. Name: su.Username,
  1664. FullName: fullName,
  1665. LoginType: s.Type,
  1666. LoginSource: s.ID,
  1667. LoginName: su.Username,
  1668. Email: su.Mail,
  1669. IsAdmin: su.IsAdmin,
  1670. IsRestricted: su.IsRestricted,
  1671. IsActive: true,
  1672. }
  1673. err = CreateUser(usr)
  1674. if err != nil {
  1675. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1676. } else if isAttributeSSHPublicKeySet {
  1677. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1678. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1679. sshKeysNeedUpdate = true
  1680. }
  1681. }
  1682. } else if updateExisting {
  1683. existingUsers = append(existingUsers, usr.ID)
  1684. // Synchronize SSH Public Key if that attribute is set
  1685. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1686. sshKeysNeedUpdate = true
  1687. }
  1688. // Check if user data has changed
  1689. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1690. (len(s.LDAP().RestrictedFilter) > 0 && usr.IsRestricted != su.IsRestricted) ||
  1691. !strings.EqualFold(usr.Email, su.Mail) ||
  1692. usr.FullName != fullName ||
  1693. !usr.IsActive {
  1694. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1695. usr.FullName = fullName
  1696. usr.Email = su.Mail
  1697. // Change existing admin flag only if AdminFilter option is set
  1698. if len(s.LDAP().AdminFilter) > 0 {
  1699. usr.IsAdmin = su.IsAdmin
  1700. }
  1701. // Change existing restricted flag only if RestrictedFilter option is set
  1702. if !usr.IsAdmin && len(s.LDAP().RestrictedFilter) > 0 {
  1703. usr.IsRestricted = su.IsRestricted
  1704. }
  1705. usr.IsActive = true
  1706. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_restricted", "is_active")
  1707. if err != nil {
  1708. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1709. }
  1710. }
  1711. }
  1712. }
  1713. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1714. if sshKeysNeedUpdate {
  1715. err = RewriteAllPublicKeys()
  1716. if err != nil {
  1717. log.Error("RewriteAllPublicKeys: %v", err)
  1718. }
  1719. }
  1720. select {
  1721. case <-ctx.Done():
  1722. log.Warn("SyncExternalUsers: Cancelled during update of %s before delete users", s.Name)
  1723. return ErrCancelledf("During update of %s before delete users", s.Name)
  1724. default:
  1725. }
  1726. // Deactivate users not present in LDAP
  1727. if updateExisting {
  1728. for _, usr := range users {
  1729. found := false
  1730. for _, uid := range existingUsers {
  1731. if usr.ID == uid {
  1732. found = true
  1733. break
  1734. }
  1735. }
  1736. if !found {
  1737. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1738. usr.IsActive = false
  1739. err = UpdateUserCols(usr, "is_active")
  1740. if err != nil {
  1741. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747. }
  1748. return nil
  1749. }