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