You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 46 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
8 years ago
11 years ago
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
10 years ago
8 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
9 years ago
10 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/md5"
  9. "crypto/sha256"
  10. "crypto/subtle"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. "image"
  15. // Needed for jpeg support
  16. _ "image/jpeg"
  17. "image/png"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "time"
  22. "unicode/utf8"
  23. "github.com/Unknwon/com"
  24. "github.com/go-xorm/builder"
  25. "github.com/go-xorm/xorm"
  26. "github.com/nfnt/resize"
  27. "golang.org/x/crypto/pbkdf2"
  28. "golang.org/x/crypto/ssh"
  29. "code.gitea.io/git"
  30. api "code.gitea.io/sdk/gitea"
  31. "code.gitea.io/gitea/modules/avatar"
  32. "code.gitea.io/gitea/modules/base"
  33. "code.gitea.io/gitea/modules/generate"
  34. "code.gitea.io/gitea/modules/log"
  35. "code.gitea.io/gitea/modules/setting"
  36. "code.gitea.io/gitea/modules/util"
  37. )
  38. // UserType defines the user type
  39. type UserType int
  40. const (
  41. // UserTypeIndividual defines an individual user
  42. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  43. // UserTypeOrganization defines an organization
  44. UserTypeOrganization
  45. )
  46. const syncExternalUsers = "sync_external_users"
  47. var (
  48. // ErrUserNotKeyOwner user does not own this key error
  49. ErrUserNotKeyOwner = errors.New("User does not own this public key")
  50. // ErrEmailNotExist e-mail does not exist error
  51. ErrEmailNotExist = errors.New("E-mail does not exist")
  52. // ErrEmailNotActivated e-mail address has not been activated error
  53. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  54. // ErrUserNameIllegal user name contains illegal characters error
  55. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  56. // ErrLoginSourceNotActived login source is not actived error
  57. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  58. // ErrUnsupportedLoginType login source is unknown error
  59. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  60. )
  61. // User represents the object of individual and member of organization.
  62. type User struct {
  63. ID int64 `xorm:"pk autoincr"`
  64. LowerName string `xorm:"UNIQUE NOT NULL"`
  65. Name string `xorm:"UNIQUE NOT NULL"`
  66. FullName string
  67. // Email is the primary email address (to be used for communication)
  68. Email string `xorm:"NOT NULL"`
  69. KeepEmailPrivate bool
  70. Passwd string `xorm:"NOT NULL"`
  71. // MustChangePassword is an attribute that determines if a user
  72. // is to change his/her password after registration.
  73. MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
  74. LoginType LoginType
  75. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  76. LoginName string
  77. Type UserType
  78. OwnedOrgs []*User `xorm:"-"`
  79. Orgs []*User `xorm:"-"`
  80. Repos []*Repository `xorm:"-"`
  81. Location string
  82. Website string
  83. Rands string `xorm:"VARCHAR(10)"`
  84. Salt string `xorm:"VARCHAR(10)"`
  85. Language string `xorm:"VARCHAR(5)"`
  86. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  87. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  88. LastLoginUnix util.TimeStamp `xorm:"INDEX"`
  89. // Remember visibility choice for convenience, true for private
  90. LastRepoVisibility bool
  91. // Maximum repository creation limit, -1 means use global default
  92. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  93. // Permissions
  94. IsActive bool `xorm:"INDEX"` // Activate primary email
  95. IsAdmin bool
  96. AllowGitHook bool
  97. AllowImportLocal bool // Allow migrate repository by local path
  98. AllowCreateOrganization bool `xorm:"DEFAULT true"`
  99. ProhibitLogin bool `xorm:"NOT NULL DEFAULT false"`
  100. // Avatar
  101. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  102. AvatarEmail string `xorm:"NOT NULL"`
  103. UseCustomAvatar bool
  104. // Counters
  105. NumFollowers int
  106. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  107. NumStars int
  108. NumRepos int
  109. // For organization
  110. Description string
  111. NumTeams int
  112. NumMembers int
  113. Teams []*Team `xorm:"-"`
  114. Members []*User `xorm:"-"`
  115. // Preferences
  116. DiffViewStyle string `xorm:"NOT NULL DEFAULT ''"`
  117. Theme string `xorm:"NOT NULL DEFAULT ''"`
  118. }
  119. // BeforeUpdate is invoked from XORM before updating this object.
  120. func (u *User) BeforeUpdate() {
  121. if u.MaxRepoCreation < -1 {
  122. u.MaxRepoCreation = -1
  123. }
  124. // Organization does not need email
  125. u.Email = strings.ToLower(u.Email)
  126. if !u.IsOrganization() {
  127. if len(u.AvatarEmail) == 0 {
  128. u.AvatarEmail = u.Email
  129. }
  130. if len(u.AvatarEmail) > 0 && u.Avatar == "" {
  131. u.Avatar = base.HashEmail(u.AvatarEmail)
  132. }
  133. }
  134. u.LowerName = strings.ToLower(u.Name)
  135. u.Location = base.TruncateString(u.Location, 255)
  136. u.Website = base.TruncateString(u.Website, 255)
  137. u.Description = base.TruncateString(u.Description, 255)
  138. }
  139. // AfterLoad is invoked from XORM after filling all the fields of this object.
  140. func (u *User) AfterLoad() {
  141. if u.Theme == "" {
  142. u.Theme = setting.UI.DefaultTheme
  143. }
  144. }
  145. // SetLastLogin set time to last login
  146. func (u *User) SetLastLogin() {
  147. u.LastLoginUnix = util.TimeStampNow()
  148. }
  149. // UpdateDiffViewStyle updates the users diff view style
  150. func (u *User) UpdateDiffViewStyle(style string) error {
  151. u.DiffViewStyle = style
  152. return UpdateUserCols(u, "diff_view_style")
  153. }
  154. // UpdateTheme updates a users' theme irrespective of the site wide theme
  155. func (u *User) UpdateTheme(themeName string) error {
  156. u.Theme = themeName
  157. return UpdateUserCols(u, "theme")
  158. }
  159. // getEmail returns an noreply email, if the user has set to keep his
  160. // email address private, otherwise the primary email address.
  161. func (u *User) getEmail() string {
  162. if u.KeepEmailPrivate {
  163. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  164. }
  165. return u.Email
  166. }
  167. // APIFormat converts a User to api.User
  168. func (u *User) APIFormat() *api.User {
  169. return &api.User{
  170. ID: u.ID,
  171. UserName: u.Name,
  172. FullName: u.FullName,
  173. Email: u.getEmail(),
  174. AvatarURL: u.AvatarLink(),
  175. Language: u.Language,
  176. }
  177. }
  178. // IsLocal returns true if user login type is LoginPlain.
  179. func (u *User) IsLocal() bool {
  180. return u.LoginType <= LoginPlain
  181. }
  182. // IsOAuth2 returns true if user login type is LoginOAuth2.
  183. func (u *User) IsOAuth2() bool {
  184. return u.LoginType == LoginOAuth2
  185. }
  186. // HasForkedRepo checks if user has already forked a repository with given ID.
  187. func (u *User) HasForkedRepo(repoID int64) bool {
  188. _, has := HasForkedRepo(u.ID, repoID)
  189. return has
  190. }
  191. // MaxCreationLimit returns the number of repositories a user is allowed to create
  192. func (u *User) MaxCreationLimit() int {
  193. if u.MaxRepoCreation <= -1 {
  194. return setting.Repository.MaxCreationLimit
  195. }
  196. return u.MaxRepoCreation
  197. }
  198. // CanCreateRepo returns if user login can create a repository
  199. func (u *User) CanCreateRepo() bool {
  200. if u.IsAdmin {
  201. return true
  202. }
  203. if u.MaxRepoCreation <= -1 {
  204. if setting.Repository.MaxCreationLimit <= -1 {
  205. return true
  206. }
  207. return u.NumRepos < setting.Repository.MaxCreationLimit
  208. }
  209. return u.NumRepos < u.MaxRepoCreation
  210. }
  211. // CanCreateOrganization returns true if user can create organisation.
  212. func (u *User) CanCreateOrganization() bool {
  213. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  214. }
  215. // CanEditGitHook returns true if user can edit Git hooks.
  216. func (u *User) CanEditGitHook() bool {
  217. return !setting.DisableGitHooks && (u.IsAdmin || u.AllowGitHook)
  218. }
  219. // CanImportLocal returns true if user can migrate repository by local path.
  220. func (u *User) CanImportLocal() bool {
  221. if !setting.ImportLocalPaths {
  222. return false
  223. }
  224. return u.IsAdmin || u.AllowImportLocal
  225. }
  226. // DashboardLink returns the user dashboard page link.
  227. func (u *User) DashboardLink() string {
  228. if u.IsOrganization() {
  229. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  230. }
  231. return setting.AppSubURL + "/"
  232. }
  233. // HomeLink returns the user or organization home page link.
  234. func (u *User) HomeLink() string {
  235. return setting.AppSubURL + "/" + u.Name
  236. }
  237. // HTMLURL returns the user or organization's full link.
  238. func (u *User) HTMLURL() string {
  239. return setting.AppURL + u.Name
  240. }
  241. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  242. func (u *User) GenerateEmailActivateCode(email string) string {
  243. code := base.CreateTimeLimitCode(
  244. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  245. setting.Service.ActiveCodeLives, nil)
  246. // Add tail hex username
  247. code += hex.EncodeToString([]byte(u.LowerName))
  248. return code
  249. }
  250. // GenerateActivateCode generates an activate code based on user information.
  251. func (u *User) GenerateActivateCode() string {
  252. return u.GenerateEmailActivateCode(u.Email)
  253. }
  254. // CustomAvatarPath returns user custom avatar file path.
  255. func (u *User) CustomAvatarPath() string {
  256. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  257. }
  258. // GenerateRandomAvatar generates a random avatar for user.
  259. func (u *User) GenerateRandomAvatar() error {
  260. return u.generateRandomAvatar(x)
  261. }
  262. func (u *User) generateRandomAvatar(e Engine) error {
  263. seed := u.Email
  264. if len(seed) == 0 {
  265. seed = u.Name
  266. }
  267. img, err := avatar.RandomImage([]byte(seed))
  268. if err != nil {
  269. return fmt.Errorf("RandomImage: %v", err)
  270. }
  271. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  272. // since random image is not a user's photo, there is no security for enumable
  273. if u.Avatar == "" {
  274. u.Avatar = fmt.Sprintf("%d", u.ID)
  275. }
  276. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  277. return fmt.Errorf("MkdirAll: %v", err)
  278. }
  279. fw, err := os.Create(u.CustomAvatarPath())
  280. if err != nil {
  281. return fmt.Errorf("Create: %v", err)
  282. }
  283. defer fw.Close()
  284. if _, err := e.ID(u.ID).Cols("avatar").Update(u); err != nil {
  285. return err
  286. }
  287. if err = png.Encode(fw, img); err != nil {
  288. return fmt.Errorf("Encode: %v", err)
  289. }
  290. log.Info("New random avatar created: %d", u.ID)
  291. return nil
  292. }
  293. // SizedRelAvatarLink returns a relative link to the user's avatar. When
  294. // applicable, the link is for an avatar of the indicated size (in pixels).
  295. func (u *User) SizedRelAvatarLink(size int) string {
  296. if u.ID == -1 {
  297. return base.DefaultAvatarLink()
  298. }
  299. switch {
  300. case u.UseCustomAvatar:
  301. if !com.IsFile(u.CustomAvatarPath()) {
  302. return base.DefaultAvatarLink()
  303. }
  304. return setting.AppSubURL + "/avatars/" + u.Avatar
  305. case setting.DisableGravatar, setting.OfflineMode:
  306. if !com.IsFile(u.CustomAvatarPath()) {
  307. if err := u.GenerateRandomAvatar(); err != nil {
  308. log.Error(3, "GenerateRandomAvatar: %v", err)
  309. }
  310. }
  311. return setting.AppSubURL + "/avatars/" + u.Avatar
  312. }
  313. return base.SizedAvatarLink(u.AvatarEmail, size)
  314. }
  315. // RelAvatarLink returns a relative link to the user's avatar. The link
  316. // may either be a sub-URL to this site, or a full URL to an external avatar
  317. // service.
  318. func (u *User) RelAvatarLink() string {
  319. return u.SizedRelAvatarLink(base.DefaultAvatarSize)
  320. }
  321. // AvatarLink returns user avatar absolute link.
  322. func (u *User) AvatarLink() string {
  323. link := u.RelAvatarLink()
  324. if link[0] == '/' && link[1] != '/' {
  325. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  326. }
  327. return link
  328. }
  329. // GetFollowers returns range of user's followers.
  330. func (u *User) GetFollowers(page int) ([]*User, error) {
  331. users := make([]*User, 0, ItemsPerPage)
  332. sess := x.
  333. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  334. Where("follow.follow_id=?", u.ID).
  335. Join("LEFT", "follow", "`user`.id=follow.user_id")
  336. return users, sess.Find(&users)
  337. }
  338. // IsFollowing returns true if user is following followID.
  339. func (u *User) IsFollowing(followID int64) bool {
  340. return IsFollowing(u.ID, followID)
  341. }
  342. // GetFollowing returns range of user's following.
  343. func (u *User) GetFollowing(page int) ([]*User, error) {
  344. users := make([]*User, 0, ItemsPerPage)
  345. sess := x.
  346. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  347. Where("follow.user_id=?", u.ID).
  348. Join("LEFT", "follow", "`user`.id=follow.follow_id")
  349. return users, sess.Find(&users)
  350. }
  351. // NewGitSig generates and returns the signature of given user.
  352. func (u *User) NewGitSig() *git.Signature {
  353. return &git.Signature{
  354. Name: u.DisplayName(),
  355. Email: u.getEmail(),
  356. When: time.Now(),
  357. }
  358. }
  359. func hashPassword(passwd, salt string) string {
  360. tempPasswd := pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New)
  361. return fmt.Sprintf("%x", tempPasswd)
  362. }
  363. // HashPassword hashes a password using PBKDF.
  364. func (u *User) HashPassword(passwd string) {
  365. u.Passwd = hashPassword(passwd, u.Salt)
  366. }
  367. // ValidatePassword checks if given password matches the one belongs to the user.
  368. func (u *User) ValidatePassword(passwd string) bool {
  369. tempHash := hashPassword(passwd, u.Salt)
  370. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(tempHash)) == 1
  371. }
  372. // IsPasswordSet checks if the password is set or left empty
  373. func (u *User) IsPasswordSet() bool {
  374. return !u.ValidatePassword("")
  375. }
  376. // UploadAvatar saves custom avatar for user.
  377. // FIXME: split uploads to different subdirs in case we have massive users.
  378. func (u *User) UploadAvatar(data []byte) error {
  379. imgCfg, _, err := image.DecodeConfig(bytes.NewReader(data))
  380. if err != nil {
  381. return fmt.Errorf("DecodeConfig: %v", err)
  382. }
  383. if imgCfg.Width > setting.AvatarMaxWidth {
  384. return fmt.Errorf("Image width is to large: %d > %d", imgCfg.Width, setting.AvatarMaxWidth)
  385. }
  386. if imgCfg.Height > setting.AvatarMaxHeight {
  387. return fmt.Errorf("Image height is to large: %d > %d", imgCfg.Height, setting.AvatarMaxHeight)
  388. }
  389. img, _, err := image.Decode(bytes.NewReader(data))
  390. if err != nil {
  391. return fmt.Errorf("Decode: %v", err)
  392. }
  393. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  394. sess := x.NewSession()
  395. defer sess.Close()
  396. if err = sess.Begin(); err != nil {
  397. return err
  398. }
  399. u.UseCustomAvatar = true
  400. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  401. if err = updateUser(sess, u); err != nil {
  402. return fmt.Errorf("updateUser: %v", err)
  403. }
  404. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  405. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  406. }
  407. fw, err := os.Create(u.CustomAvatarPath())
  408. if err != nil {
  409. return fmt.Errorf("Create: %v", err)
  410. }
  411. defer fw.Close()
  412. if err = png.Encode(fw, m); err != nil {
  413. return fmt.Errorf("Encode: %v", err)
  414. }
  415. return sess.Commit()
  416. }
  417. // DeleteAvatar deletes the user's custom avatar.
  418. func (u *User) DeleteAvatar() error {
  419. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  420. if len(u.Avatar) > 0 {
  421. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  422. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  423. }
  424. }
  425. u.UseCustomAvatar = false
  426. u.Avatar = ""
  427. if _, err := x.ID(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  428. return fmt.Errorf("UpdateUser: %v", err)
  429. }
  430. return nil
  431. }
  432. // IsOrganization returns true if user is actually a organization.
  433. func (u *User) IsOrganization() bool {
  434. return u.Type == UserTypeOrganization
  435. }
  436. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  437. func (u *User) IsUserOrgOwner(orgID int64) bool {
  438. isOwner, err := IsOrganizationOwner(orgID, u.ID)
  439. if err != nil {
  440. log.Error(4, "IsOrganizationOwner: %v", err)
  441. return false
  442. }
  443. return isOwner
  444. }
  445. // IsPublicMember returns true if user public his/her membership in given organization.
  446. func (u *User) IsPublicMember(orgID int64) bool {
  447. isMember, err := IsPublicMembership(orgID, u.ID)
  448. if err != nil {
  449. log.Error(4, "IsPublicMembership: %v", err)
  450. return false
  451. }
  452. return isMember
  453. }
  454. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  455. return e.
  456. Where("uid=?", u.ID).
  457. Count(new(OrgUser))
  458. }
  459. // GetOrganizationCount returns count of membership of organization of user.
  460. func (u *User) GetOrganizationCount() (int64, error) {
  461. return u.getOrganizationCount(x)
  462. }
  463. // GetRepositories returns repositories that user owns, including private repositories.
  464. func (u *User) GetRepositories(page, pageSize int) (err error) {
  465. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  466. return err
  467. }
  468. // GetRepositoryIDs returns repositories IDs where user owned and has unittypes
  469. func (u *User) GetRepositoryIDs(units ...UnitType) ([]int64, error) {
  470. var ids []int64
  471. sess := x.Table("repository").Cols("repository.id")
  472. if len(units) > 0 {
  473. sess = sess.Join("INNER", "repo_unit", "repository.id = repo_unit.repo_id")
  474. sess = sess.In("repo_unit.type", units)
  475. }
  476. return ids, sess.Where("owner_id = ?", u.ID).Find(&ids)
  477. }
  478. // GetOrgRepositoryIDs returns repositories IDs where user's team owned and has unittypes
  479. func (u *User) GetOrgRepositoryIDs(units ...UnitType) ([]int64, error) {
  480. var ids []int64
  481. sess := x.Table("repository").
  482. Cols("repository.id").
  483. Join("INNER", "team_user", "repository.owner_id = team_user.org_id").
  484. Join("INNER", "team_repo", "repository.is_private != ? OR (team_user.team_id = team_repo.team_id AND repository.id = team_repo.repo_id)", true)
  485. if len(units) > 0 {
  486. sess = sess.Join("INNER", "team_unit", "team_unit.team_id = team_user.team_id")
  487. sess = sess.In("team_unit.type", units)
  488. }
  489. return ids, sess.
  490. Where("team_user.uid = ?", u.ID).
  491. GroupBy("repository.id").Find(&ids)
  492. }
  493. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  494. func (u *User) GetAccessRepoIDs(units ...UnitType) ([]int64, error) {
  495. ids, err := u.GetRepositoryIDs(units...)
  496. if err != nil {
  497. return nil, err
  498. }
  499. ids2, err := u.GetOrgRepositoryIDs(units...)
  500. if err != nil {
  501. return nil, err
  502. }
  503. return append(ids, ids2...), nil
  504. }
  505. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  506. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  507. return GetUserMirrorRepositories(u.ID)
  508. }
  509. // GetOwnedOrganizations returns all organizations that user owns.
  510. func (u *User) GetOwnedOrganizations() (err error) {
  511. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  512. return err
  513. }
  514. // GetOrganizations returns all organizations that user belongs to.
  515. func (u *User) GetOrganizations(all bool) error {
  516. ous, err := GetOrgUsersByUserID(u.ID, all)
  517. if err != nil {
  518. return err
  519. }
  520. u.Orgs = make([]*User, len(ous))
  521. for i, ou := range ous {
  522. u.Orgs[i], err = GetUserByID(ou.OrgID)
  523. if err != nil {
  524. return err
  525. }
  526. }
  527. return nil
  528. }
  529. // DisplayName returns full name if it's not empty,
  530. // returns username otherwise.
  531. func (u *User) DisplayName() string {
  532. if len(u.FullName) > 0 {
  533. return u.FullName
  534. }
  535. return u.Name
  536. }
  537. // ShortName ellipses username to length
  538. func (u *User) ShortName(length int) string {
  539. return base.EllipsisString(u.Name, length)
  540. }
  541. // IsMailable checks if a user is eligible
  542. // to receive emails.
  543. func (u *User) IsMailable() bool {
  544. return u.IsActive
  545. }
  546. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  547. if len(name) == 0 {
  548. return false, nil
  549. }
  550. return e.
  551. Where("id!=?", uid).
  552. Get(&User{LowerName: strings.ToLower(name)})
  553. }
  554. // IsUserExist checks if given user name exist,
  555. // the user name should be noncased unique.
  556. // If uid is presented, then check will rule out that one,
  557. // it is used when update a user name in settings page.
  558. func IsUserExist(uid int64, name string) (bool, error) {
  559. return isUserExist(x, uid, name)
  560. }
  561. // GetUserSalt returns a random user salt token.
  562. func GetUserSalt() (string, error) {
  563. return generate.GetRandomString(10)
  564. }
  565. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  566. func NewGhostUser() *User {
  567. return &User{
  568. ID: -1,
  569. Name: "Ghost",
  570. LowerName: "ghost",
  571. }
  572. }
  573. var (
  574. reservedUsernames = []string{
  575. "admin",
  576. "api",
  577. "assets",
  578. "avatars",
  579. "commits",
  580. "css",
  581. "debug",
  582. "error",
  583. "explore",
  584. "help",
  585. "img",
  586. "install",
  587. "issues",
  588. "js",
  589. "less",
  590. "metrics",
  591. "new",
  592. "org",
  593. "plugins",
  594. "pulls",
  595. "raw",
  596. "repo",
  597. "stars",
  598. "template",
  599. "user",
  600. "vendor",
  601. ".",
  602. "..",
  603. }
  604. reservedUserPatterns = []string{"*.keys"}
  605. )
  606. // isUsableName checks if name is reserved or pattern of name is not allowed
  607. // based on given reserved names and patterns.
  608. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  609. func isUsableName(names, patterns []string, name string) error {
  610. name = strings.TrimSpace(strings.ToLower(name))
  611. if utf8.RuneCountInString(name) == 0 {
  612. return ErrNameEmpty
  613. }
  614. for i := range names {
  615. if name == names[i] {
  616. return ErrNameReserved{name}
  617. }
  618. }
  619. for _, pat := range patterns {
  620. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  621. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  622. return ErrNamePatternNotAllowed{pat}
  623. }
  624. }
  625. return nil
  626. }
  627. // IsUsableUsername returns an error when a username is reserved
  628. func IsUsableUsername(name string) error {
  629. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  630. }
  631. // CreateUser creates record of a new user.
  632. func CreateUser(u *User) (err error) {
  633. if err = IsUsableUsername(u.Name); err != nil {
  634. return err
  635. }
  636. sess := x.NewSession()
  637. defer sess.Close()
  638. if err = sess.Begin(); err != nil {
  639. return err
  640. }
  641. isExist, err := isUserExist(sess, 0, u.Name)
  642. if err != nil {
  643. return err
  644. } else if isExist {
  645. return ErrUserAlreadyExist{u.Name}
  646. }
  647. u.Email = strings.ToLower(u.Email)
  648. isExist, err = sess.
  649. Where("email=?", u.Email).
  650. Get(new(User))
  651. if err != nil {
  652. return err
  653. } else if isExist {
  654. return ErrEmailAlreadyUsed{u.Email}
  655. }
  656. isExist, err = isEmailUsed(sess, u.Email)
  657. if err != nil {
  658. return err
  659. } else if isExist {
  660. return ErrEmailAlreadyUsed{u.Email}
  661. }
  662. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  663. u.LowerName = strings.ToLower(u.Name)
  664. u.AvatarEmail = u.Email
  665. u.Avatar = base.HashEmail(u.AvatarEmail)
  666. if u.Rands, err = GetUserSalt(); err != nil {
  667. return err
  668. }
  669. if u.Salt, err = GetUserSalt(); err != nil {
  670. return err
  671. }
  672. u.HashPassword(u.Passwd)
  673. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  674. u.MaxRepoCreation = -1
  675. u.Theme = setting.UI.DefaultTheme
  676. if _, err = sess.Insert(u); err != nil {
  677. return err
  678. }
  679. return sess.Commit()
  680. }
  681. func countUsers(e Engine) int64 {
  682. count, _ := e.
  683. Where("type=0").
  684. Count(new(User))
  685. return count
  686. }
  687. // CountUsers returns number of users.
  688. func CountUsers() int64 {
  689. return countUsers(x)
  690. }
  691. // get user by verify code
  692. func getVerifyUser(code string) (user *User) {
  693. if len(code) <= base.TimeLimitCodeLength {
  694. return nil
  695. }
  696. // use tail hex username query user
  697. hexStr := code[base.TimeLimitCodeLength:]
  698. if b, err := hex.DecodeString(hexStr); err == nil {
  699. if user, err = GetUserByName(string(b)); user != nil {
  700. return user
  701. }
  702. log.Error(4, "user.getVerifyUser: %v", err)
  703. }
  704. return nil
  705. }
  706. // VerifyUserActiveCode verifies active code when active account
  707. func VerifyUserActiveCode(code string) (user *User) {
  708. minutes := setting.Service.ActiveCodeLives
  709. if user = getVerifyUser(code); user != nil {
  710. // time limit code
  711. prefix := code[:base.TimeLimitCodeLength]
  712. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  713. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  714. return user
  715. }
  716. }
  717. return nil
  718. }
  719. // VerifyActiveEmailCode verifies active email code when active account
  720. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  721. minutes := setting.Service.ActiveCodeLives
  722. if user := getVerifyUser(code); user != nil {
  723. // time limit code
  724. prefix := code[:base.TimeLimitCodeLength]
  725. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  726. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  727. emailAddress := &EmailAddress{Email: email}
  728. if has, _ := x.Get(emailAddress); has {
  729. return emailAddress
  730. }
  731. }
  732. }
  733. return nil
  734. }
  735. // ChangeUserName changes all corresponding setting from old user name to new one.
  736. func ChangeUserName(u *User, newUserName string) (err error) {
  737. if err = IsUsableUsername(newUserName); err != nil {
  738. return err
  739. }
  740. isExist, err := IsUserExist(0, newUserName)
  741. if err != nil {
  742. return err
  743. } else if isExist {
  744. return ErrUserAlreadyExist{newUserName}
  745. }
  746. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  747. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  748. }
  749. // Delete all local copies of repository wiki that user owns.
  750. if err = x.BufferSize(setting.IterateBufferSize).
  751. Where("owner_id=?", u.ID).
  752. Iterate(new(Repository), func(idx int, bean interface{}) error {
  753. repo := bean.(*Repository)
  754. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  755. return nil
  756. }); err != nil {
  757. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  758. }
  759. // Do not fail if directory does not exist
  760. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  761. return fmt.Errorf("Rename user directory: %v", err)
  762. }
  763. return nil
  764. }
  765. // checkDupEmail checks whether there are the same email with the user
  766. func checkDupEmail(e Engine, u *User) error {
  767. u.Email = strings.ToLower(u.Email)
  768. has, err := e.
  769. Where("id!=?", u.ID).
  770. And("type=?", u.Type).
  771. And("email=?", u.Email).
  772. Get(new(User))
  773. if err != nil {
  774. return err
  775. } else if has {
  776. return ErrEmailAlreadyUsed{u.Email}
  777. }
  778. return nil
  779. }
  780. func updateUser(e Engine, u *User) error {
  781. _, err := e.ID(u.ID).AllCols().Update(u)
  782. return err
  783. }
  784. // UpdateUser updates user's information.
  785. func UpdateUser(u *User) error {
  786. return updateUser(x, u)
  787. }
  788. // UpdateUserCols update user according special columns
  789. func UpdateUserCols(u *User, cols ...string) error {
  790. return updateUserCols(x, u, cols...)
  791. }
  792. func updateUserCols(e Engine, u *User, cols ...string) error {
  793. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  794. return err
  795. }
  796. // UpdateUserSetting updates user's settings.
  797. func UpdateUserSetting(u *User) error {
  798. if !u.IsOrganization() {
  799. if err := checkDupEmail(x, u); err != nil {
  800. return err
  801. }
  802. }
  803. return updateUser(x, u)
  804. }
  805. // deleteBeans deletes all given beans, beans should contain delete conditions.
  806. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  807. for i := range beans {
  808. if _, err = e.Delete(beans[i]); err != nil {
  809. return err
  810. }
  811. }
  812. return nil
  813. }
  814. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  815. func deleteUser(e *xorm.Session, u *User) error {
  816. // Note: A user owns any repository or belongs to any organization
  817. // cannot perform delete operation.
  818. // Check ownership of repository.
  819. count, err := getRepositoryCount(e, u)
  820. if err != nil {
  821. return fmt.Errorf("GetRepositoryCount: %v", err)
  822. } else if count > 0 {
  823. return ErrUserOwnRepos{UID: u.ID}
  824. }
  825. // Check membership of organization.
  826. count, err = u.getOrganizationCount(e)
  827. if err != nil {
  828. return fmt.Errorf("GetOrganizationCount: %v", err)
  829. } else if count > 0 {
  830. return ErrUserHasOrgs{UID: u.ID}
  831. }
  832. // ***** START: Watch *****
  833. watchedRepoIDs := make([]int64, 0, 10)
  834. if err = e.Table("watch").Cols("watch.repo_id").
  835. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  836. return fmt.Errorf("get all watches: %v", err)
  837. }
  838. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  839. return fmt.Errorf("decrease repository num_watches: %v", err)
  840. }
  841. // ***** END: Watch *****
  842. // ***** START: Star *****
  843. starredRepoIDs := make([]int64, 0, 10)
  844. if err = e.Table("star").Cols("star.repo_id").
  845. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  846. return fmt.Errorf("get all stars: %v", err)
  847. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  848. return fmt.Errorf("decrease repository num_stars: %v", err)
  849. }
  850. // ***** END: Star *****
  851. // ***** START: Follow *****
  852. followeeIDs := make([]int64, 0, 10)
  853. if err = e.Table("follow").Cols("follow.follow_id").
  854. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  855. return fmt.Errorf("get all followees: %v", err)
  856. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  857. return fmt.Errorf("decrease user num_followers: %v", err)
  858. }
  859. followerIDs := make([]int64, 0, 10)
  860. if err = e.Table("follow").Cols("follow.user_id").
  861. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  862. return fmt.Errorf("get all followers: %v", err)
  863. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  864. return fmt.Errorf("decrease user num_following: %v", err)
  865. }
  866. // ***** END: Follow *****
  867. if err = deleteBeans(e,
  868. &AccessToken{UID: u.ID},
  869. &Collaboration{UserID: u.ID},
  870. &Access{UserID: u.ID},
  871. &Watch{UserID: u.ID},
  872. &Star{UID: u.ID},
  873. &Follow{UserID: u.ID},
  874. &Follow{FollowID: u.ID},
  875. &Action{UserID: u.ID},
  876. &IssueUser{UID: u.ID},
  877. &EmailAddress{UID: u.ID},
  878. &UserOpenID{UID: u.ID},
  879. &Reaction{UserID: u.ID},
  880. &TeamUser{UID: u.ID},
  881. &Collaboration{UserID: u.ID},
  882. &Stopwatch{UserID: u.ID},
  883. ); err != nil {
  884. return fmt.Errorf("deleteBeans: %v", err)
  885. }
  886. // ***** START: PublicKey *****
  887. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  888. return fmt.Errorf("deletePublicKeys: %v", err)
  889. }
  890. rewriteAllPublicKeys(e)
  891. // ***** END: PublicKey *****
  892. // ***** START: GPGPublicKey *****
  893. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  894. return fmt.Errorf("deleteGPGKeys: %v", err)
  895. }
  896. // ***** END: GPGPublicKey *****
  897. // Clear assignee.
  898. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  899. return fmt.Errorf("clear assignee: %v", err)
  900. }
  901. // ***** START: ExternalLoginUser *****
  902. if err = removeAllAccountLinks(e, u); err != nil {
  903. return fmt.Errorf("ExternalLoginUser: %v", err)
  904. }
  905. // ***** END: ExternalLoginUser *****
  906. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  907. return fmt.Errorf("Delete: %v", err)
  908. }
  909. // FIXME: system notice
  910. // Note: There are something just cannot be roll back,
  911. // so just keep error logs of those operations.
  912. path := UserPath(u.Name)
  913. if err := os.RemoveAll(path); err != nil {
  914. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  915. }
  916. if len(u.Avatar) > 0 {
  917. avatarPath := u.CustomAvatarPath()
  918. if com.IsExist(avatarPath) {
  919. if err := os.Remove(avatarPath); err != nil {
  920. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  921. }
  922. }
  923. }
  924. return nil
  925. }
  926. // DeleteUser completely and permanently deletes everything of a user,
  927. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  928. func DeleteUser(u *User) (err error) {
  929. sess := x.NewSession()
  930. defer sess.Close()
  931. if err = sess.Begin(); err != nil {
  932. return err
  933. }
  934. if err = deleteUser(sess, u); err != nil {
  935. // Note: don't wrapper error here.
  936. return err
  937. }
  938. return sess.Commit()
  939. }
  940. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  941. func DeleteInactivateUsers() (err error) {
  942. users := make([]*User, 0, 10)
  943. if err = x.
  944. Where("is_active = ?", false).
  945. Find(&users); err != nil {
  946. return fmt.Errorf("get all inactive users: %v", err)
  947. }
  948. // FIXME: should only update authorized_keys file once after all deletions.
  949. for _, u := range users {
  950. if err = DeleteUser(u); err != nil {
  951. // Ignore users that were set inactive by admin.
  952. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  953. continue
  954. }
  955. return err
  956. }
  957. }
  958. _, err = x.
  959. Where("is_activated = ?", false).
  960. Delete(new(EmailAddress))
  961. return err
  962. }
  963. // UserPath returns the path absolute path of user repositories.
  964. func UserPath(userName string) string {
  965. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  966. }
  967. // GetUserByKeyID get user information by user's public key id
  968. func GetUserByKeyID(keyID int64) (*User, error) {
  969. var user User
  970. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  971. Where("`public_key`.id=?", keyID).
  972. Get(&user)
  973. if err != nil {
  974. return nil, err
  975. }
  976. if !has {
  977. return nil, ErrUserNotExist{0, "", keyID}
  978. }
  979. return &user, nil
  980. }
  981. func getUserByID(e Engine, id int64) (*User, error) {
  982. u := new(User)
  983. has, err := e.ID(id).Get(u)
  984. if err != nil {
  985. return nil, err
  986. } else if !has {
  987. return nil, ErrUserNotExist{id, "", 0}
  988. }
  989. return u, nil
  990. }
  991. // GetUserByID returns the user object by given ID if exists.
  992. func GetUserByID(id int64) (*User, error) {
  993. return getUserByID(x, id)
  994. }
  995. // GetUserByName returns user by given name.
  996. func GetUserByName(name string) (*User, error) {
  997. return getUserByName(x, name)
  998. }
  999. func getUserByName(e Engine, name string) (*User, error) {
  1000. if len(name) == 0 {
  1001. return nil, ErrUserNotExist{0, name, 0}
  1002. }
  1003. u := &User{LowerName: strings.ToLower(name)}
  1004. has, err := e.Get(u)
  1005. if err != nil {
  1006. return nil, err
  1007. } else if !has {
  1008. return nil, ErrUserNotExist{0, name, 0}
  1009. }
  1010. return u, nil
  1011. }
  1012. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  1013. func GetUserEmailsByNames(names []string) []string {
  1014. return getUserEmailsByNames(x, names)
  1015. }
  1016. func getUserEmailsByNames(e Engine, names []string) []string {
  1017. mails := make([]string, 0, len(names))
  1018. for _, name := range names {
  1019. u, err := getUserByName(e, name)
  1020. if err != nil {
  1021. continue
  1022. }
  1023. if u.IsMailable() {
  1024. mails = append(mails, u.Email)
  1025. }
  1026. }
  1027. return mails
  1028. }
  1029. // GetUsersByIDs returns all resolved users from a list of Ids.
  1030. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1031. ous := make([]*User, 0, len(ids))
  1032. if len(ids) == 0 {
  1033. return ous, nil
  1034. }
  1035. err := x.In("id", ids).
  1036. Asc("name").
  1037. Find(&ous)
  1038. return ous, err
  1039. }
  1040. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1041. func GetUserIDsByNames(names []string) []int64 {
  1042. ids := make([]int64, 0, len(names))
  1043. for _, name := range names {
  1044. u, err := GetUserByName(name)
  1045. if err != nil {
  1046. continue
  1047. }
  1048. ids = append(ids, u.ID)
  1049. }
  1050. return ids
  1051. }
  1052. // UserCommit represents a commit with validation of user.
  1053. type UserCommit struct {
  1054. User *User
  1055. *git.Commit
  1056. }
  1057. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1058. func ValidateCommitWithEmail(c *git.Commit) *User {
  1059. if c.Author == nil {
  1060. return nil
  1061. }
  1062. u, err := GetUserByEmail(c.Author.Email)
  1063. if err != nil {
  1064. return nil
  1065. }
  1066. return u
  1067. }
  1068. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1069. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1070. var (
  1071. u *User
  1072. emails = map[string]*User{}
  1073. newCommits = list.New()
  1074. e = oldCommits.Front()
  1075. )
  1076. for e != nil {
  1077. c := e.Value.(*git.Commit)
  1078. if c.Author != nil {
  1079. if v, ok := emails[c.Author.Email]; !ok {
  1080. u, _ = GetUserByEmail(c.Author.Email)
  1081. emails[c.Author.Email] = u
  1082. } else {
  1083. u = v
  1084. }
  1085. } else {
  1086. u = nil
  1087. }
  1088. newCommits.PushBack(UserCommit{
  1089. User: u,
  1090. Commit: c,
  1091. })
  1092. e = e.Next()
  1093. }
  1094. return newCommits
  1095. }
  1096. // GetUserByEmail returns the user object by given e-mail if exists.
  1097. func GetUserByEmail(email string) (*User, error) {
  1098. if len(email) == 0 {
  1099. return nil, ErrUserNotExist{0, email, 0}
  1100. }
  1101. email = strings.ToLower(email)
  1102. // First try to find the user by primary email
  1103. user := &User{Email: email}
  1104. has, err := x.Get(user)
  1105. if err != nil {
  1106. return nil, err
  1107. }
  1108. if has {
  1109. return user, nil
  1110. }
  1111. // Otherwise, check in alternative list for activated email addresses
  1112. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1113. has, err = x.Get(emailAddress)
  1114. if err != nil {
  1115. return nil, err
  1116. }
  1117. if has {
  1118. return GetUserByID(emailAddress.UID)
  1119. }
  1120. return nil, ErrUserNotExist{0, email, 0}
  1121. }
  1122. // GetUser checks if a user already exists
  1123. func GetUser(user *User) (bool, error) {
  1124. return x.Get(user)
  1125. }
  1126. // SearchUserOptions contains the options for searching
  1127. type SearchUserOptions struct {
  1128. Keyword string
  1129. Type UserType
  1130. UID int64
  1131. OrderBy SearchOrderBy
  1132. Page int
  1133. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1134. IsActive util.OptionalBool
  1135. SearchByEmail bool // Search by email as well as username/full name
  1136. }
  1137. func (opts *SearchUserOptions) toConds() builder.Cond {
  1138. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1139. if len(opts.Keyword) > 0 {
  1140. lowerKeyword := strings.ToLower(opts.Keyword)
  1141. keywordCond := builder.Or(
  1142. builder.Like{"lower_name", lowerKeyword},
  1143. builder.Like{"LOWER(full_name)", lowerKeyword},
  1144. )
  1145. if opts.SearchByEmail {
  1146. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1147. }
  1148. cond = cond.And(keywordCond)
  1149. }
  1150. if opts.UID > 0 {
  1151. cond = cond.And(builder.Eq{"id": opts.UID})
  1152. }
  1153. if !opts.IsActive.IsNone() {
  1154. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1155. }
  1156. return cond
  1157. }
  1158. // SearchUsers takes options i.e. keyword and part of user name to search,
  1159. // it returns results in given range and number of total results.
  1160. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1161. cond := opts.toConds()
  1162. count, err := x.Where(cond).Count(new(User))
  1163. if err != nil {
  1164. return nil, 0, fmt.Errorf("Count: %v", err)
  1165. }
  1166. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1167. opts.PageSize = setting.UI.ExplorePagingNum
  1168. }
  1169. if opts.Page <= 0 {
  1170. opts.Page = 1
  1171. }
  1172. if len(opts.OrderBy) == 0 {
  1173. opts.OrderBy = SearchOrderByAlphabetically
  1174. }
  1175. users = make([]*User, 0, opts.PageSize)
  1176. return users, count, x.Where(cond).
  1177. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  1178. OrderBy(opts.OrderBy.String()).
  1179. Find(&users)
  1180. }
  1181. // GetStarredRepos returns the repos starred by a particular user
  1182. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1183. sess := x.Where("star.uid=?", userID).
  1184. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1185. if !private {
  1186. sess = sess.And("is_private=?", false)
  1187. }
  1188. repos := make([]*Repository, 0, 10)
  1189. err := sess.Find(&repos)
  1190. if err != nil {
  1191. return nil, err
  1192. }
  1193. return repos, nil
  1194. }
  1195. // GetWatchedRepos returns the repos watched by a particular user
  1196. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1197. sess := x.Where("watch.user_id=?", userID).
  1198. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1199. if !private {
  1200. sess = sess.And("is_private=?", false)
  1201. }
  1202. repos := make([]*Repository, 0, 10)
  1203. err := sess.Find(&repos)
  1204. if err != nil {
  1205. return nil, err
  1206. }
  1207. return repos, nil
  1208. }
  1209. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1210. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1211. // Start session
  1212. sess := x.NewSession()
  1213. defer sess.Close()
  1214. if err := sess.Begin(); err != nil {
  1215. return false, err
  1216. }
  1217. // Delete keys marked for deletion
  1218. var sshKeysNeedUpdate bool
  1219. for _, KeyToDelete := range keys {
  1220. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1221. if err != nil {
  1222. log.Error(4, "SearchPublicKeyByContent: %v", err)
  1223. continue
  1224. }
  1225. if err = deletePublicKeys(sess, key.ID); err != nil {
  1226. log.Error(4, "deletePublicKeys: %v", err)
  1227. continue
  1228. }
  1229. sshKeysNeedUpdate = true
  1230. }
  1231. if err := sess.Commit(); err != nil {
  1232. return false, err
  1233. }
  1234. return sshKeysNeedUpdate, nil
  1235. }
  1236. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1237. func addLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) bool {
  1238. var sshKeysNeedUpdate bool
  1239. for _, sshKey := range SSHPublicKeys {
  1240. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1241. if err == nil {
  1242. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1243. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1244. log.Error(4, "addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1245. } else {
  1246. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1247. sshKeysNeedUpdate = true
  1248. }
  1249. } else {
  1250. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1251. }
  1252. }
  1253. return sshKeysNeedUpdate
  1254. }
  1255. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1256. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) bool {
  1257. var sshKeysNeedUpdate bool
  1258. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1259. // Get Public Keys from DB with current LDAP source
  1260. var giteaKeys []string
  1261. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1262. if err != nil {
  1263. log.Error(4, "synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1264. }
  1265. for _, v := range keys {
  1266. giteaKeys = append(giteaKeys, v.OmitEmail())
  1267. }
  1268. // Get Public Keys from LDAP and skip duplicate keys
  1269. var ldapKeys []string
  1270. for _, v := range SSHPublicKeys {
  1271. ldapKey := strings.Join(strings.Split(v, " ")[:2], " ")
  1272. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1273. ldapKeys = append(ldapKeys, ldapKey)
  1274. }
  1275. }
  1276. // Check if Public Key sync is needed
  1277. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1278. 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))
  1279. return false
  1280. }
  1281. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1282. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1283. var newLdapSSHKeys []string
  1284. for _, LDAPPublicSSHKey := range ldapKeys {
  1285. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1286. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1287. }
  1288. }
  1289. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1290. sshKeysNeedUpdate = true
  1291. }
  1292. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1293. var giteaKeysToDelete []string
  1294. for _, giteaKey := range giteaKeys {
  1295. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1296. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1297. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1298. }
  1299. }
  1300. // Delete LDAP keys from DB that doesn't exist in LDAP
  1301. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1302. if err != nil {
  1303. log.Error(4, "synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1304. }
  1305. if needUpd {
  1306. sshKeysNeedUpdate = true
  1307. }
  1308. return sshKeysNeedUpdate
  1309. }
  1310. // SyncExternalUsers is used to synchronize users with external authorization source
  1311. func SyncExternalUsers() {
  1312. if !taskStatusTable.StartIfNotRunning(syncExternalUsers) {
  1313. return
  1314. }
  1315. defer taskStatusTable.Stop(syncExternalUsers)
  1316. log.Trace("Doing: SyncExternalUsers")
  1317. ls, err := LoginSources()
  1318. if err != nil {
  1319. log.Error(4, "SyncExternalUsers: %v", err)
  1320. return
  1321. }
  1322. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1323. for _, s := range ls {
  1324. if !s.IsActived || !s.IsSyncEnabled {
  1325. continue
  1326. }
  1327. if s.IsLDAP() {
  1328. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1329. var existingUsers []int64
  1330. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1331. var sshKeysNeedUpdate bool
  1332. // Find all users with this login type
  1333. var users []User
  1334. x.Where("login_type = ?", LoginLDAP).
  1335. And("login_source = ?", s.ID).
  1336. Find(&users)
  1337. sr := s.LDAP().SearchEntries()
  1338. for _, su := range sr {
  1339. if len(su.Username) == 0 {
  1340. continue
  1341. }
  1342. if len(su.Mail) == 0 {
  1343. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1344. }
  1345. var usr *User
  1346. // Search for existing user
  1347. for _, du := range users {
  1348. if du.LowerName == strings.ToLower(su.Username) {
  1349. usr = &du
  1350. break
  1351. }
  1352. }
  1353. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1354. // If no existing user found, create one
  1355. if usr == nil {
  1356. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1357. usr = &User{
  1358. LowerName: strings.ToLower(su.Username),
  1359. Name: su.Username,
  1360. FullName: fullName,
  1361. LoginType: s.Type,
  1362. LoginSource: s.ID,
  1363. LoginName: su.Username,
  1364. Email: su.Mail,
  1365. IsAdmin: su.IsAdmin,
  1366. IsActive: true,
  1367. }
  1368. err = CreateUser(usr)
  1369. if err != nil {
  1370. log.Error(4, "SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1371. } else if isAttributeSSHPublicKeySet {
  1372. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1373. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1374. sshKeysNeedUpdate = true
  1375. }
  1376. }
  1377. } else if updateExisting {
  1378. existingUsers = append(existingUsers, usr.ID)
  1379. // Synchronize SSH Public Key if that attribute is set
  1380. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1381. sshKeysNeedUpdate = true
  1382. }
  1383. // Check if user data has changed
  1384. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1385. strings.ToLower(usr.Email) != strings.ToLower(su.Mail) ||
  1386. usr.FullName != fullName ||
  1387. !usr.IsActive {
  1388. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1389. usr.FullName = fullName
  1390. usr.Email = su.Mail
  1391. // Change existing admin flag only if AdminFilter option is set
  1392. if len(s.LDAP().AdminFilter) > 0 {
  1393. usr.IsAdmin = su.IsAdmin
  1394. }
  1395. usr.IsActive = true
  1396. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1397. if err != nil {
  1398. log.Error(4, "SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1399. }
  1400. }
  1401. }
  1402. }
  1403. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1404. if sshKeysNeedUpdate {
  1405. RewriteAllPublicKeys()
  1406. }
  1407. // Deactivate users not present in LDAP
  1408. if updateExisting {
  1409. for _, usr := range users {
  1410. found := false
  1411. for _, uid := range existingUsers {
  1412. if usr.ID == uid {
  1413. found = true
  1414. break
  1415. }
  1416. }
  1417. if !found {
  1418. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1419. usr.IsActive = false
  1420. err = UpdateUserCols(&usr, "is_active")
  1421. if err != nil {
  1422. log.Error(4, "SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. }
  1429. }