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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "container/list"
  8. "context"
  9. "crypto/md5"
  10. "crypto/sha256"
  11. "crypto/subtle"
  12. "encoding/hex"
  13. "errors"
  14. "fmt"
  15. _ "image/jpeg" // Needed for jpeg support
  16. "image/png"
  17. "os"
  18. "path/filepath"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "unicode/utf8"
  24. "code.gitea.io/gitea/modules/avatar"
  25. "code.gitea.io/gitea/modules/base"
  26. "code.gitea.io/gitea/modules/generate"
  27. "code.gitea.io/gitea/modules/git"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/public"
  30. "code.gitea.io/gitea/modules/setting"
  31. "code.gitea.io/gitea/modules/structs"
  32. api "code.gitea.io/gitea/modules/structs"
  33. "code.gitea.io/gitea/modules/timeutil"
  34. "code.gitea.io/gitea/modules/util"
  35. "github.com/unknwon/com"
  36. "golang.org/x/crypto/argon2"
  37. "golang.org/x/crypto/bcrypt"
  38. "golang.org/x/crypto/pbkdf2"
  39. "golang.org/x/crypto/scrypt"
  40. "golang.org/x/crypto/ssh"
  41. "xorm.io/builder"
  42. "xorm.io/xorm"
  43. )
  44. // UserType defines the user type
  45. type UserType int
  46. const (
  47. // UserTypeIndividual defines an individual user
  48. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  49. // UserTypeOrganization defines an organization
  50. UserTypeOrganization
  51. )
  52. const (
  53. algoBcrypt = "bcrypt"
  54. algoScrypt = "scrypt"
  55. algoArgon2 = "argon2"
  56. algoPbkdf2 = "pbkdf2"
  57. // EmailNotificationsEnabled indicates that the user would like to receive all email notifications
  58. EmailNotificationsEnabled = "enabled"
  59. // EmailNotificationsOnMention indicates that the user would like to be notified via email when mentioned.
  60. EmailNotificationsOnMention = "onmention"
  61. // EmailNotificationsDisabled indicates that the user would not like to be notified via email.
  62. EmailNotificationsDisabled = "disabled"
  63. )
  64. var (
  65. // ErrUserNotKeyOwner user does not own this key error
  66. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  67. // ErrEmailNotExist e-mail does not exist error
  68. ErrEmailNotExist = errors.New("E-mail does not exist")
  69. // ErrEmailNotActivated e-mail address has not been activated error
  70. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  71. // ErrUserNameIllegal user name contains illegal characters error
  72. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  73. // ErrLoginSourceNotActived login source is not actived error
  74. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  75. // ErrUnsupportedLoginType login source is unknown error
  76. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  77. // Characters prohibited in a user name (anything except A-Za-z0-9_.-)
  78. alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
  79. )
  80. // User represents the object of individual and member of organization.
  81. type User struct {
  82. ID int64 `xorm:"pk autoincr"`
  83. LowerName string `xorm:"UNIQUE NOT NULL"`
  84. Name string `xorm:"UNIQUE NOT NULL"`
  85. FullName string
  86. // Email is the primary email address (to be used for communication)
  87. Email string `xorm:"NOT NULL"`
  88. KeepEmailPrivate bool
  89. EmailNotificationsPreference string `xorm:"VARCHAR(20) NOT NULL DEFAULT 'enabled'"`
  90. Passwd string `xorm:"NOT NULL"`
  91. PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'pbkdf2'"`
  92. // MustChangePassword is an attribute that determines if a user
  93. // is to change his/her password after registration.
  94. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  95. LoginType LoginType
  96. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  97. LoginName string
  98. Type UserType
  99. OwnedOrgs []*User `xorm:"-"`
  100. Orgs []*User `xorm:"-"`
  101. Repos []*Repository `xorm:"-"`
  102. Location string
  103. Website string
  104. Rands string `xorm:"VARCHAR(10)"`
  105. Salt string `xorm:"VARCHAR(10)"`
  106. Language string `xorm:"VARCHAR(5)"`
  107. Description string
  108. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  109. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  110. LastLoginUnix timeutil.TimeStamp `xorm:"INDEX"`
  111. // Remember visibility choice for convenience, true for private
  112. LastRepoVisibility bool
  113. // Maximum repository creation limit, -1 means use global default
  114. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  115. // Permissions
  116. IsActive bool `xorm:"INDEX"` // Activate primary email
  117. IsAdmin bool
  118. IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
  119. AllowGitHook bool
  120. AllowImportLocal bool // Allow migrate repository by local path
  121. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  122. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  123. // Avatar
  124. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  125. AvatarEmail string `xorm:"NOT NULL"`
  126. UseCustomAvatar bool
  127. // Counters
  128. NumFollowers int
  129. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  130. NumStars int
  131. NumRepos int
  132. // For organization
  133. NumTeams int
  134. NumMembers int
  135. Teams []*Team `xorm:"-"`
  136. Members UserList `xorm:"-"`
  137. MembersIsPublic map[int64]bool `xorm:"-"`
  138. Visibility structs.VisibleType `xorm:"NOT NULL DEFAULT 0"`
  139. RepoAdminChangeTeamAccess bool `xorm:"NOT NULL DEFAULT false"`
  140. // Preferences
  141. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  142. Theme string `xorm:"NOT NULL DEFAULT ''"`
  143. 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.TrimRight(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 := os.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. // IsUserPartOfOrg returns true if user with userID is part of the u organisation.
  521. func (u *User) IsUserPartOfOrg(userID int64) bool {
  522. return u.isUserPartOfOrg(x, userID)
  523. }
  524. func (u *User) isUserPartOfOrg(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) (err error) {
  552. u.Repos, _, err = GetUserRepositories(&SearchRepoOptions{Actor: u, Private: true, ListOptions: listOpts})
  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. // ***** END: PublicKey *****
  1079. // ***** START: GPGPublicKey *****
  1080. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  1081. return fmt.Errorf("deleteGPGKeys: %v", err)
  1082. }
  1083. // ***** END: GPGPublicKey *****
  1084. // Clear assignee.
  1085. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  1086. return fmt.Errorf("clear assignee: %v", err)
  1087. }
  1088. // ***** START: ExternalLoginUser *****
  1089. if err = removeAllAccountLinks(e, u); err != nil {
  1090. return fmt.Errorf("ExternalLoginUser: %v", err)
  1091. }
  1092. // ***** END: ExternalLoginUser *****
  1093. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  1094. return fmt.Errorf("Delete: %v", err)
  1095. }
  1096. // FIXME: system notice
  1097. // Note: There are something just cannot be roll back,
  1098. // so just keep error logs of those operations.
  1099. path := UserPath(u.Name)
  1100. if err := os.RemoveAll(path); err != nil {
  1101. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  1102. }
  1103. if len(u.Avatar) > 0 {
  1104. avatarPath := u.CustomAvatarPath()
  1105. if com.IsExist(avatarPath) {
  1106. if err := os.Remove(avatarPath); err != nil {
  1107. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1108. }
  1109. }
  1110. }
  1111. return nil
  1112. }
  1113. // DeleteUser completely and permanently deletes everything of a user,
  1114. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  1115. func DeleteUser(u *User) (err error) {
  1116. if u.IsOrganization() {
  1117. return fmt.Errorf("%s is an organization not a user", u.Name)
  1118. }
  1119. sess := x.NewSession()
  1120. defer sess.Close()
  1121. if err = sess.Begin(); err != nil {
  1122. return err
  1123. }
  1124. if err = deleteUser(sess, u); err != nil {
  1125. // Note: don't wrapper error here.
  1126. return err
  1127. }
  1128. return sess.Commit()
  1129. }
  1130. // DeleteInactiveUsers deletes all inactive users and email addresses.
  1131. func DeleteInactiveUsers(ctx context.Context, olderThan time.Duration) (err error) {
  1132. users := make([]*User, 0, 10)
  1133. if olderThan > 0 {
  1134. if err = x.
  1135. Where("is_active = ? and created_unix < ?", false, time.Now().Add(-olderThan).Unix()).
  1136. Find(&users); err != nil {
  1137. return fmt.Errorf("get all inactive users: %v", err)
  1138. }
  1139. } else {
  1140. if err = x.
  1141. Where("is_active = ?", false).
  1142. Find(&users); err != nil {
  1143. return fmt.Errorf("get all inactive users: %v", err)
  1144. }
  1145. }
  1146. // FIXME: should only update authorized_keys file once after all deletions.
  1147. for _, u := range users {
  1148. select {
  1149. case <-ctx.Done():
  1150. return ErrCancelledf("Before delete inactive user %s", u.Name)
  1151. default:
  1152. }
  1153. if err = DeleteUser(u); err != nil {
  1154. // Ignore users that were set inactive by admin.
  1155. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  1156. continue
  1157. }
  1158. return err
  1159. }
  1160. }
  1161. _, err = x.
  1162. Where("is_activated = ?", false).
  1163. Delete(new(EmailAddress))
  1164. return err
  1165. }
  1166. // UserPath returns the path absolute path of user repositories.
  1167. func UserPath(userName string) string {
  1168. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  1169. }
  1170. func getUserByID(e Engine, id int64) (*User, error) {
  1171. u := new(User)
  1172. has, err := e.ID(id).Get(u)
  1173. if err != nil {
  1174. return nil, err
  1175. } else if !has {
  1176. return nil, ErrUserNotExist{id, "", 0}
  1177. }
  1178. return u, nil
  1179. }
  1180. // GetUserByID returns the user object by given ID if exists.
  1181. func GetUserByID(id int64) (*User, error) {
  1182. return getUserByID(x, id)
  1183. }
  1184. // GetUserByName returns user by given name.
  1185. func GetUserByName(name string) (*User, error) {
  1186. return getUserByName(x, name)
  1187. }
  1188. func getUserByName(e Engine, name string) (*User, error) {
  1189. if len(name) == 0 {
  1190. return nil, ErrUserNotExist{0, name, 0}
  1191. }
  1192. u := &User{LowerName: strings.ToLower(name)}
  1193. has, err := e.Get(u)
  1194. if err != nil {
  1195. return nil, err
  1196. } else if !has {
  1197. return nil, ErrUserNotExist{0, name, 0}
  1198. }
  1199. return u, nil
  1200. }
  1201. // GetUserEmailsByNames returns a list of e-mails corresponds to names of users
  1202. // that have their email notifications set to enabled or onmention.
  1203. func GetUserEmailsByNames(names []string) []string {
  1204. return getUserEmailsByNames(x, names)
  1205. }
  1206. func getUserEmailsByNames(e Engine, names []string) []string {
  1207. mails := make([]string, 0, len(names))
  1208. for _, name := range names {
  1209. u, err := getUserByName(e, name)
  1210. if err != nil {
  1211. continue
  1212. }
  1213. if u.IsMailable() && u.EmailNotifications() != EmailNotificationsDisabled {
  1214. mails = append(mails, u.Email)
  1215. }
  1216. }
  1217. return mails
  1218. }
  1219. // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails
  1220. func GetMaileableUsersByIDs(ids []int64) ([]*User, error) {
  1221. if len(ids) == 0 {
  1222. return nil, nil
  1223. }
  1224. ous := make([]*User, 0, len(ids))
  1225. return ous, x.In("id", ids).
  1226. Where("`type` = ?", UserTypeIndividual).
  1227. And("`prohibit_login` = ?", false).
  1228. And("`is_active` = ?", true).
  1229. And("`email_notifications_preference` = ?", EmailNotificationsEnabled).
  1230. Find(&ous)
  1231. }
  1232. // GetUserNamesByIDs returns usernames for all resolved users from a list of Ids.
  1233. func GetUserNamesByIDs(ids []int64) ([]string, error) {
  1234. unames := make([]string, 0, len(ids))
  1235. err := x.In("id", ids).
  1236. Table("user").
  1237. Asc("name").
  1238. Cols("name").
  1239. Find(&unames)
  1240. return unames, err
  1241. }
  1242. // GetUsersByIDs returns all resolved users from a list of Ids.
  1243. func GetUsersByIDs(ids []int64) (UserList, error) {
  1244. ous := make([]*User, 0, len(ids))
  1245. if len(ids) == 0 {
  1246. return ous, nil
  1247. }
  1248. err := x.In("id", ids).
  1249. Asc("name").
  1250. Find(&ous)
  1251. return ous, err
  1252. }
  1253. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1254. func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) {
  1255. ids := make([]int64, 0, len(names))
  1256. for _, name := range names {
  1257. u, err := GetUserByName(name)
  1258. if err != nil {
  1259. if ignoreNonExistent {
  1260. continue
  1261. } else {
  1262. return nil, err
  1263. }
  1264. }
  1265. ids = append(ids, u.ID)
  1266. }
  1267. return ids, nil
  1268. }
  1269. // UserCommit represents a commit with validation of user.
  1270. type UserCommit struct {
  1271. User *User
  1272. *git.Commit
  1273. }
  1274. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1275. func ValidateCommitWithEmail(c *git.Commit) *User {
  1276. if c.Author == nil {
  1277. return nil
  1278. }
  1279. u, err := GetUserByEmail(c.Author.Email)
  1280. if err != nil {
  1281. return nil
  1282. }
  1283. return u
  1284. }
  1285. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1286. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1287. var (
  1288. u *User
  1289. emails = map[string]*User{}
  1290. newCommits = list.New()
  1291. e = oldCommits.Front()
  1292. )
  1293. for e != nil {
  1294. c := e.Value.(*git.Commit)
  1295. if c.Author != nil {
  1296. if v, ok := emails[c.Author.Email]; !ok {
  1297. u, _ = GetUserByEmail(c.Author.Email)
  1298. emails[c.Author.Email] = u
  1299. } else {
  1300. u = v
  1301. }
  1302. } else {
  1303. u = nil
  1304. }
  1305. newCommits.PushBack(UserCommit{
  1306. User: u,
  1307. Commit: c,
  1308. })
  1309. e = e.Next()
  1310. }
  1311. return newCommits
  1312. }
  1313. // GetUserByEmail returns the user object by given e-mail if exists.
  1314. func GetUserByEmail(email string) (*User, error) {
  1315. return GetUserByEmailContext(DefaultDBContext(), email)
  1316. }
  1317. // GetUserByEmailContext returns the user object by given e-mail if exists with db context
  1318. func GetUserByEmailContext(ctx DBContext, email string) (*User, error) {
  1319. if len(email) == 0 {
  1320. return nil, ErrUserNotExist{0, email, 0}
  1321. }
  1322. email = strings.ToLower(email)
  1323. // First try to find the user by primary email
  1324. user := &User{Email: email}
  1325. has, err := ctx.e.Get(user)
  1326. if err != nil {
  1327. return nil, err
  1328. }
  1329. if has {
  1330. return user, nil
  1331. }
  1332. // Otherwise, check in alternative list for activated email addresses
  1333. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1334. has, err = ctx.e.Get(emailAddress)
  1335. if err != nil {
  1336. return nil, err
  1337. }
  1338. if has {
  1339. return getUserByID(ctx.e, emailAddress.UID)
  1340. }
  1341. // Finally, if email address is the protected email address:
  1342. if strings.HasSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress)) {
  1343. username := strings.TrimSuffix(email, fmt.Sprintf("@%s", setting.Service.NoReplyAddress))
  1344. user := &User{}
  1345. has, err := ctx.e.Where("lower_name=?", username).Get(user)
  1346. if err != nil {
  1347. return nil, err
  1348. }
  1349. if has {
  1350. return user, nil
  1351. }
  1352. }
  1353. return nil, ErrUserNotExist{0, email, 0}
  1354. }
  1355. // GetUser checks if a user already exists
  1356. func GetUser(user *User) (bool, error) {
  1357. return x.Get(user)
  1358. }
  1359. // SearchUserOptions contains the options for searching
  1360. type SearchUserOptions struct {
  1361. ListOptions
  1362. Keyword string
  1363. Type UserType
  1364. UID int64
  1365. OrderBy SearchOrderBy
  1366. Visible []structs.VisibleType
  1367. Actor *User // The user doing the search
  1368. IsActive util.OptionalBool
  1369. SearchByEmail bool // Search by email as well as username/full name
  1370. }
  1371. func (opts *SearchUserOptions) toConds() builder.Cond {
  1372. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1373. if len(opts.Keyword) > 0 {
  1374. lowerKeyword := strings.ToLower(opts.Keyword)
  1375. keywordCond := builder.Or(
  1376. builder.Like{"lower_name", lowerKeyword},
  1377. builder.Like{"LOWER(full_name)", lowerKeyword},
  1378. )
  1379. if opts.SearchByEmail {
  1380. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1381. }
  1382. cond = cond.And(keywordCond)
  1383. }
  1384. if len(opts.Visible) > 0 {
  1385. cond = cond.And(builder.In("visibility", opts.Visible))
  1386. } else {
  1387. cond = cond.And(builder.In("visibility", structs.VisibleTypePublic))
  1388. }
  1389. if opts.Actor != nil {
  1390. var exprCond builder.Cond
  1391. if setting.Database.UseMySQL {
  1392. exprCond = builder.Expr("org_user.org_id = user.id")
  1393. } else if setting.Database.UseMSSQL {
  1394. exprCond = builder.Expr("org_user.org_id = [user].id")
  1395. } else {
  1396. exprCond = builder.Expr("org_user.org_id = \"user\".id")
  1397. }
  1398. var accessCond = builder.NewCond()
  1399. if !opts.Actor.IsRestricted {
  1400. accessCond = builder.Or(
  1401. 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}))),
  1402. builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited))
  1403. } else {
  1404. // restricted users only see orgs they are a member of
  1405. accessCond = builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.Actor.ID})))
  1406. }
  1407. cond = cond.And(accessCond)
  1408. }
  1409. if opts.UID > 0 {
  1410. cond = cond.And(builder.Eq{"id": opts.UID})
  1411. }
  1412. if !opts.IsActive.IsNone() {
  1413. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1414. }
  1415. return cond
  1416. }
  1417. // SearchUsers takes options i.e. keyword and part of user name to search,
  1418. // it returns results in given range and number of total results.
  1419. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1420. cond := opts.toConds()
  1421. count, err := x.Where(cond).Count(new(User))
  1422. if err != nil {
  1423. return nil, 0, fmt.Errorf("Count: %v", err)
  1424. }
  1425. if len(opts.OrderBy) == 0 {
  1426. opts.OrderBy = SearchOrderByAlphabetically
  1427. }
  1428. sess := x.Where(cond).OrderBy(opts.OrderBy.String())
  1429. if opts.Page != 0 {
  1430. sess = opts.setSessionPagination(sess)
  1431. }
  1432. users = make([]*User, 0, opts.PageSize)
  1433. return users, count, sess.Find(&users)
  1434. }
  1435. // GetStarredRepos returns the repos starred by a particular user
  1436. func GetStarredRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1437. sess := x.Where("star.uid=?", userID).
  1438. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1439. if !private {
  1440. sess = sess.And("is_private=?", false)
  1441. }
  1442. if listOptions.Page != 0 {
  1443. sess = listOptions.setSessionPagination(sess)
  1444. repos := make([]*Repository, 0, listOptions.PageSize)
  1445. return repos, sess.Find(&repos)
  1446. }
  1447. repos := make([]*Repository, 0, 10)
  1448. return repos, sess.Find(&repos)
  1449. }
  1450. // GetWatchedRepos returns the repos watched by a particular user
  1451. func GetWatchedRepos(userID int64, private bool, listOptions ListOptions) ([]*Repository, error) {
  1452. sess := x.Where("watch.user_id=?", userID).
  1453. And("`watch`.mode<>?", RepoWatchModeDont).
  1454. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1455. if !private {
  1456. sess = sess.And("is_private=?", false)
  1457. }
  1458. if listOptions.Page != 0 {
  1459. sess = listOptions.setSessionPagination(sess)
  1460. repos := make([]*Repository, 0, listOptions.PageSize)
  1461. return repos, sess.Find(&repos)
  1462. }
  1463. repos := make([]*Repository, 0, 10)
  1464. return repos, sess.Find(&repos)
  1465. }
  1466. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1467. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1468. // Start session
  1469. sess := x.NewSession()
  1470. defer sess.Close()
  1471. if err := sess.Begin(); err != nil {
  1472. return false, err
  1473. }
  1474. // Delete keys marked for deletion
  1475. var sshKeysNeedUpdate bool
  1476. for _, KeyToDelete := range keys {
  1477. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1478. if err != nil {
  1479. log.Error("SearchPublicKeyByContent: %v", err)
  1480. continue
  1481. }
  1482. if err = deletePublicKeys(sess, key.ID); err != nil {
  1483. log.Error("deletePublicKeys: %v", err)
  1484. continue
  1485. }
  1486. sshKeysNeedUpdate = true
  1487. }
  1488. if err := sess.Commit(); err != nil {
  1489. return false, err
  1490. }
  1491. return sshKeysNeedUpdate, nil
  1492. }
  1493. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1494. func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1495. var sshKeysNeedUpdate bool
  1496. for _, sshKey := range sshPublicKeys {
  1497. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1498. if err == nil {
  1499. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1500. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1501. if IsErrKeyAlreadyExist(err) {
  1502. log.Trace("addLdapSSHPublicKeys[%s]: LDAP Public SSH Key %s already exists for user", s.Name, usr.Name)
  1503. } else {
  1504. log.Error("addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1505. }
  1506. } else {
  1507. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1508. sshKeysNeedUpdate = true
  1509. }
  1510. } else {
  1511. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1512. }
  1513. }
  1514. return sshKeysNeedUpdate
  1515. }
  1516. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1517. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool {
  1518. var sshKeysNeedUpdate bool
  1519. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1520. // Get Public Keys from DB with current LDAP source
  1521. var giteaKeys []string
  1522. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1523. if err != nil {
  1524. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1525. }
  1526. for _, v := range keys {
  1527. giteaKeys = append(giteaKeys, v.OmitEmail())
  1528. }
  1529. // Get Public Keys from LDAP and skip duplicate keys
  1530. var ldapKeys []string
  1531. for _, v := range sshPublicKeys {
  1532. sshKeySplit := strings.Split(v, " ")
  1533. if len(sshKeySplit) > 1 {
  1534. ldapKey := strings.Join(sshKeySplit[:2], " ")
  1535. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1536. ldapKeys = append(ldapKeys, ldapKey)
  1537. }
  1538. }
  1539. }
  1540. // Check if Public Key sync is needed
  1541. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1542. 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))
  1543. return false
  1544. }
  1545. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1546. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1547. var newLdapSSHKeys []string
  1548. for _, LDAPPublicSSHKey := range ldapKeys {
  1549. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1550. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1551. }
  1552. }
  1553. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1554. sshKeysNeedUpdate = true
  1555. }
  1556. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1557. var giteaKeysToDelete []string
  1558. for _, giteaKey := range giteaKeys {
  1559. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1560. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1561. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1562. }
  1563. }
  1564. // Delete LDAP keys from DB that doesn't exist in LDAP
  1565. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1566. if err != nil {
  1567. log.Error("synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1568. }
  1569. if needUpd {
  1570. sshKeysNeedUpdate = true
  1571. }
  1572. return sshKeysNeedUpdate
  1573. }
  1574. // SyncExternalUsers is used to synchronize users with external authorization source
  1575. func SyncExternalUsers(ctx context.Context, updateExisting bool) error {
  1576. log.Trace("Doing: SyncExternalUsers")
  1577. ls, err := LoginSources()
  1578. if err != nil {
  1579. log.Error("SyncExternalUsers: %v", err)
  1580. return err
  1581. }
  1582. for _, s := range ls {
  1583. if !s.IsActived || !s.IsSyncEnabled {
  1584. continue
  1585. }
  1586. select {
  1587. case <-ctx.Done():
  1588. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1589. return ErrCancelledf("Before update of %s", s.Name)
  1590. default:
  1591. }
  1592. if s.IsLDAP() {
  1593. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1594. var existingUsers []int64
  1595. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1596. var sshKeysNeedUpdate bool
  1597. // Find all users with this login type
  1598. var users []*User
  1599. err = x.Where("login_type = ?", LoginLDAP).
  1600. And("login_source = ?", s.ID).
  1601. Find(&users)
  1602. if err != nil {
  1603. log.Error("SyncExternalUsers: %v", err)
  1604. return err
  1605. }
  1606. select {
  1607. case <-ctx.Done():
  1608. log.Warn("SyncExternalUsers: Cancelled before update of %s", s.Name)
  1609. return ErrCancelledf("Before update of %s", s.Name)
  1610. default:
  1611. }
  1612. sr, err := s.LDAP().SearchEntries()
  1613. if err != nil {
  1614. log.Error("SyncExternalUsers LDAP source failure [%s], skipped", s.Name)
  1615. continue
  1616. }
  1617. if len(sr) == 0 {
  1618. if !s.LDAP().AllowDeactivateAll {
  1619. log.Error("LDAP search found no entries but did not report an error. Refusing to deactivate all users")
  1620. continue
  1621. } else {
  1622. log.Warn("LDAP search found no entries but did not report an error. All users will be deactivated as per settings")
  1623. }
  1624. }
  1625. for _, su := range sr {
  1626. select {
  1627. case <-ctx.Done():
  1628. log.Warn("SyncExternalUsers: Cancelled at update of %s before completed update of users", s.Name)
  1629. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1630. if sshKeysNeedUpdate {
  1631. err = RewriteAllPublicKeys()
  1632. if err != nil {
  1633. log.Error("RewriteAllPublicKeys: %v", err)
  1634. }
  1635. }
  1636. return ErrCancelledf("During update of %s before completed update of users", s.Name)
  1637. default:
  1638. }
  1639. if len(su.Username) == 0 {
  1640. continue
  1641. }
  1642. if len(su.Mail) == 0 {
  1643. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1644. }
  1645. var usr *User
  1646. // Search for existing user
  1647. for _, du := range users {
  1648. if du.LowerName == strings.ToLower(su.Username) {
  1649. usr = du
  1650. break
  1651. }
  1652. }
  1653. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1654. // If no existing user found, create one
  1655. if usr == nil {
  1656. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1657. usr = &User{
  1658. LowerName: strings.ToLower(su.Username),
  1659. Name: su.Username,
  1660. FullName: fullName,
  1661. LoginType: s.Type,
  1662. LoginSource: s.ID,
  1663. LoginName: su.Username,
  1664. Email: su.Mail,
  1665. IsAdmin: su.IsAdmin,
  1666. IsRestricted: su.IsRestricted,
  1667. IsActive: true,
  1668. }
  1669. err = CreateUser(usr)
  1670. if err != nil {
  1671. log.Error("SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1672. } else if isAttributeSSHPublicKeySet {
  1673. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1674. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1675. sshKeysNeedUpdate = true
  1676. }
  1677. }
  1678. } else if updateExisting {
  1679. existingUsers = append(existingUsers, usr.ID)
  1680. // Synchronize SSH Public Key if that attribute is set
  1681. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1682. sshKeysNeedUpdate = true
  1683. }
  1684. // Check if user data has changed
  1685. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1686. (len(s.LDAP().RestrictedFilter) > 0 && usr.IsRestricted != su.IsRestricted) ||
  1687. !strings.EqualFold(usr.Email, su.Mail) ||
  1688. usr.FullName != fullName ||
  1689. !usr.IsActive {
  1690. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1691. usr.FullName = fullName
  1692. usr.Email = su.Mail
  1693. // Change existing admin flag only if AdminFilter option is set
  1694. if len(s.LDAP().AdminFilter) > 0 {
  1695. usr.IsAdmin = su.IsAdmin
  1696. }
  1697. // Change existing restricted flag only if RestrictedFilter option is set
  1698. if !usr.IsAdmin && len(s.LDAP().RestrictedFilter) > 0 {
  1699. usr.IsRestricted = su.IsRestricted
  1700. }
  1701. usr.IsActive = true
  1702. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_restricted", "is_active")
  1703. if err != nil {
  1704. log.Error("SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1705. }
  1706. }
  1707. }
  1708. }
  1709. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1710. if sshKeysNeedUpdate {
  1711. err = RewriteAllPublicKeys()
  1712. if err != nil {
  1713. log.Error("RewriteAllPublicKeys: %v", err)
  1714. }
  1715. }
  1716. select {
  1717. case <-ctx.Done():
  1718. log.Warn("SyncExternalUsers: Cancelled during update of %s before delete users", s.Name)
  1719. return ErrCancelledf("During update of %s before delete users", s.Name)
  1720. default:
  1721. }
  1722. // Deactivate users not present in LDAP
  1723. if updateExisting {
  1724. for _, usr := range users {
  1725. found := false
  1726. for _, uid := range existingUsers {
  1727. if usr.ID == uid {
  1728. found = true
  1729. break
  1730. }
  1731. }
  1732. if !found {
  1733. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1734. usr.IsActive = false
  1735. err = UpdateUserCols(usr, "is_active")
  1736. if err != nil {
  1737. log.Error("SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1738. }
  1739. }
  1740. }
  1741. }
  1742. }
  1743. }
  1744. return nil
  1745. }