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