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

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