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

user.go 38 kB

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