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

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