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 38 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
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
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
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
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
11 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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/markdown"
  34. "code.gitea.io/gitea/modules/setting"
  35. )
  36. // UserType defines the user type
  37. type UserType int
  38. const (
  39. // UserTypeIndividual defines an individual user
  40. UserTypeIndividual UserType = iota // Historic reason to make it starts at 0.
  41. // UserTypeOrganization defines an organization
  42. UserTypeOrganization
  43. )
  44. 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 "full_name":
  139. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  140. case "created_unix":
  141. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  142. case "updated_unix":
  143. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  144. case "last_login_unix":
  145. u.LastLogin = time.Unix(u.LastLoginUnix, 0).Local()
  146. }
  147. }
  148. // getEmail returns an noreply email, if the user has set to keep his
  149. // email address private, otherwise the primary email address.
  150. func (u *User) getEmail() string {
  151. if u.KeepEmailPrivate {
  152. return fmt.Sprintf("%s@%s", u.LowerName, setting.Service.NoReplyAddress)
  153. }
  154. return u.Email
  155. }
  156. // APIFormat converts a User to api.User
  157. func (u *User) APIFormat() *api.User {
  158. return &api.User{
  159. ID: u.ID,
  160. UserName: u.Name,
  161. FullName: u.FullName,
  162. Email: u.getEmail(),
  163. AvatarURL: u.AvatarLink(),
  164. }
  165. }
  166. // IsLocal returns true if user login type is LoginPlain.
  167. func (u *User) IsLocal() bool {
  168. return u.LoginType <= LoginPlain
  169. }
  170. // IsOAuth2 returns true if user login type is LoginOAuth2.
  171. func (u *User) IsOAuth2() bool {
  172. return u.LoginType == LoginOAuth2
  173. }
  174. // HasForkedRepo checks if user has already forked a repository with given ID.
  175. func (u *User) HasForkedRepo(repoID int64) bool {
  176. _, has := HasForkedRepo(u.ID, repoID)
  177. return has
  178. }
  179. // RepoCreationNum returns the number of repositories created by the user
  180. func (u *User) RepoCreationNum() int {
  181. if u.MaxRepoCreation <= -1 {
  182. return setting.Repository.MaxCreationLimit
  183. }
  184. return u.MaxRepoCreation
  185. }
  186. // CanCreateRepo returns if user login can create a repository
  187. func (u *User) CanCreateRepo() bool {
  188. if u.MaxRepoCreation <= -1 {
  189. if setting.Repository.MaxCreationLimit <= -1 {
  190. return true
  191. }
  192. return u.NumRepos < setting.Repository.MaxCreationLimit
  193. }
  194. return u.NumRepos < u.MaxRepoCreation
  195. }
  196. // CanCreateOrganization returns true if user can create organisation.
  197. func (u *User) CanCreateOrganization() bool {
  198. return u.IsAdmin || (u.AllowCreateOrganization && !setting.Admin.DisableRegularOrgCreation)
  199. }
  200. // CanEditGitHook returns true if user can edit Git hooks.
  201. func (u *User) CanEditGitHook() bool {
  202. return u.IsAdmin || u.AllowGitHook
  203. }
  204. // CanImportLocal returns true if user can migrate repository by local path.
  205. func (u *User) CanImportLocal() bool {
  206. if !setting.ImportLocalPaths {
  207. return false
  208. }
  209. return u.IsAdmin || u.AllowImportLocal
  210. }
  211. // DashboardLink returns the user dashboard page link.
  212. func (u *User) DashboardLink() string {
  213. if u.IsOrganization() {
  214. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  215. }
  216. return setting.AppSubURL + "/"
  217. }
  218. // HomeLink returns the user or organization home page link.
  219. func (u *User) HomeLink() string {
  220. return setting.AppSubURL + "/" + u.Name
  221. }
  222. // HTMLURL returns the user or organization's full link.
  223. func (u *User) HTMLURL() string {
  224. return setting.AppURL + u.Name
  225. }
  226. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  227. func (u *User) GenerateEmailActivateCode(email string) string {
  228. code := base.CreateTimeLimitCode(
  229. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  230. setting.Service.ActiveCodeLives, nil)
  231. // Add tail hex username
  232. code += hex.EncodeToString([]byte(u.LowerName))
  233. return code
  234. }
  235. // GenerateActivateCode generates an activate code based on user information.
  236. func (u *User) GenerateActivateCode() string {
  237. return u.GenerateEmailActivateCode(u.Email)
  238. }
  239. // CustomAvatarPath returns user custom avatar file path.
  240. func (u *User) CustomAvatarPath() string {
  241. return filepath.Join(setting.AvatarUploadPath, u.Avatar)
  242. }
  243. // GenerateRandomAvatar generates a random avatar for user.
  244. func (u *User) GenerateRandomAvatar() error {
  245. seed := u.Email
  246. if len(seed) == 0 {
  247. seed = u.Name
  248. }
  249. img, err := avatar.RandomImage([]byte(seed))
  250. if err != nil {
  251. return fmt.Errorf("RandomImage: %v", err)
  252. }
  253. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  254. // since random image is not a user's photo, there is no security for enumable
  255. u.Avatar = fmt.Sprintf("%d", u.ID)
  256. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  257. return fmt.Errorf("MkdirAll: %v", err)
  258. }
  259. fw, err := os.Create(u.CustomAvatarPath())
  260. if err != nil {
  261. return fmt.Errorf("Create: %v", err)
  262. }
  263. defer fw.Close()
  264. if err = png.Encode(fw, img); err != nil {
  265. return fmt.Errorf("Encode: %v", err)
  266. }
  267. log.Info("New random avatar created: %d", u.ID)
  268. return nil
  269. }
  270. // RelAvatarLink returns relative avatar link to the site domain,
  271. // which includes app sub-url as prefix. However, it is possible
  272. // to return full URL if user enables Gravatar-like service.
  273. func (u *User) RelAvatarLink() string {
  274. defaultImgURL := setting.AppSubURL + "/img/avatar_default.png"
  275. if u.ID == -1 {
  276. return defaultImgURL
  277. }
  278. switch {
  279. case u.UseCustomAvatar:
  280. if !com.IsFile(u.CustomAvatarPath()) {
  281. return defaultImgURL
  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 sessionRelease(sess)
  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, 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, 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 repsitories IDs where user's or user is a team member orgnizations
  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 elegible
  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 ramdom 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", "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 = true
  600. u.MaxRepoCreation = -1
  601. sess := x.NewSession()
  602. defer sessionRelease(sess)
  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. u.Avatar = base.HashEmail(u.AvatarEmail)
  729. }
  730. u.LowerName = strings.ToLower(u.Name)
  731. u.Location = base.TruncateString(u.Location, 255)
  732. u.Website = base.TruncateString(u.Website, 255)
  733. u.Description = base.TruncateString(u.Description, 255)
  734. u.FullName = markdown.Sanitizer.Sanitize(u.FullName)
  735. _, err := e.Id(u.ID).AllCols().Update(u)
  736. return err
  737. }
  738. // UpdateUser updates user's information.
  739. func UpdateUser(u *User) error {
  740. return updateUser(x, u)
  741. }
  742. // UpdateUserSetting updates user's settings.
  743. func UpdateUserSetting(u *User) error {
  744. if !u.IsOrganization() {
  745. if err := checkDupEmail(x, u); err != nil {
  746. return err
  747. }
  748. }
  749. return updateUser(x, u)
  750. }
  751. // deleteBeans deletes all given beans, beans should contain delete conditions.
  752. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  753. for i := range beans {
  754. if _, err = e.Delete(beans[i]); err != nil {
  755. return err
  756. }
  757. }
  758. return nil
  759. }
  760. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  761. func deleteUser(e *xorm.Session, u *User) error {
  762. // Note: A user owns any repository or belongs to any organization
  763. // cannot perform delete operation.
  764. // Check ownership of repository.
  765. count, err := getRepositoryCount(e, u)
  766. if err != nil {
  767. return fmt.Errorf("GetRepositoryCount: %v", err)
  768. } else if count > 0 {
  769. return ErrUserOwnRepos{UID: u.ID}
  770. }
  771. // Check membership of organization.
  772. count, err = u.getOrganizationCount(e)
  773. if err != nil {
  774. return fmt.Errorf("GetOrganizationCount: %v", err)
  775. } else if count > 0 {
  776. return ErrUserHasOrgs{UID: u.ID}
  777. }
  778. // ***** START: Watch *****
  779. watches := make([]*Watch, 0, 10)
  780. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  781. return fmt.Errorf("get all watches: %v", err)
  782. }
  783. for i := range watches {
  784. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  785. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  786. }
  787. }
  788. // ***** END: Watch *****
  789. // ***** START: Star *****
  790. stars := make([]*Star, 0, 10)
  791. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  792. return fmt.Errorf("get all stars: %v", err)
  793. }
  794. for i := range stars {
  795. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  796. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  797. }
  798. }
  799. // ***** END: Star *****
  800. // ***** START: Follow *****
  801. followers := make([]*Follow, 0, 10)
  802. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  803. return fmt.Errorf("get all followers: %v", err)
  804. }
  805. for i := range followers {
  806. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  807. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  808. }
  809. }
  810. // ***** END: Follow *****
  811. if err = deleteBeans(e,
  812. &AccessToken{UID: u.ID},
  813. &Collaboration{UserID: u.ID},
  814. &Access{UserID: u.ID},
  815. &Watch{UserID: u.ID},
  816. &Star{UID: u.ID},
  817. &Follow{FollowID: u.ID},
  818. &Action{UserID: u.ID},
  819. &IssueUser{UID: u.ID},
  820. &EmailAddress{UID: u.ID},
  821. ); err != nil {
  822. return fmt.Errorf("deleteBeans: %v", err)
  823. }
  824. // ***** START: PublicKey *****
  825. keys := make([]*PublicKey, 0, 10)
  826. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  827. return fmt.Errorf("get all public keys: %v", err)
  828. }
  829. keyIDs := make([]int64, len(keys))
  830. for i := range keys {
  831. keyIDs[i] = keys[i].ID
  832. }
  833. if err = deletePublicKeys(e, keyIDs...); err != nil {
  834. return fmt.Errorf("deletePublicKeys: %v", err)
  835. }
  836. // ***** END: PublicKey *****
  837. // Clear assignee.
  838. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  839. return fmt.Errorf("clear assignee: %v", err)
  840. }
  841. // ***** START: ExternalLoginUser *****
  842. if err = RemoveAllAccountLinks(u); err != nil {
  843. return fmt.Errorf("ExternalLoginUser: %v", err)
  844. }
  845. // ***** END: ExternalLoginUser *****
  846. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  847. return fmt.Errorf("Delete: %v", err)
  848. }
  849. // FIXME: system notice
  850. // Note: There are something just cannot be roll back,
  851. // so just keep error logs of those operations.
  852. path := UserPath(u.Name)
  853. if err := os.RemoveAll(path); err != nil {
  854. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  855. }
  856. if len(u.Avatar) > 0 {
  857. avatarPath := u.CustomAvatarPath()
  858. if com.IsExist(avatarPath) {
  859. if err := os.Remove(avatarPath); err != nil {
  860. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  861. }
  862. }
  863. }
  864. return nil
  865. }
  866. // DeleteUser completely and permanently deletes everything of a user,
  867. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  868. func DeleteUser(u *User) (err error) {
  869. sess := x.NewSession()
  870. defer sessionRelease(sess)
  871. if err = sess.Begin(); err != nil {
  872. return err
  873. }
  874. if err = deleteUser(sess, u); err != nil {
  875. // Note: don't wrapper error here.
  876. return err
  877. }
  878. if err = sess.Commit(); err != nil {
  879. return err
  880. }
  881. return RewriteAllPublicKeys()
  882. }
  883. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  884. func DeleteInactivateUsers() (err error) {
  885. users := make([]*User, 0, 10)
  886. if err = x.
  887. Where("is_active = ?", false).
  888. Find(&users); err != nil {
  889. return fmt.Errorf("get all inactive users: %v", err)
  890. }
  891. // FIXME: should only update authorized_keys file once after all deletions.
  892. for _, u := range users {
  893. if err = DeleteUser(u); err != nil {
  894. // Ignore users that were set inactive by admin.
  895. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  896. continue
  897. }
  898. return err
  899. }
  900. }
  901. _, err = x.
  902. Where("is_activated = ?", false).
  903. Delete(new(EmailAddress))
  904. return err
  905. }
  906. // UserPath returns the path absolute path of user repositories.
  907. func UserPath(userName string) string {
  908. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  909. }
  910. // GetUserByKeyID get user information by user's public key id
  911. func GetUserByKeyID(keyID int64) (*User, error) {
  912. var user User
  913. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  914. Where("`public_key`.id=?", keyID).
  915. Get(&user)
  916. if err != nil {
  917. return nil, err
  918. }
  919. if !has {
  920. return nil, ErrUserNotExist{0, "", keyID}
  921. }
  922. return &user, nil
  923. }
  924. func getUserByID(e Engine, id int64) (*User, error) {
  925. u := new(User)
  926. has, err := e.Id(id).Get(u)
  927. if err != nil {
  928. return nil, err
  929. } else if !has {
  930. return nil, ErrUserNotExist{id, "", 0}
  931. }
  932. return u, nil
  933. }
  934. // GetUserByID returns the user object by given ID if exists.
  935. func GetUserByID(id int64) (*User, error) {
  936. return getUserByID(x, id)
  937. }
  938. // GetAssigneeByID returns the user with write access of repository by given ID.
  939. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  940. has, err := HasAccess(&User{ID: userID}, repo, AccessModeWrite)
  941. if err != nil {
  942. return nil, err
  943. } else if !has {
  944. return nil, ErrUserNotExist{userID, "", 0}
  945. }
  946. return GetUserByID(userID)
  947. }
  948. // GetUserByName returns user by given name.
  949. func GetUserByName(name string) (*User, error) {
  950. if len(name) == 0 {
  951. return nil, ErrUserNotExist{0, name, 0}
  952. }
  953. u := &User{LowerName: strings.ToLower(name)}
  954. has, err := x.Get(u)
  955. if err != nil {
  956. return nil, err
  957. } else if !has {
  958. return nil, ErrUserNotExist{0, name, 0}
  959. }
  960. return u, nil
  961. }
  962. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  963. func GetUserEmailsByNames(names []string) []string {
  964. mails := make([]string, 0, len(names))
  965. for _, name := range names {
  966. u, err := GetUserByName(name)
  967. if err != nil {
  968. continue
  969. }
  970. if u.IsMailable() {
  971. mails = append(mails, u.Email)
  972. }
  973. }
  974. return mails
  975. }
  976. // GetUsersByIDs returns all resolved users from a list of Ids.
  977. func GetUsersByIDs(ids []int64) ([]*User, error) {
  978. ous := make([]*User, 0, len(ids))
  979. if len(ids) == 0 {
  980. return ous, nil
  981. }
  982. err := x.In("id", ids).
  983. Asc("name").
  984. Find(&ous)
  985. return ous, err
  986. }
  987. // GetUserIDsByNames returns a slice of ids corresponds to names.
  988. func GetUserIDsByNames(names []string) []int64 {
  989. ids := make([]int64, 0, len(names))
  990. for _, name := range names {
  991. u, err := GetUserByName(name)
  992. if err != nil {
  993. continue
  994. }
  995. ids = append(ids, u.ID)
  996. }
  997. return ids
  998. }
  999. // UserCommit represents a commit with validation of user.
  1000. type UserCommit struct {
  1001. User *User
  1002. *git.Commit
  1003. }
  1004. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1005. func ValidateCommitWithEmail(c *git.Commit) *User {
  1006. u, err := GetUserByEmail(c.Author.Email)
  1007. if err != nil {
  1008. return nil
  1009. }
  1010. return u
  1011. }
  1012. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1013. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1014. var (
  1015. u *User
  1016. emails = map[string]*User{}
  1017. newCommits = list.New()
  1018. e = oldCommits.Front()
  1019. )
  1020. for e != nil {
  1021. c := e.Value.(*git.Commit)
  1022. if v, ok := emails[c.Author.Email]; !ok {
  1023. u, _ = GetUserByEmail(c.Author.Email)
  1024. emails[c.Author.Email] = u
  1025. } else {
  1026. u = v
  1027. }
  1028. newCommits.PushBack(UserCommit{
  1029. User: u,
  1030. Commit: c,
  1031. })
  1032. e = e.Next()
  1033. }
  1034. return newCommits
  1035. }
  1036. // GetUserByEmail returns the user object by given e-mail if exists.
  1037. func GetUserByEmail(email string) (*User, error) {
  1038. if len(email) == 0 {
  1039. return nil, ErrUserNotExist{0, email, 0}
  1040. }
  1041. email = strings.ToLower(email)
  1042. // First try to find the user by primary email
  1043. user := &User{Email: email}
  1044. has, err := x.Get(user)
  1045. if err != nil {
  1046. return nil, err
  1047. }
  1048. if has {
  1049. return user, nil
  1050. }
  1051. // Otherwise, check in alternative list for activated email addresses
  1052. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1053. has, err = x.Get(emailAddress)
  1054. if err != nil {
  1055. return nil, err
  1056. }
  1057. if has {
  1058. return GetUserByID(emailAddress.UID)
  1059. }
  1060. return nil, ErrUserNotExist{0, email, 0}
  1061. }
  1062. // GetUser checks if a user already exists
  1063. func GetUser(user *User) (bool, error) {
  1064. return x.Get(user)
  1065. }
  1066. // SearchUserOptions contains the options for searching
  1067. type SearchUserOptions struct {
  1068. Keyword string
  1069. Type UserType
  1070. OrderBy string
  1071. Page int
  1072. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1073. }
  1074. // SearchUserByName takes keyword and part of user name to search,
  1075. // it returns results in given range and number of total results.
  1076. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1077. if len(opts.Keyword) == 0 {
  1078. return users, 0, nil
  1079. }
  1080. opts.Keyword = strings.ToLower(opts.Keyword)
  1081. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1082. opts.PageSize = setting.UI.ExplorePagingNum
  1083. }
  1084. if opts.Page <= 0 {
  1085. opts.Page = 1
  1086. }
  1087. users = make([]*User, 0, opts.PageSize)
  1088. // Append conditions
  1089. cond := builder.And(
  1090. builder.Eq{"type": opts.Type},
  1091. builder.Or(
  1092. builder.Like{"lower_name", opts.Keyword},
  1093. builder.Like{"LOWER(full_name)", opts.Keyword},
  1094. ),
  1095. )
  1096. count, err := x.Where(cond).Count(new(User))
  1097. if err != nil {
  1098. return nil, 0, fmt.Errorf("Count: %v", err)
  1099. }
  1100. sess := x.Where(cond).
  1101. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1102. if len(opts.OrderBy) > 0 {
  1103. sess.OrderBy(opts.OrderBy)
  1104. }
  1105. return users, count, sess.Find(&users)
  1106. }
  1107. // ___________ .__ .__
  1108. // \_ _____/___ | | | | ______ _ __
  1109. // | __)/ _ \| | | | / _ \ \/ \/ /
  1110. // | \( <_> ) |_| |_( <_> ) /
  1111. // \___ / \____/|____/____/\____/ \/\_/
  1112. // \/
  1113. // Follow represents relations of user and his/her followers.
  1114. type Follow struct {
  1115. ID int64 `xorm:"pk autoincr"`
  1116. UserID int64 `xorm:"UNIQUE(follow)"`
  1117. FollowID int64 `xorm:"UNIQUE(follow)"`
  1118. }
  1119. // IsFollowing returns true if user is following followID.
  1120. func IsFollowing(userID, followID int64) bool {
  1121. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  1122. return has
  1123. }
  1124. // FollowUser marks someone be another's follower.
  1125. func FollowUser(userID, followID int64) (err error) {
  1126. if userID == followID || IsFollowing(userID, followID) {
  1127. return nil
  1128. }
  1129. sess := x.NewSession()
  1130. defer sessionRelease(sess)
  1131. if err = sess.Begin(); err != nil {
  1132. return err
  1133. }
  1134. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1135. return err
  1136. }
  1137. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  1138. return err
  1139. }
  1140. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  1141. return err
  1142. }
  1143. return sess.Commit()
  1144. }
  1145. // UnfollowUser unmarks someone as another's follower.
  1146. func UnfollowUser(userID, followID int64) (err error) {
  1147. if userID == followID || !IsFollowing(userID, followID) {
  1148. return nil
  1149. }
  1150. sess := x.NewSession()
  1151. defer sessionRelease(sess)
  1152. if err = sess.Begin(); err != nil {
  1153. return err
  1154. }
  1155. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  1156. return err
  1157. }
  1158. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  1159. return err
  1160. }
  1161. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  1162. return err
  1163. }
  1164. return sess.Commit()
  1165. }
  1166. // GetStarredRepos returns the repos starred by a particular user
  1167. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1168. sess := x.Where("star.uid=?", userID).
  1169. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1170. if !private {
  1171. sess = sess.And("is_private=?", false)
  1172. }
  1173. repos := make([]*Repository, 0, 10)
  1174. err := sess.Find(&repos)
  1175. if err != nil {
  1176. return nil, err
  1177. }
  1178. return repos, nil
  1179. }
  1180. // GetWatchedRepos returns the repos watched by a particular user
  1181. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1182. sess := x.Where("watch.user_id=?", userID).
  1183. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1184. if !private {
  1185. sess = sess.And("is_private=?", false)
  1186. }
  1187. repos := make([]*Repository, 0, 10)
  1188. err := sess.Find(&repos)
  1189. if err != nil {
  1190. return nil, err
  1191. }
  1192. return repos, nil
  1193. }