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

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