You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 40 kB

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