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