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 47 kB

11 years ago
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  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.GitName(),
  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. trimmed := strings.TrimSpace(u.FullName)
  534. if len(trimmed) > 0 {
  535. return trimmed
  536. }
  537. return u.Name
  538. }
  539. func gitSafeName(name string) string {
  540. return strings.TrimSpace(strings.NewReplacer("\n", "", "<", "", ">", "").Replace(name))
  541. }
  542. // GitName returns a git safe name
  543. func (u *User) GitName() string {
  544. gitName := gitSafeName(u.FullName)
  545. if len(gitName) > 0 {
  546. return gitName
  547. }
  548. // Although u.Name should be safe if created in our system
  549. // LDAP users may have bad names
  550. gitName = gitSafeName(u.Name)
  551. if len(gitName) > 0 {
  552. return gitName
  553. }
  554. // Totally pathological name so it's got to be:
  555. return fmt.Sprintf("user-%d", u.ID)
  556. }
  557. // ShortName ellipses username to length
  558. func (u *User) ShortName(length int) string {
  559. return base.EllipsisString(u.Name, length)
  560. }
  561. // IsMailable checks if a user is eligible
  562. // to receive emails.
  563. func (u *User) IsMailable() bool {
  564. return u.IsActive
  565. }
  566. func isUserExist(e Engine, uid int64, name string) (bool, error) {
  567. if len(name) == 0 {
  568. return false, nil
  569. }
  570. return e.
  571. Where("id!=?", uid).
  572. Get(&User{LowerName: strings.ToLower(name)})
  573. }
  574. // IsUserExist checks if given user name exist,
  575. // the user name should be noncased unique.
  576. // If uid is presented, then check will rule out that one,
  577. // it is used when update a user name in settings page.
  578. func IsUserExist(uid int64, name string) (bool, error) {
  579. return isUserExist(x, uid, name)
  580. }
  581. // GetUserSalt returns a random user salt token.
  582. func GetUserSalt() (string, error) {
  583. return generate.GetRandomString(10)
  584. }
  585. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  586. func NewGhostUser() *User {
  587. return &User{
  588. ID: -1,
  589. Name: "Ghost",
  590. LowerName: "ghost",
  591. }
  592. }
  593. var (
  594. reservedUsernames = []string{
  595. "admin",
  596. "api",
  597. "assets",
  598. "avatars",
  599. "commits",
  600. "css",
  601. "debug",
  602. "error",
  603. "explore",
  604. "help",
  605. "img",
  606. "install",
  607. "issues",
  608. "js",
  609. "less",
  610. "metrics",
  611. "new",
  612. "org",
  613. "plugins",
  614. "pulls",
  615. "raw",
  616. "repo",
  617. "stars",
  618. "template",
  619. "user",
  620. "vendor",
  621. ".",
  622. "..",
  623. }
  624. reservedUserPatterns = []string{"*.keys"}
  625. )
  626. // isUsableName checks if name is reserved or pattern of name is not allowed
  627. // based on given reserved names and patterns.
  628. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  629. func isUsableName(names, patterns []string, name string) error {
  630. name = strings.TrimSpace(strings.ToLower(name))
  631. if utf8.RuneCountInString(name) == 0 {
  632. return ErrNameEmpty
  633. }
  634. for i := range names {
  635. if name == names[i] {
  636. return ErrNameReserved{name}
  637. }
  638. }
  639. for _, pat := range patterns {
  640. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  641. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  642. return ErrNamePatternNotAllowed{pat}
  643. }
  644. }
  645. return nil
  646. }
  647. // IsUsableUsername returns an error when a username is reserved
  648. func IsUsableUsername(name string) error {
  649. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  650. }
  651. // CreateUser creates record of a new user.
  652. func CreateUser(u *User) (err error) {
  653. if err = IsUsableUsername(u.Name); err != nil {
  654. return err
  655. }
  656. sess := x.NewSession()
  657. defer sess.Close()
  658. if err = sess.Begin(); err != nil {
  659. return err
  660. }
  661. isExist, err := isUserExist(sess, 0, u.Name)
  662. if err != nil {
  663. return err
  664. } else if isExist {
  665. return ErrUserAlreadyExist{u.Name}
  666. }
  667. u.Email = strings.ToLower(u.Email)
  668. isExist, err = sess.
  669. Where("email=?", u.Email).
  670. Get(new(User))
  671. if err != nil {
  672. return err
  673. } else if isExist {
  674. return ErrEmailAlreadyUsed{u.Email}
  675. }
  676. isExist, err = isEmailUsed(sess, u.Email)
  677. if err != nil {
  678. return err
  679. } else if isExist {
  680. return ErrEmailAlreadyUsed{u.Email}
  681. }
  682. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  683. u.LowerName = strings.ToLower(u.Name)
  684. u.AvatarEmail = u.Email
  685. u.Avatar = base.HashEmail(u.AvatarEmail)
  686. if u.Rands, err = GetUserSalt(); err != nil {
  687. return err
  688. }
  689. if u.Salt, err = GetUserSalt(); err != nil {
  690. return err
  691. }
  692. u.HashPassword(u.Passwd)
  693. u.AllowCreateOrganization = setting.Service.DefaultAllowCreateOrganization
  694. u.MaxRepoCreation = -1
  695. u.Theme = setting.UI.DefaultTheme
  696. if _, err = sess.Insert(u); err != nil {
  697. return err
  698. }
  699. return sess.Commit()
  700. }
  701. func countUsers(e Engine) int64 {
  702. count, _ := e.
  703. Where("type=0").
  704. Count(new(User))
  705. return count
  706. }
  707. // CountUsers returns number of users.
  708. func CountUsers() int64 {
  709. return countUsers(x)
  710. }
  711. // get user by verify code
  712. func getVerifyUser(code string) (user *User) {
  713. if len(code) <= base.TimeLimitCodeLength {
  714. return nil
  715. }
  716. // use tail hex username query user
  717. hexStr := code[base.TimeLimitCodeLength:]
  718. if b, err := hex.DecodeString(hexStr); err == nil {
  719. if user, err = GetUserByName(string(b)); user != nil {
  720. return user
  721. }
  722. log.Error(4, "user.getVerifyUser: %v", err)
  723. }
  724. return nil
  725. }
  726. // VerifyUserActiveCode verifies active code when active account
  727. func VerifyUserActiveCode(code string) (user *User) {
  728. minutes := setting.Service.ActiveCodeLives
  729. if user = getVerifyUser(code); user != nil {
  730. // time limit code
  731. prefix := code[:base.TimeLimitCodeLength]
  732. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  733. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  734. return user
  735. }
  736. }
  737. return nil
  738. }
  739. // VerifyActiveEmailCode verifies active email code when active account
  740. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  741. minutes := setting.Service.ActiveCodeLives
  742. if user := getVerifyUser(code); user != nil {
  743. // time limit code
  744. prefix := code[:base.TimeLimitCodeLength]
  745. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  746. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  747. emailAddress := &EmailAddress{Email: email}
  748. if has, _ := x.Get(emailAddress); has {
  749. return emailAddress
  750. }
  751. }
  752. }
  753. return nil
  754. }
  755. // ChangeUserName changes all corresponding setting from old user name to new one.
  756. func ChangeUserName(u *User, newUserName string) (err error) {
  757. if err = IsUsableUsername(newUserName); err != nil {
  758. return err
  759. }
  760. isExist, err := IsUserExist(0, newUserName)
  761. if err != nil {
  762. return err
  763. } else if isExist {
  764. return ErrUserAlreadyExist{newUserName}
  765. }
  766. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  767. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  768. }
  769. // Delete all local copies of repository wiki that user owns.
  770. if err = x.BufferSize(setting.IterateBufferSize).
  771. Where("owner_id=?", u.ID).
  772. Iterate(new(Repository), func(idx int, bean interface{}) error {
  773. repo := bean.(*Repository)
  774. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  775. return nil
  776. }); err != nil {
  777. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  778. }
  779. // Do not fail if directory does not exist
  780. if err = os.Rename(UserPath(u.Name), UserPath(newUserName)); err != nil && !os.IsNotExist(err) {
  781. return fmt.Errorf("Rename user directory: %v", err)
  782. }
  783. return nil
  784. }
  785. // checkDupEmail checks whether there are the same email with the user
  786. func checkDupEmail(e Engine, u *User) error {
  787. u.Email = strings.ToLower(u.Email)
  788. has, err := e.
  789. Where("id!=?", u.ID).
  790. And("type=?", u.Type).
  791. And("email=?", u.Email).
  792. Get(new(User))
  793. if err != nil {
  794. return err
  795. } else if has {
  796. return ErrEmailAlreadyUsed{u.Email}
  797. }
  798. return nil
  799. }
  800. func updateUser(e Engine, u *User) error {
  801. _, err := e.ID(u.ID).AllCols().Update(u)
  802. return err
  803. }
  804. // UpdateUser updates user's information.
  805. func UpdateUser(u *User) error {
  806. return updateUser(x, u)
  807. }
  808. // UpdateUserCols update user according special columns
  809. func UpdateUserCols(u *User, cols ...string) error {
  810. return updateUserCols(x, u, cols...)
  811. }
  812. func updateUserCols(e Engine, u *User, cols ...string) error {
  813. _, err := e.ID(u.ID).Cols(cols...).Update(u)
  814. return err
  815. }
  816. // UpdateUserSetting updates user's settings.
  817. func UpdateUserSetting(u *User) error {
  818. if !u.IsOrganization() {
  819. if err := checkDupEmail(x, u); err != nil {
  820. return err
  821. }
  822. }
  823. return updateUser(x, u)
  824. }
  825. // deleteBeans deletes all given beans, beans should contain delete conditions.
  826. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  827. for i := range beans {
  828. if _, err = e.Delete(beans[i]); err != nil {
  829. return err
  830. }
  831. }
  832. return nil
  833. }
  834. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  835. func deleteUser(e *xorm.Session, u *User) error {
  836. // Note: A user owns any repository or belongs to any organization
  837. // cannot perform delete operation.
  838. // Check ownership of repository.
  839. count, err := getRepositoryCount(e, u)
  840. if err != nil {
  841. return fmt.Errorf("GetRepositoryCount: %v", err)
  842. } else if count > 0 {
  843. return ErrUserOwnRepos{UID: u.ID}
  844. }
  845. // Check membership of organization.
  846. count, err = u.getOrganizationCount(e)
  847. if err != nil {
  848. return fmt.Errorf("GetOrganizationCount: %v", err)
  849. } else if count > 0 {
  850. return ErrUserHasOrgs{UID: u.ID}
  851. }
  852. // ***** START: Watch *****
  853. watchedRepoIDs := make([]int64, 0, 10)
  854. if err = e.Table("watch").Cols("watch.repo_id").
  855. Where("watch.user_id = ?", u.ID).Find(&watchedRepoIDs); err != nil {
  856. return fmt.Errorf("get all watches: %v", err)
  857. }
  858. if _, err = e.Decr("num_watches").In("id", watchedRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  859. return fmt.Errorf("decrease repository num_watches: %v", err)
  860. }
  861. // ***** END: Watch *****
  862. // ***** START: Star *****
  863. starredRepoIDs := make([]int64, 0, 10)
  864. if err = e.Table("star").Cols("star.repo_id").
  865. Where("star.uid = ?", u.ID).Find(&starredRepoIDs); err != nil {
  866. return fmt.Errorf("get all stars: %v", err)
  867. } else if _, err = e.Decr("num_stars").In("id", starredRepoIDs).NoAutoTime().Update(new(Repository)); err != nil {
  868. return fmt.Errorf("decrease repository num_stars: %v", err)
  869. }
  870. // ***** END: Star *****
  871. // ***** START: Follow *****
  872. followeeIDs := make([]int64, 0, 10)
  873. if err = e.Table("follow").Cols("follow.follow_id").
  874. Where("follow.user_id = ?", u.ID).Find(&followeeIDs); err != nil {
  875. return fmt.Errorf("get all followees: %v", err)
  876. } else if _, err = e.Decr("num_followers").In("id", followeeIDs).Update(new(User)); err != nil {
  877. return fmt.Errorf("decrease user num_followers: %v", err)
  878. }
  879. followerIDs := make([]int64, 0, 10)
  880. if err = e.Table("follow").Cols("follow.user_id").
  881. Where("follow.follow_id = ?", u.ID).Find(&followerIDs); err != nil {
  882. return fmt.Errorf("get all followers: %v", err)
  883. } else if _, err = e.Decr("num_following").In("id", followerIDs).Update(new(User)); err != nil {
  884. return fmt.Errorf("decrease user num_following: %v", err)
  885. }
  886. // ***** END: Follow *****
  887. if err = deleteBeans(e,
  888. &AccessToken{UID: u.ID},
  889. &Collaboration{UserID: u.ID},
  890. &Access{UserID: u.ID},
  891. &Watch{UserID: u.ID},
  892. &Star{UID: u.ID},
  893. &Follow{UserID: u.ID},
  894. &Follow{FollowID: u.ID},
  895. &Action{UserID: u.ID},
  896. &IssueUser{UID: u.ID},
  897. &EmailAddress{UID: u.ID},
  898. &UserOpenID{UID: u.ID},
  899. &Reaction{UserID: u.ID},
  900. &TeamUser{UID: u.ID},
  901. &Collaboration{UserID: u.ID},
  902. &Stopwatch{UserID: u.ID},
  903. ); err != nil {
  904. return fmt.Errorf("deleteBeans: %v", err)
  905. }
  906. // ***** START: PublicKey *****
  907. if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil {
  908. return fmt.Errorf("deletePublicKeys: %v", err)
  909. }
  910. rewriteAllPublicKeys(e)
  911. // ***** END: PublicKey *****
  912. // ***** START: GPGPublicKey *****
  913. if _, err = e.Delete(&GPGKey{OwnerID: u.ID}); err != nil {
  914. return fmt.Errorf("deleteGPGKeys: %v", err)
  915. }
  916. // ***** END: GPGPublicKey *****
  917. // Clear assignee.
  918. if err = clearAssigneeByUserID(e, u.ID); err != nil {
  919. return fmt.Errorf("clear assignee: %v", err)
  920. }
  921. // ***** START: ExternalLoginUser *****
  922. if err = removeAllAccountLinks(e, u); err != nil {
  923. return fmt.Errorf("ExternalLoginUser: %v", err)
  924. }
  925. // ***** END: ExternalLoginUser *****
  926. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  927. return fmt.Errorf("Delete: %v", err)
  928. }
  929. // FIXME: system notice
  930. // Note: There are something just cannot be roll back,
  931. // so just keep error logs of those operations.
  932. path := UserPath(u.Name)
  933. if err := os.RemoveAll(path); err != nil {
  934. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  935. }
  936. if len(u.Avatar) > 0 {
  937. avatarPath := u.CustomAvatarPath()
  938. if com.IsExist(avatarPath) {
  939. if err := os.Remove(avatarPath); err != nil {
  940. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  941. }
  942. }
  943. }
  944. return nil
  945. }
  946. // DeleteUser completely and permanently deletes everything of a user,
  947. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  948. func DeleteUser(u *User) (err error) {
  949. sess := x.NewSession()
  950. defer sess.Close()
  951. if err = sess.Begin(); err != nil {
  952. return err
  953. }
  954. if err = deleteUser(sess, u); err != nil {
  955. // Note: don't wrapper error here.
  956. return err
  957. }
  958. return sess.Commit()
  959. }
  960. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  961. func DeleteInactivateUsers() (err error) {
  962. users := make([]*User, 0, 10)
  963. if err = x.
  964. Where("is_active = ?", false).
  965. Find(&users); err != nil {
  966. return fmt.Errorf("get all inactive users: %v", err)
  967. }
  968. // FIXME: should only update authorized_keys file once after all deletions.
  969. for _, u := range users {
  970. if err = DeleteUser(u); err != nil {
  971. // Ignore users that were set inactive by admin.
  972. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  973. continue
  974. }
  975. return err
  976. }
  977. }
  978. _, err = x.
  979. Where("is_activated = ?", false).
  980. Delete(new(EmailAddress))
  981. return err
  982. }
  983. // UserPath returns the path absolute path of user repositories.
  984. func UserPath(userName string) string {
  985. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  986. }
  987. // GetUserByKeyID get user information by user's public key id
  988. func GetUserByKeyID(keyID int64) (*User, error) {
  989. var user User
  990. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  991. Where("`public_key`.id=?", keyID).
  992. Get(&user)
  993. if err != nil {
  994. return nil, err
  995. }
  996. if !has {
  997. return nil, ErrUserNotExist{0, "", keyID}
  998. }
  999. return &user, nil
  1000. }
  1001. func getUserByID(e Engine, id int64) (*User, error) {
  1002. u := new(User)
  1003. has, err := e.ID(id).Get(u)
  1004. if err != nil {
  1005. return nil, err
  1006. } else if !has {
  1007. return nil, ErrUserNotExist{id, "", 0}
  1008. }
  1009. return u, nil
  1010. }
  1011. // GetUserByID returns the user object by given ID if exists.
  1012. func GetUserByID(id int64) (*User, error) {
  1013. return getUserByID(x, id)
  1014. }
  1015. // GetUserByName returns user by given name.
  1016. func GetUserByName(name string) (*User, error) {
  1017. return getUserByName(x, name)
  1018. }
  1019. func getUserByName(e Engine, name string) (*User, error) {
  1020. if len(name) == 0 {
  1021. return nil, ErrUserNotExist{0, name, 0}
  1022. }
  1023. u := &User{LowerName: strings.ToLower(name)}
  1024. has, err := e.Get(u)
  1025. if err != nil {
  1026. return nil, err
  1027. } else if !has {
  1028. return nil, ErrUserNotExist{0, name, 0}
  1029. }
  1030. return u, nil
  1031. }
  1032. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  1033. func GetUserEmailsByNames(names []string) []string {
  1034. return getUserEmailsByNames(x, names)
  1035. }
  1036. func getUserEmailsByNames(e Engine, names []string) []string {
  1037. mails := make([]string, 0, len(names))
  1038. for _, name := range names {
  1039. u, err := getUserByName(e, name)
  1040. if err != nil {
  1041. continue
  1042. }
  1043. if u.IsMailable() {
  1044. mails = append(mails, u.Email)
  1045. }
  1046. }
  1047. return mails
  1048. }
  1049. // GetUsersByIDs returns all resolved users from a list of Ids.
  1050. func GetUsersByIDs(ids []int64) ([]*User, error) {
  1051. ous := make([]*User, 0, len(ids))
  1052. if len(ids) == 0 {
  1053. return ous, nil
  1054. }
  1055. err := x.In("id", ids).
  1056. Asc("name").
  1057. Find(&ous)
  1058. return ous, err
  1059. }
  1060. // GetUserIDsByNames returns a slice of ids corresponds to names.
  1061. func GetUserIDsByNames(names []string) []int64 {
  1062. ids := make([]int64, 0, len(names))
  1063. for _, name := range names {
  1064. u, err := GetUserByName(name)
  1065. if err != nil {
  1066. continue
  1067. }
  1068. ids = append(ids, u.ID)
  1069. }
  1070. return ids
  1071. }
  1072. // UserCommit represents a commit with validation of user.
  1073. type UserCommit struct {
  1074. User *User
  1075. *git.Commit
  1076. }
  1077. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1078. func ValidateCommitWithEmail(c *git.Commit) *User {
  1079. if c.Author == nil {
  1080. return nil
  1081. }
  1082. u, err := GetUserByEmail(c.Author.Email)
  1083. if err != nil {
  1084. return nil
  1085. }
  1086. return u
  1087. }
  1088. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1089. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1090. var (
  1091. u *User
  1092. emails = map[string]*User{}
  1093. newCommits = list.New()
  1094. e = oldCommits.Front()
  1095. )
  1096. for e != nil {
  1097. c := e.Value.(*git.Commit)
  1098. if c.Author != nil {
  1099. if v, ok := emails[c.Author.Email]; !ok {
  1100. u, _ = GetUserByEmail(c.Author.Email)
  1101. emails[c.Author.Email] = u
  1102. } else {
  1103. u = v
  1104. }
  1105. } else {
  1106. u = nil
  1107. }
  1108. newCommits.PushBack(UserCommit{
  1109. User: u,
  1110. Commit: c,
  1111. })
  1112. e = e.Next()
  1113. }
  1114. return newCommits
  1115. }
  1116. // GetUserByEmail returns the user object by given e-mail if exists.
  1117. func GetUserByEmail(email string) (*User, error) {
  1118. if len(email) == 0 {
  1119. return nil, ErrUserNotExist{0, email, 0}
  1120. }
  1121. email = strings.ToLower(email)
  1122. // First try to find the user by primary email
  1123. user := &User{Email: email}
  1124. has, err := x.Get(user)
  1125. if err != nil {
  1126. return nil, err
  1127. }
  1128. if has {
  1129. return user, nil
  1130. }
  1131. // Otherwise, check in alternative list for activated email addresses
  1132. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1133. has, err = x.Get(emailAddress)
  1134. if err != nil {
  1135. return nil, err
  1136. }
  1137. if has {
  1138. return GetUserByID(emailAddress.UID)
  1139. }
  1140. return nil, ErrUserNotExist{0, email, 0}
  1141. }
  1142. // GetUser checks if a user already exists
  1143. func GetUser(user *User) (bool, error) {
  1144. return x.Get(user)
  1145. }
  1146. // SearchUserOptions contains the options for searching
  1147. type SearchUserOptions struct {
  1148. Keyword string
  1149. Type UserType
  1150. UID int64
  1151. OrderBy SearchOrderBy
  1152. Page int
  1153. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1154. IsActive util.OptionalBool
  1155. SearchByEmail bool // Search by email as well as username/full name
  1156. }
  1157. func (opts *SearchUserOptions) toConds() builder.Cond {
  1158. var cond builder.Cond = builder.Eq{"type": opts.Type}
  1159. if len(opts.Keyword) > 0 {
  1160. lowerKeyword := strings.ToLower(opts.Keyword)
  1161. keywordCond := builder.Or(
  1162. builder.Like{"lower_name", lowerKeyword},
  1163. builder.Like{"LOWER(full_name)", lowerKeyword},
  1164. )
  1165. if opts.SearchByEmail {
  1166. keywordCond = keywordCond.Or(builder.Like{"LOWER(email)", lowerKeyword})
  1167. }
  1168. cond = cond.And(keywordCond)
  1169. }
  1170. if opts.UID > 0 {
  1171. cond = cond.And(builder.Eq{"id": opts.UID})
  1172. }
  1173. if !opts.IsActive.IsNone() {
  1174. cond = cond.And(builder.Eq{"is_active": opts.IsActive.IsTrue()})
  1175. }
  1176. return cond
  1177. }
  1178. // SearchUsers takes options i.e. keyword and part of user name to search,
  1179. // it returns results in given range and number of total results.
  1180. func SearchUsers(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1181. cond := opts.toConds()
  1182. count, err := x.Where(cond).Count(new(User))
  1183. if err != nil {
  1184. return nil, 0, fmt.Errorf("Count: %v", err)
  1185. }
  1186. if opts.PageSize == 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1187. opts.PageSize = setting.UI.ExplorePagingNum
  1188. }
  1189. if opts.Page <= 0 {
  1190. opts.Page = 1
  1191. }
  1192. if len(opts.OrderBy) == 0 {
  1193. opts.OrderBy = SearchOrderByAlphabetically
  1194. }
  1195. sess := x.Where(cond)
  1196. if opts.PageSize > 0 {
  1197. sess = sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1198. }
  1199. users = make([]*User, 0, opts.PageSize)
  1200. return users, count, sess.OrderBy(opts.OrderBy.String()).Find(&users)
  1201. }
  1202. // GetStarredRepos returns the repos starred by a particular user
  1203. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1204. sess := x.Where("star.uid=?", userID).
  1205. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1206. if !private {
  1207. sess = sess.And("is_private=?", false)
  1208. }
  1209. repos := make([]*Repository, 0, 10)
  1210. err := sess.Find(&repos)
  1211. if err != nil {
  1212. return nil, err
  1213. }
  1214. return repos, nil
  1215. }
  1216. // GetWatchedRepos returns the repos watched by a particular user
  1217. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1218. sess := x.Where("watch.user_id=?", userID).
  1219. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1220. if !private {
  1221. sess = sess.And("is_private=?", false)
  1222. }
  1223. repos := make([]*Repository, 0, 10)
  1224. err := sess.Find(&repos)
  1225. if err != nil {
  1226. return nil, err
  1227. }
  1228. return repos, nil
  1229. }
  1230. // deleteKeysMarkedForDeletion returns true if ssh keys needs update
  1231. func deleteKeysMarkedForDeletion(keys []string) (bool, error) {
  1232. // Start session
  1233. sess := x.NewSession()
  1234. defer sess.Close()
  1235. if err := sess.Begin(); err != nil {
  1236. return false, err
  1237. }
  1238. // Delete keys marked for deletion
  1239. var sshKeysNeedUpdate bool
  1240. for _, KeyToDelete := range keys {
  1241. key, err := searchPublicKeyByContentWithEngine(sess, KeyToDelete)
  1242. if err != nil {
  1243. log.Error(4, "SearchPublicKeyByContent: %v", err)
  1244. continue
  1245. }
  1246. if err = deletePublicKeys(sess, key.ID); err != nil {
  1247. log.Error(4, "deletePublicKeys: %v", err)
  1248. continue
  1249. }
  1250. sshKeysNeedUpdate = true
  1251. }
  1252. if err := sess.Commit(); err != nil {
  1253. return false, err
  1254. }
  1255. return sshKeysNeedUpdate, nil
  1256. }
  1257. // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes.
  1258. func addLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) bool {
  1259. var sshKeysNeedUpdate bool
  1260. for _, sshKey := range SSHPublicKeys {
  1261. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey))
  1262. if err == nil {
  1263. sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40])
  1264. if _, err := AddPublicKey(usr.ID, sshKeyName, sshKey, s.ID); err != nil {
  1265. log.Error(4, "addLdapSSHPublicKeys[%s]: Error adding LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, err)
  1266. } else {
  1267. log.Trace("addLdapSSHPublicKeys[%s]: Added LDAP Public SSH Key for user %s", s.Name, usr.Name)
  1268. sshKeysNeedUpdate = true
  1269. }
  1270. } else {
  1271. log.Warn("addLdapSSHPublicKeys[%s]: Skipping invalid LDAP Public SSH Key for user %s: %v", s.Name, usr.Name, sshKey)
  1272. }
  1273. }
  1274. return sshKeysNeedUpdate
  1275. }
  1276. // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes.
  1277. func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) bool {
  1278. var sshKeysNeedUpdate bool
  1279. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name)
  1280. // Get Public Keys from DB with current LDAP source
  1281. var giteaKeys []string
  1282. keys, err := ListPublicLdapSSHKeys(usr.ID, s.ID)
  1283. if err != nil {
  1284. log.Error(4, "synchronizeLdapSSHPublicKeys[%s]: Error listing LDAP Public SSH Keys for user %s: %v", s.Name, usr.Name, err)
  1285. }
  1286. for _, v := range keys {
  1287. giteaKeys = append(giteaKeys, v.OmitEmail())
  1288. }
  1289. // Get Public Keys from LDAP and skip duplicate keys
  1290. var ldapKeys []string
  1291. for _, v := range SSHPublicKeys {
  1292. ldapKey := strings.Join(strings.Split(v, " ")[:2], " ")
  1293. if !util.ExistsInSlice(ldapKey, ldapKeys) {
  1294. ldapKeys = append(ldapKeys, ldapKey)
  1295. }
  1296. }
  1297. // Check if Public Key sync is needed
  1298. if util.IsEqualSlice(giteaKeys, ldapKeys) {
  1299. 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))
  1300. return false
  1301. }
  1302. log.Trace("synchronizeLdapSSHPublicKeys[%s]: LDAP Public Key needs update for user %s (LDAP:%v/DB:%v)", s.Name, usr.Name, len(ldapKeys), len(giteaKeys))
  1303. // Add LDAP Public SSH Keys that doesn't already exist in DB
  1304. var newLdapSSHKeys []string
  1305. for _, LDAPPublicSSHKey := range ldapKeys {
  1306. if !util.ExistsInSlice(LDAPPublicSSHKey, giteaKeys) {
  1307. newLdapSSHKeys = append(newLdapSSHKeys, LDAPPublicSSHKey)
  1308. }
  1309. }
  1310. if addLdapSSHPublicKeys(usr, s, newLdapSSHKeys) {
  1311. sshKeysNeedUpdate = true
  1312. }
  1313. // Mark LDAP keys from DB that doesn't exist in LDAP for deletion
  1314. var giteaKeysToDelete []string
  1315. for _, giteaKey := range giteaKeys {
  1316. if !util.ExistsInSlice(giteaKey, ldapKeys) {
  1317. log.Trace("synchronizeLdapSSHPublicKeys[%s]: Marking LDAP Public SSH Key for deletion for user %s: %v", s.Name, usr.Name, giteaKey)
  1318. giteaKeysToDelete = append(giteaKeysToDelete, giteaKey)
  1319. }
  1320. }
  1321. // Delete LDAP keys from DB that doesn't exist in LDAP
  1322. needUpd, err := deleteKeysMarkedForDeletion(giteaKeysToDelete)
  1323. if err != nil {
  1324. log.Error(4, "synchronizeLdapSSHPublicKeys[%s]: Error deleting LDAP Public SSH Keys marked for deletion for user %s: %v", s.Name, usr.Name, err)
  1325. }
  1326. if needUpd {
  1327. sshKeysNeedUpdate = true
  1328. }
  1329. return sshKeysNeedUpdate
  1330. }
  1331. // SyncExternalUsers is used to synchronize users with external authorization source
  1332. func SyncExternalUsers() {
  1333. if !taskStatusTable.StartIfNotRunning(syncExternalUsers) {
  1334. return
  1335. }
  1336. defer taskStatusTable.Stop(syncExternalUsers)
  1337. log.Trace("Doing: SyncExternalUsers")
  1338. ls, err := LoginSources()
  1339. if err != nil {
  1340. log.Error(4, "SyncExternalUsers: %v", err)
  1341. return
  1342. }
  1343. updateExisting := setting.Cron.SyncExternalUsers.UpdateExisting
  1344. for _, s := range ls {
  1345. if !s.IsActived || !s.IsSyncEnabled {
  1346. continue
  1347. }
  1348. if s.IsLDAP() {
  1349. log.Trace("Doing: SyncExternalUsers[%s]", s.Name)
  1350. var existingUsers []int64
  1351. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(s.LDAP().AttributeSSHPublicKey)) > 0
  1352. var sshKeysNeedUpdate bool
  1353. // Find all users with this login type
  1354. var users []User
  1355. x.Where("login_type = ?", LoginLDAP).
  1356. And("login_source = ?", s.ID).
  1357. Find(&users)
  1358. sr := s.LDAP().SearchEntries()
  1359. for _, su := range sr {
  1360. if len(su.Username) == 0 {
  1361. continue
  1362. }
  1363. if len(su.Mail) == 0 {
  1364. su.Mail = fmt.Sprintf("%s@localhost", su.Username)
  1365. }
  1366. var usr *User
  1367. // Search for existing user
  1368. for _, du := range users {
  1369. if du.LowerName == strings.ToLower(su.Username) {
  1370. usr = &du
  1371. break
  1372. }
  1373. }
  1374. fullName := composeFullName(su.Name, su.Surname, su.Username)
  1375. // If no existing user found, create one
  1376. if usr == nil {
  1377. log.Trace("SyncExternalUsers[%s]: Creating user %s", s.Name, su.Username)
  1378. usr = &User{
  1379. LowerName: strings.ToLower(su.Username),
  1380. Name: su.Username,
  1381. FullName: fullName,
  1382. LoginType: s.Type,
  1383. LoginSource: s.ID,
  1384. LoginName: su.Username,
  1385. Email: su.Mail,
  1386. IsAdmin: su.IsAdmin,
  1387. IsActive: true,
  1388. }
  1389. err = CreateUser(usr)
  1390. if err != nil {
  1391. log.Error(4, "SyncExternalUsers[%s]: Error creating user %s: %v", s.Name, su.Username, err)
  1392. } else if isAttributeSSHPublicKeySet {
  1393. log.Trace("SyncExternalUsers[%s]: Adding LDAP Public SSH Keys for user %s", s.Name, usr.Name)
  1394. if addLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1395. sshKeysNeedUpdate = true
  1396. }
  1397. }
  1398. } else if updateExisting {
  1399. existingUsers = append(existingUsers, usr.ID)
  1400. // Synchronize SSH Public Key if that attribute is set
  1401. if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(usr, s, su.SSHPublicKey) {
  1402. sshKeysNeedUpdate = true
  1403. }
  1404. // Check if user data has changed
  1405. if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) ||
  1406. strings.ToLower(usr.Email) != strings.ToLower(su.Mail) ||
  1407. usr.FullName != fullName ||
  1408. !usr.IsActive {
  1409. log.Trace("SyncExternalUsers[%s]: Updating user %s", s.Name, usr.Name)
  1410. usr.FullName = fullName
  1411. usr.Email = su.Mail
  1412. // Change existing admin flag only if AdminFilter option is set
  1413. if len(s.LDAP().AdminFilter) > 0 {
  1414. usr.IsAdmin = su.IsAdmin
  1415. }
  1416. usr.IsActive = true
  1417. err = UpdateUserCols(usr, "full_name", "email", "is_admin", "is_active")
  1418. if err != nil {
  1419. log.Error(4, "SyncExternalUsers[%s]: Error updating user %s: %v", s.Name, usr.Name, err)
  1420. }
  1421. }
  1422. }
  1423. }
  1424. // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed
  1425. if sshKeysNeedUpdate {
  1426. RewriteAllPublicKeys()
  1427. }
  1428. // Deactivate users not present in LDAP
  1429. if updateExisting {
  1430. for _, usr := range users {
  1431. found := false
  1432. for _, uid := range existingUsers {
  1433. if usr.ID == uid {
  1434. found = true
  1435. break
  1436. }
  1437. }
  1438. if !found {
  1439. log.Trace("SyncExternalUsers[%s]: Deactivating user %s", s.Name, usr.Name)
  1440. usr.IsActive = false
  1441. err = UpdateUserCols(&usr, "is_active")
  1442. if err != nil {
  1443. log.Error(4, "SyncExternalUsers[%s]: Error deactivating user %s: %v", s.Name, usr.Name, err)
  1444. }
  1445. }
  1446. }
  1447. }
  1448. }
  1449. }
  1450. }