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