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

user.go 46 kB

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