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 36 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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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.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. return u.generateRandomAvatar(x)
  246. }
  247. func (u *User) generateRandomAvatar(e Engine) error {
  248. seed := u.Email
  249. if len(seed) == 0 {
  250. seed = u.Name
  251. }
  252. img, err := avatar.RandomImage([]byte(seed))
  253. if err != nil {
  254. return fmt.Errorf("RandomImage: %v", err)
  255. }
  256. // NOTICE for random avatar, it still uses id as avatar name, but custom avatar use md5
  257. // since random image is not a user's photo, there is no security for enumable
  258. u.Avatar = fmt.Sprintf("%d", u.ID)
  259. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  260. return fmt.Errorf("MkdirAll: %v", err)
  261. }
  262. fw, err := os.Create(u.CustomAvatarPath())
  263. if err != nil {
  264. return fmt.Errorf("Create: %v", err)
  265. }
  266. defer fw.Close()
  267. if _, err := e.Id(u.ID).Cols("avatar").Update(u); err != nil {
  268. return err
  269. }
  270. if err = png.Encode(fw, img); err != nil {
  271. return fmt.Errorf("Encode: %v", err)
  272. }
  273. log.Info("New random avatar created: %d", u.ID)
  274. return nil
  275. }
  276. // RelAvatarLink returns relative avatar link to the site domain,
  277. // which includes app sub-url as prefix. However, it is possible
  278. // to return full URL if user enables Gravatar-like service.
  279. func (u *User) RelAvatarLink() string {
  280. defaultImgURL := setting.AppSubURL + "/img/avatar_default.png"
  281. if u.ID == -1 {
  282. return defaultImgURL
  283. }
  284. switch {
  285. case u.UseCustomAvatar:
  286. if !com.IsFile(u.CustomAvatarPath()) {
  287. return defaultImgURL
  288. }
  289. return setting.AppSubURL + "/avatars/" + u.Avatar
  290. case setting.DisableGravatar, setting.OfflineMode:
  291. if !com.IsFile(u.CustomAvatarPath()) {
  292. if err := u.GenerateRandomAvatar(); err != nil {
  293. log.Error(3, "GenerateRandomAvatar: %v", err)
  294. }
  295. }
  296. return setting.AppSubURL + "/avatars/" + u.Avatar
  297. }
  298. return base.AvatarLink(u.AvatarEmail)
  299. }
  300. // AvatarLink returns user avatar absolute link.
  301. func (u *User) AvatarLink() string {
  302. link := u.RelAvatarLink()
  303. if link[0] == '/' && link[1] != '/' {
  304. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  305. }
  306. return link
  307. }
  308. // GetFollowers returns range of user's followers.
  309. func (u *User) GetFollowers(page int) ([]*User, error) {
  310. users := make([]*User, 0, ItemsPerPage)
  311. sess := x.
  312. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  313. Where("follow.follow_id=?", u.ID)
  314. if setting.UsePostgreSQL {
  315. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  316. } else {
  317. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  318. }
  319. return users, sess.Find(&users)
  320. }
  321. // IsFollowing returns true if user is following followID.
  322. func (u *User) IsFollowing(followID int64) bool {
  323. return IsFollowing(u.ID, followID)
  324. }
  325. // GetFollowing returns range of user's following.
  326. func (u *User) GetFollowing(page int) ([]*User, error) {
  327. users := make([]*User, 0, ItemsPerPage)
  328. sess := x.
  329. Limit(ItemsPerPage, (page-1)*ItemsPerPage).
  330. Where("follow.user_id=?", u.ID)
  331. if setting.UsePostgreSQL {
  332. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  333. } else {
  334. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  335. }
  336. return users, sess.Find(&users)
  337. }
  338. // NewGitSig generates and returns the signature of given user.
  339. func (u *User) NewGitSig() *git.Signature {
  340. return &git.Signature{
  341. Name: u.DisplayName(),
  342. Email: u.getEmail(),
  343. When: time.Now(),
  344. }
  345. }
  346. // EncodePasswd encodes password to safe format.
  347. func (u *User) EncodePasswd() {
  348. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  349. u.Passwd = fmt.Sprintf("%x", newPasswd)
  350. }
  351. // ValidatePassword checks if given password matches the one belongs to the user.
  352. func (u *User) ValidatePassword(passwd string) bool {
  353. newUser := &User{Passwd: passwd, Salt: u.Salt}
  354. newUser.EncodePasswd()
  355. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  356. }
  357. // IsPasswordSet checks if the password is set or left empty
  358. func (u *User) IsPasswordSet() bool {
  359. return !u.ValidatePassword("")
  360. }
  361. // UploadAvatar saves custom avatar for user.
  362. // FIXME: split uploads to different subdirs in case we have massive users.
  363. func (u *User) UploadAvatar(data []byte) error {
  364. img, _, err := image.Decode(bytes.NewReader(data))
  365. if err != nil {
  366. return fmt.Errorf("Decode: %v", err)
  367. }
  368. m := resize.Resize(avatar.AvatarSize, avatar.AvatarSize, img, resize.NearestNeighbor)
  369. sess := x.NewSession()
  370. defer sessionRelease(sess)
  371. if err = sess.Begin(); err != nil {
  372. return err
  373. }
  374. u.UseCustomAvatar = true
  375. u.Avatar = fmt.Sprintf("%x", md5.Sum(data))
  376. if err = updateUser(sess, u); err != nil {
  377. return fmt.Errorf("updateUser: %v", err)
  378. }
  379. if err := os.MkdirAll(setting.AvatarUploadPath, os.ModePerm); err != nil {
  380. return fmt.Errorf("Failed to create dir %s: %v", setting.AvatarUploadPath, err)
  381. }
  382. fw, err := os.Create(u.CustomAvatarPath())
  383. if err != nil {
  384. return fmt.Errorf("Create: %v", err)
  385. }
  386. defer fw.Close()
  387. if err = png.Encode(fw, m); err != nil {
  388. return fmt.Errorf("Encode: %v", err)
  389. }
  390. return sess.Commit()
  391. }
  392. // DeleteAvatar deletes the user's custom avatar.
  393. func (u *User) DeleteAvatar() error {
  394. log.Trace("DeleteAvatar[%d]: %s", u.ID, u.CustomAvatarPath())
  395. if len(u.Avatar) > 0 {
  396. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  397. return fmt.Errorf("Failed to remove %s: %v", u.CustomAvatarPath(), err)
  398. }
  399. }
  400. u.UseCustomAvatar = false
  401. u.Avatar = ""
  402. if _, err := x.Id(u.ID).Cols("avatar, use_custom_avatar").Update(u); err != nil {
  403. return fmt.Errorf("UpdateUser: %v", err)
  404. }
  405. return nil
  406. }
  407. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  408. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  409. has, err := HasAccess(u.ID, repo, AccessModeAdmin)
  410. if err != nil {
  411. log.Error(3, "HasAccess: %v", err)
  412. }
  413. return has
  414. }
  415. // IsWriterOfRepo returns true if user has write access to given repository.
  416. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  417. has, err := HasAccess(u.ID, repo, AccessModeWrite)
  418. if err != nil {
  419. log.Error(3, "HasAccess: %v", err)
  420. }
  421. return has
  422. }
  423. // IsOrganization returns true if user is actually a organization.
  424. func (u *User) IsOrganization() bool {
  425. return u.Type == UserTypeOrganization
  426. }
  427. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  428. func (u *User) IsUserOrgOwner(orgID int64) bool {
  429. return IsOrganizationOwner(orgID, u.ID)
  430. }
  431. // IsPublicMember returns true if user public his/her membership in given organization.
  432. func (u *User) IsPublicMember(orgID int64) bool {
  433. return IsPublicMembership(orgID, u.ID)
  434. }
  435. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  436. return e.
  437. Where("uid=?", u.ID).
  438. Count(new(OrgUser))
  439. }
  440. // GetOrganizationCount returns count of membership of organization of user.
  441. func (u *User) GetOrganizationCount() (int64, error) {
  442. return u.getOrganizationCount(x)
  443. }
  444. // GetRepositories returns repositories that user owns, including private repositories.
  445. func (u *User) GetRepositories(page, pageSize int) (err error) {
  446. u.Repos, err = GetUserRepositories(u.ID, true, page, pageSize, "")
  447. return err
  448. }
  449. // GetRepositoryIDs returns repositories IDs where user owned
  450. func (u *User) GetRepositoryIDs() ([]int64, error) {
  451. var ids []int64
  452. return ids, x.Table("repository").Cols("id").Where("owner_id = ?", u.ID).Find(&ids)
  453. }
  454. // GetOrgRepositoryIDs returns repositories IDs where user's team owned
  455. func (u *User) GetOrgRepositoryIDs() ([]int64, error) {
  456. var ids []int64
  457. return ids, x.Table("repository").
  458. Cols("repository.id").
  459. Join("INNER", "team_user", "repository.owner_id = team_user.org_id AND team_user.uid = ?", u.ID).
  460. GroupBy("repository.id").Find(&ids)
  461. }
  462. // GetAccessRepoIDs returns all repositories IDs where user's or user is a team member organizations
  463. func (u *User) GetAccessRepoIDs() ([]int64, error) {
  464. ids, err := u.GetRepositoryIDs()
  465. if err != nil {
  466. return nil, err
  467. }
  468. ids2, err := u.GetOrgRepositoryIDs()
  469. if err != nil {
  470. return nil, err
  471. }
  472. return append(ids, ids2...), nil
  473. }
  474. // GetMirrorRepositories returns mirror repositories that user owns, including private repositories.
  475. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  476. return GetUserMirrorRepositories(u.ID)
  477. }
  478. // GetOwnedOrganizations returns all organizations that user owns.
  479. func (u *User) GetOwnedOrganizations() (err error) {
  480. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  481. return err
  482. }
  483. // GetOrganizations returns all organizations that user belongs to.
  484. func (u *User) GetOrganizations(all bool) error {
  485. ous, err := GetOrgUsersByUserID(u.ID, all)
  486. if err != nil {
  487. return err
  488. }
  489. u.Orgs = make([]*User, len(ous))
  490. for i, ou := range ous {
  491. u.Orgs[i], err = GetUserByID(ou.OrgID)
  492. if err != nil {
  493. return err
  494. }
  495. }
  496. return nil
  497. }
  498. // DisplayName returns full name if it's not empty,
  499. // returns username otherwise.
  500. func (u *User) DisplayName() string {
  501. if len(u.FullName) > 0 {
  502. return u.FullName
  503. }
  504. return u.Name
  505. }
  506. // ShortName ellipses username to length
  507. func (u *User) ShortName(length int) string {
  508. return base.EllipsisString(u.Name, length)
  509. }
  510. // IsMailable checks if a user is eligible
  511. // to receive emails.
  512. func (u *User) IsMailable() bool {
  513. return u.IsActive
  514. }
  515. // IsUserExist checks if given user name exist,
  516. // the user name should be noncased unique.
  517. // If uid is presented, then check will rule out that one,
  518. // it is used when update a user name in settings page.
  519. func IsUserExist(uid int64, name string) (bool, error) {
  520. if len(name) == 0 {
  521. return false, nil
  522. }
  523. return x.
  524. Where("id!=?", uid).
  525. Get(&User{LowerName: strings.ToLower(name)})
  526. }
  527. // GetUserSalt returns a random user salt token.
  528. func GetUserSalt() (string, error) {
  529. return base.GetRandomString(10)
  530. }
  531. // NewGhostUser creates and returns a fake user for someone has deleted his/her account.
  532. func NewGhostUser() *User {
  533. return &User{
  534. ID: -1,
  535. Name: "Ghost",
  536. LowerName: "ghost",
  537. }
  538. }
  539. var (
  540. reservedUsernames = []string{"assets", "css", "explore", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  541. reservedUserPatterns = []string{"*.keys"}
  542. )
  543. // isUsableName checks if name is reserved or pattern of name is not allowed
  544. // based on given reserved names and patterns.
  545. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  546. func isUsableName(names, patterns []string, name string) error {
  547. name = strings.TrimSpace(strings.ToLower(name))
  548. if utf8.RuneCountInString(name) == 0 {
  549. return ErrNameEmpty
  550. }
  551. for i := range names {
  552. if name == names[i] {
  553. return ErrNameReserved{name}
  554. }
  555. }
  556. for _, pat := range patterns {
  557. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  558. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  559. return ErrNamePatternNotAllowed{pat}
  560. }
  561. }
  562. return nil
  563. }
  564. // IsUsableUsername returns an error when a username is reserved
  565. func IsUsableUsername(name string) error {
  566. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  567. }
  568. // CreateUser creates record of a new user.
  569. func CreateUser(u *User) (err error) {
  570. if err = IsUsableUsername(u.Name); err != nil {
  571. return err
  572. }
  573. isExist, err := IsUserExist(0, u.Name)
  574. if err != nil {
  575. return err
  576. } else if isExist {
  577. return ErrUserAlreadyExist{u.Name}
  578. }
  579. u.Email = strings.ToLower(u.Email)
  580. has, err := x.
  581. Where("email=?", u.Email).
  582. Get(new(User))
  583. if err != nil {
  584. return err
  585. } else if has {
  586. return ErrEmailAlreadyUsed{u.Email}
  587. }
  588. isExist, err = IsEmailUsed(u.Email)
  589. if err != nil {
  590. return err
  591. } else if isExist {
  592. return ErrEmailAlreadyUsed{u.Email}
  593. }
  594. u.KeepEmailPrivate = setting.Service.DefaultKeepEmailPrivate
  595. u.LowerName = strings.ToLower(u.Name)
  596. u.AvatarEmail = u.Email
  597. u.Avatar = base.HashEmail(u.AvatarEmail)
  598. if u.Rands, err = GetUserSalt(); err != nil {
  599. return err
  600. }
  601. if u.Salt, err = GetUserSalt(); err != nil {
  602. return err
  603. }
  604. u.EncodePasswd()
  605. u.AllowCreateOrganization = true
  606. u.MaxRepoCreation = -1
  607. sess := x.NewSession()
  608. defer sessionRelease(sess)
  609. if err = sess.Begin(); err != nil {
  610. return err
  611. }
  612. if _, err = sess.Insert(u); err != nil {
  613. return err
  614. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  615. return err
  616. }
  617. return sess.Commit()
  618. }
  619. func countUsers(e Engine) int64 {
  620. count, _ := e.
  621. Where("type=0").
  622. Count(new(User))
  623. return count
  624. }
  625. // CountUsers returns number of users.
  626. func CountUsers() int64 {
  627. return countUsers(x)
  628. }
  629. // Users returns number of users in given page.
  630. func Users(opts *SearchUserOptions) ([]*User, error) {
  631. if len(opts.OrderBy) == 0 {
  632. opts.OrderBy = "name ASC"
  633. }
  634. users := make([]*User, 0, opts.PageSize)
  635. sess := x.
  636. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).
  637. Where("type=0")
  638. return users, sess.
  639. OrderBy(opts.OrderBy).
  640. Find(&users)
  641. }
  642. // get user by verify code
  643. func getVerifyUser(code string) (user *User) {
  644. if len(code) <= base.TimeLimitCodeLength {
  645. return nil
  646. }
  647. // use tail hex username query user
  648. hexStr := code[base.TimeLimitCodeLength:]
  649. if b, err := hex.DecodeString(hexStr); err == nil {
  650. if user, err = GetUserByName(string(b)); user != nil {
  651. return user
  652. }
  653. log.Error(4, "user.getVerifyUser: %v", err)
  654. }
  655. return nil
  656. }
  657. // VerifyUserActiveCode verifies active code when active account
  658. func VerifyUserActiveCode(code string) (user *User) {
  659. minutes := setting.Service.ActiveCodeLives
  660. if user = getVerifyUser(code); user != nil {
  661. // time limit code
  662. prefix := code[:base.TimeLimitCodeLength]
  663. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  664. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  665. return user
  666. }
  667. }
  668. return nil
  669. }
  670. // VerifyActiveEmailCode verifies active email code when active account
  671. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  672. minutes := setting.Service.ActiveCodeLives
  673. if user := getVerifyUser(code); user != nil {
  674. // time limit code
  675. prefix := code[:base.TimeLimitCodeLength]
  676. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  677. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  678. emailAddress := &EmailAddress{Email: email}
  679. if has, _ := x.Get(emailAddress); has {
  680. return emailAddress
  681. }
  682. }
  683. }
  684. return nil
  685. }
  686. // ChangeUserName changes all corresponding setting from old user name to new one.
  687. func ChangeUserName(u *User, newUserName string) (err error) {
  688. if err = IsUsableUsername(newUserName); err != nil {
  689. return err
  690. }
  691. isExist, err := IsUserExist(0, newUserName)
  692. if err != nil {
  693. return err
  694. } else if isExist {
  695. return ErrUserAlreadyExist{newUserName}
  696. }
  697. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  698. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  699. }
  700. // Delete all local copies of repository wiki that user owns.
  701. if err = x.
  702. Where("owner_id=?", u.ID).
  703. Iterate(new(Repository), func(idx int, bean interface{}) error {
  704. repo := bean.(*Repository)
  705. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  706. return nil
  707. }); err != nil {
  708. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  709. }
  710. return os.Rename(UserPath(u.Name), UserPath(newUserName))
  711. }
  712. // checkDupEmail checks whether there are the same email with the user
  713. func checkDupEmail(e Engine, u *User) error {
  714. u.Email = strings.ToLower(u.Email)
  715. has, err := e.
  716. Where("id!=?", u.ID).
  717. And("type=?", u.Type).
  718. And("email=?", u.Email).
  719. Get(new(User))
  720. if err != nil {
  721. return err
  722. } else if has {
  723. return ErrEmailAlreadyUsed{u.Email}
  724. }
  725. return nil
  726. }
  727. func updateUser(e Engine, u *User) error {
  728. // Organization does not need email
  729. u.Email = strings.ToLower(u.Email)
  730. if !u.IsOrganization() {
  731. if len(u.AvatarEmail) == 0 {
  732. u.AvatarEmail = u.Email
  733. }
  734. u.Avatar = base.HashEmail(u.AvatarEmail)
  735. }
  736. u.LowerName = strings.ToLower(u.Name)
  737. u.Location = base.TruncateString(u.Location, 255)
  738. u.Website = base.TruncateString(u.Website, 255)
  739. u.Description = base.TruncateString(u.Description, 255)
  740. u.FullName = markdown.Sanitize(u.FullName)
  741. _, err := e.Id(u.ID).AllCols().Update(u)
  742. return err
  743. }
  744. // UpdateUser updates user's information.
  745. func UpdateUser(u *User) error {
  746. return updateUser(x, u)
  747. }
  748. // UpdateUserSetting updates user's settings.
  749. func UpdateUserSetting(u *User) error {
  750. if !u.IsOrganization() {
  751. if err := checkDupEmail(x, u); err != nil {
  752. return err
  753. }
  754. }
  755. return updateUser(x, u)
  756. }
  757. // deleteBeans deletes all given beans, beans should contain delete conditions.
  758. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  759. for i := range beans {
  760. if _, err = e.Delete(beans[i]); err != nil {
  761. return err
  762. }
  763. }
  764. return nil
  765. }
  766. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  767. func deleteUser(e *xorm.Session, u *User) error {
  768. // Note: A user owns any repository or belongs to any organization
  769. // cannot perform delete operation.
  770. // Check ownership of repository.
  771. count, err := getRepositoryCount(e, u)
  772. if err != nil {
  773. return fmt.Errorf("GetRepositoryCount: %v", err)
  774. } else if count > 0 {
  775. return ErrUserOwnRepos{UID: u.ID}
  776. }
  777. // Check membership of organization.
  778. count, err = u.getOrganizationCount(e)
  779. if err != nil {
  780. return fmt.Errorf("GetOrganizationCount: %v", err)
  781. } else if count > 0 {
  782. return ErrUserHasOrgs{UID: u.ID}
  783. }
  784. // ***** START: Watch *****
  785. watches := make([]*Watch, 0, 10)
  786. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  787. return fmt.Errorf("get all watches: %v", err)
  788. }
  789. for i := range watches {
  790. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  791. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  792. }
  793. }
  794. // ***** END: Watch *****
  795. // ***** START: Star *****
  796. stars := make([]*Star, 0, 10)
  797. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  798. return fmt.Errorf("get all stars: %v", err)
  799. }
  800. for i := range stars {
  801. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  802. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  803. }
  804. }
  805. // ***** END: Star *****
  806. // ***** START: Follow *****
  807. followers := make([]*Follow, 0, 10)
  808. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  809. return fmt.Errorf("get all followers: %v", err)
  810. }
  811. for i := range followers {
  812. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  813. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  814. }
  815. }
  816. // ***** END: Follow *****
  817. if err = deleteBeans(e,
  818. &AccessToken{UID: u.ID},
  819. &Collaboration{UserID: u.ID},
  820. &Access{UserID: u.ID},
  821. &Watch{UserID: u.ID},
  822. &Star{UID: u.ID},
  823. &Follow{FollowID: u.ID},
  824. &Action{UserID: u.ID},
  825. &IssueUser{UID: u.ID},
  826. &EmailAddress{UID: u.ID},
  827. &UserOpenID{UID: u.ID},
  828. ); err != nil {
  829. return fmt.Errorf("deleteBeans: %v", err)
  830. }
  831. // ***** START: PublicKey *****
  832. keys := make([]*PublicKey, 0, 10)
  833. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  834. return fmt.Errorf("get all public keys: %v", err)
  835. }
  836. keyIDs := make([]int64, len(keys))
  837. for i := range keys {
  838. keyIDs[i] = keys[i].ID
  839. }
  840. if err = deletePublicKeys(e, keyIDs...); err != nil {
  841. return fmt.Errorf("deletePublicKeys: %v", err)
  842. }
  843. // ***** END: PublicKey *****
  844. // Clear assignee.
  845. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  846. return fmt.Errorf("clear assignee: %v", err)
  847. }
  848. // ***** START: ExternalLoginUser *****
  849. if err = removeAllAccountLinks(e, u); err != nil {
  850. return fmt.Errorf("ExternalLoginUser: %v", err)
  851. }
  852. // ***** END: ExternalLoginUser *****
  853. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  854. return fmt.Errorf("Delete: %v", err)
  855. }
  856. // FIXME: system notice
  857. // Note: There are something just cannot be roll back,
  858. // so just keep error logs of those operations.
  859. path := UserPath(u.Name)
  860. if err := os.RemoveAll(path); err != nil {
  861. return fmt.Errorf("Failed to RemoveAll %s: %v", path, err)
  862. }
  863. if len(u.Avatar) > 0 {
  864. avatarPath := u.CustomAvatarPath()
  865. if com.IsExist(avatarPath) {
  866. if err := os.Remove(avatarPath); err != nil {
  867. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  868. }
  869. }
  870. }
  871. return nil
  872. }
  873. // DeleteUser completely and permanently deletes everything of a user,
  874. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  875. func DeleteUser(u *User) (err error) {
  876. sess := x.NewSession()
  877. defer sessionRelease(sess)
  878. if err = sess.Begin(); err != nil {
  879. return err
  880. }
  881. if err = deleteUser(sess, u); err != nil {
  882. // Note: don't wrapper error here.
  883. return err
  884. }
  885. if err = sess.Commit(); err != nil {
  886. return err
  887. }
  888. return RewriteAllPublicKeys()
  889. }
  890. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  891. func DeleteInactivateUsers() (err error) {
  892. users := make([]*User, 0, 10)
  893. if err = x.
  894. Where("is_active = ?", false).
  895. Find(&users); err != nil {
  896. return fmt.Errorf("get all inactive users: %v", err)
  897. }
  898. // FIXME: should only update authorized_keys file once after all deletions.
  899. for _, u := range users {
  900. if err = DeleteUser(u); err != nil {
  901. // Ignore users that were set inactive by admin.
  902. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  903. continue
  904. }
  905. return err
  906. }
  907. }
  908. _, err = x.
  909. Where("is_activated = ?", false).
  910. Delete(new(EmailAddress))
  911. return err
  912. }
  913. // UserPath returns the path absolute path of user repositories.
  914. func UserPath(userName string) string {
  915. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  916. }
  917. // GetUserByKeyID get user information by user's public key id
  918. func GetUserByKeyID(keyID int64) (*User, error) {
  919. var user User
  920. has, err := x.Join("INNER", "public_key", "`public_key`.owner_id = `user`.id").
  921. Where("`public_key`.id=?", keyID).
  922. Get(&user)
  923. if err != nil {
  924. return nil, err
  925. }
  926. if !has {
  927. return nil, ErrUserNotExist{0, "", keyID}
  928. }
  929. return &user, nil
  930. }
  931. func getUserByID(e Engine, id int64) (*User, error) {
  932. u := new(User)
  933. has, err := e.Id(id).Get(u)
  934. if err != nil {
  935. return nil, err
  936. } else if !has {
  937. return nil, ErrUserNotExist{id, "", 0}
  938. }
  939. return u, nil
  940. }
  941. // GetUserByID returns the user object by given ID if exists.
  942. func GetUserByID(id int64) (*User, error) {
  943. return getUserByID(x, id)
  944. }
  945. // GetAssigneeByID returns the user with write access of repository by given ID.
  946. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  947. has, err := HasAccess(userID, repo, AccessModeWrite)
  948. if err != nil {
  949. return nil, err
  950. } else if !has {
  951. return nil, ErrUserNotExist{userID, "", 0}
  952. }
  953. return GetUserByID(userID)
  954. }
  955. // GetUserByName returns user by given name.
  956. func GetUserByName(name string) (*User, error) {
  957. if len(name) == 0 {
  958. return nil, ErrUserNotExist{0, name, 0}
  959. }
  960. u := &User{LowerName: strings.ToLower(name)}
  961. has, err := x.Get(u)
  962. if err != nil {
  963. return nil, err
  964. } else if !has {
  965. return nil, ErrUserNotExist{0, name, 0}
  966. }
  967. return u, nil
  968. }
  969. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  970. func GetUserEmailsByNames(names []string) []string {
  971. mails := make([]string, 0, len(names))
  972. for _, name := range names {
  973. u, err := GetUserByName(name)
  974. if err != nil {
  975. continue
  976. }
  977. if u.IsMailable() {
  978. mails = append(mails, u.Email)
  979. }
  980. }
  981. return mails
  982. }
  983. // GetUsersByIDs returns all resolved users from a list of Ids.
  984. func GetUsersByIDs(ids []int64) ([]*User, error) {
  985. ous := make([]*User, 0, len(ids))
  986. if len(ids) == 0 {
  987. return ous, nil
  988. }
  989. err := x.In("id", ids).
  990. Asc("name").
  991. Find(&ous)
  992. return ous, err
  993. }
  994. // GetUserIDsByNames returns a slice of ids corresponds to names.
  995. func GetUserIDsByNames(names []string) []int64 {
  996. ids := make([]int64, 0, len(names))
  997. for _, name := range names {
  998. u, err := GetUserByName(name)
  999. if err != nil {
  1000. continue
  1001. }
  1002. ids = append(ids, u.ID)
  1003. }
  1004. return ids
  1005. }
  1006. // UserCommit represents a commit with validation of user.
  1007. type UserCommit struct {
  1008. User *User
  1009. *git.Commit
  1010. }
  1011. // ValidateCommitWithEmail check if author's e-mail of commit is corresponding to a user.
  1012. func ValidateCommitWithEmail(c *git.Commit) *User {
  1013. u, err := GetUserByEmail(c.Author.Email)
  1014. if err != nil {
  1015. return nil
  1016. }
  1017. return u
  1018. }
  1019. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  1020. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  1021. var (
  1022. u *User
  1023. emails = map[string]*User{}
  1024. newCommits = list.New()
  1025. e = oldCommits.Front()
  1026. )
  1027. for e != nil {
  1028. c := e.Value.(*git.Commit)
  1029. if v, ok := emails[c.Author.Email]; !ok {
  1030. u, _ = GetUserByEmail(c.Author.Email)
  1031. emails[c.Author.Email] = u
  1032. } else {
  1033. u = v
  1034. }
  1035. newCommits.PushBack(UserCommit{
  1036. User: u,
  1037. Commit: c,
  1038. })
  1039. e = e.Next()
  1040. }
  1041. return newCommits
  1042. }
  1043. // GetUserByEmail returns the user object by given e-mail if exists.
  1044. func GetUserByEmail(email string) (*User, error) {
  1045. if len(email) == 0 {
  1046. return nil, ErrUserNotExist{0, email, 0}
  1047. }
  1048. email = strings.ToLower(email)
  1049. // First try to find the user by primary email
  1050. user := &User{Email: email}
  1051. has, err := x.Get(user)
  1052. if err != nil {
  1053. return nil, err
  1054. }
  1055. if has {
  1056. return user, nil
  1057. }
  1058. // Otherwise, check in alternative list for activated email addresses
  1059. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  1060. has, err = x.Get(emailAddress)
  1061. if err != nil {
  1062. return nil, err
  1063. }
  1064. if has {
  1065. return GetUserByID(emailAddress.UID)
  1066. }
  1067. return nil, ErrUserNotExist{0, email, 0}
  1068. }
  1069. // GetUser checks if a user already exists
  1070. func GetUser(user *User) (bool, error) {
  1071. return x.Get(user)
  1072. }
  1073. // SearchUserOptions contains the options for searching
  1074. type SearchUserOptions struct {
  1075. Keyword string
  1076. Type UserType
  1077. OrderBy string
  1078. Page int
  1079. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  1080. }
  1081. // SearchUserByName takes keyword and part of user name to search,
  1082. // it returns results in given range and number of total results.
  1083. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  1084. if len(opts.Keyword) == 0 {
  1085. return users, 0, nil
  1086. }
  1087. opts.Keyword = strings.ToLower(opts.Keyword)
  1088. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  1089. opts.PageSize = setting.UI.ExplorePagingNum
  1090. }
  1091. if opts.Page <= 0 {
  1092. opts.Page = 1
  1093. }
  1094. users = make([]*User, 0, opts.PageSize)
  1095. // Append conditions
  1096. cond := builder.And(
  1097. builder.Eq{"type": opts.Type},
  1098. builder.Or(
  1099. builder.Like{"lower_name", opts.Keyword},
  1100. builder.Like{"LOWER(full_name)", opts.Keyword},
  1101. ),
  1102. )
  1103. count, err := x.Where(cond).Count(new(User))
  1104. if err != nil {
  1105. return nil, 0, fmt.Errorf("Count: %v", err)
  1106. }
  1107. sess := x.Where(cond).
  1108. Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  1109. if len(opts.OrderBy) > 0 {
  1110. sess.OrderBy(opts.OrderBy)
  1111. }
  1112. return users, count, sess.Find(&users)
  1113. }
  1114. // GetStarredRepos returns the repos starred by a particular user
  1115. func GetStarredRepos(userID int64, private bool) ([]*Repository, error) {
  1116. sess := x.Where("star.uid=?", userID).
  1117. Join("LEFT", "star", "`repository`.id=`star`.repo_id")
  1118. if !private {
  1119. sess = sess.And("is_private=?", false)
  1120. }
  1121. repos := make([]*Repository, 0, 10)
  1122. err := sess.Find(&repos)
  1123. if err != nil {
  1124. return nil, err
  1125. }
  1126. return repos, nil
  1127. }
  1128. // GetWatchedRepos returns the repos watched by a particular user
  1129. func GetWatchedRepos(userID int64, private bool) ([]*Repository, error) {
  1130. sess := x.Where("watch.user_id=?", userID).
  1131. Join("LEFT", "watch", "`repository`.id=`watch`.repo_id")
  1132. if !private {
  1133. sess = sess.And("is_private=?", false)
  1134. }
  1135. repos := make([]*Repository, 0, 10)
  1136. err := sess.Find(&repos)
  1137. if err != nil {
  1138. return nil, err
  1139. }
  1140. return repos, nil
  1141. }