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

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